What is Python?¶
Python is a high-level, object-oriented programming language developed by Guido van Rossum. This means that Python is based around data and is easily understood by humans.
What is Python used for?¶
Python is commonly used for developing websites and software, task automation, data analysis, and data visualization. Since it’s relatively easy to learn, Python has been adopted by many non-programmers, such as accountants and scientists, for a variety of everyday tasks, like organizing finances.
What can you do with python? Some things include:¶
Data analysis and machine learning
Web development
Automation or scripting
Software testing and prototyping
Data analysis and machine learning¶
Python has become a staple in data science, allowing data analysts and other professionals to use the language to conduct complex statistical calculations, create data visualizations, build machine learning algorithms, manipulate and analyze data, and complete other data-related tasks.
Python can build a wide range of different data visualizations, like line and bar graphs, pie charts, histograms, and 3D plots. Python also has a number of libraries that enable coders to write programs for data analysis and machine learning more quickly and efficiently, like TensorFlow and Keras.
Nutshell Tips:
Case – Sensitive Language
Counting or Indexing starts from 0
Read the Error from below
Did you know? The name Python comes from Monty Python. When Guido van Rossum was creating Python, he was also reading the scripts from BBCâs Monty Pythonâs Flying Circus. He thought the name Python was appropriately short and slightly mysterious.
In last, Python is super easy to learn but hard to master !!¶
print("Hello")
Hello
print("Hello, World")
Hello, World
print("Basic Syntax of Python")
# This is a comment
a=7
print(a)
b=5
print(b)
# Simple Maths
print(a+b)
c=a+b
print(c)
# Multiply
a=1.5
a*2
a+1
# Lets check the type of variable
type(a)
type(b)
d=2.5
type(d)
# Adding an Integer & Float gives float
a=7
b=5.5
a+b
type(a+b)
# a=b is b=a ?
# Multiplying an String with Integer is allowed in python
Name ='DataMantra'
Name*2
# Addition an String with Integer is allowed in python ?
# Let's check
Name ='DataMantra'
Name + 2
Name ='DataMantra'
type(Name)
# Superuseful function - Help with all In-built functions
help()
# Seek help
help(str)
help(int)
# Declaring the Int var
Number = 100
# Display
print( Number)
# Declaring the String var ( Strings always needs to be in " ")
Name = 'DataMantra'
# Display
print(Name)
# 1st Trick
print(Name,Number)
'single quotes'
"double quotes"
" wrap lot's of other quotes"
Age = 12
name = 'Tarun'
print('My Age is: {one}, and my name is: {two}'.format(one=Age,two=name ))
print(‘My Age is: {}, and my name is: {}’.format(Age,name))
price = 10
print(price)
# Python Interprets the code line by line
price = 10
price = 20
print(price)
# Working with Float & Boolean Data Types
Rating = 4.9
is_published = True
print(Rating)
print(is_published)
Boolean Datatypes¶
The boolean is a data type that has only two values (Yes/No) or (True/False) or (0/1)
True
False
Example of checking bool() on strings:¶
Only an empty string is False, the rest of the strings are considered to be True. Even the string with space is True, as space is also a character in Python.
bool(" ")
bool("")
bool('PythonGeeks')
# Boolean with Lists, tuples, and dictionaries:
These will be boolean False if they do not have **any element or they are empty else, these are True.**
bool(())
bool((1,2))
bool([])
bool(['t'])
bool({})
bool({4:'c'})
# Boolean with Membership operators
The operators **’in’and ‘not in’** are the two membership operators.
The âinâ gives **True** if the element is in the sequence, else returns **False.** The operator ânot inâ does the opposite.
'e' in 'PythonGeeks'
5 not in [1,3,4,5.0,8]
6.7 in (1,5,'t')
Boolean with Comparison Operators¶
In Python, we have six comparison operators and these are ==,!=,<,<=,>,>=. These give True if the values satisfy the condition of the first operand is
a. equal to the second one for ==
b. not equal the second one for !=
c. less than the second one for <
d. less than or equal to the second one for <=
e. greater than the second one for >
g. f. greater than or equal to the second operand for >=.
1 > 2
False
4.5 == 7
False
1 < 2
True
1 >= 1
True
1 <= 4
True
1 == 1
True
'hi' == 'bye'
False
Logical Operators¶
The operators and, or, are the logical operators in Python.
AND – The âandâ gives True if both the operands are True else returns False.
OR – The âorâ gives True if at least one of the operands is True else returns False.
not – It is a unary operator that is used to negate the expression after succeeding the operator. According to this, every True expression becomes False, and vice versa.
Consider the statement:¶
Sunita will not go to school.
If the above statement is true, the statement âSunita will go to schoolâ would be false.
Thus, not interchanges True and False values.
(1 > 2) and (2 < 3)
False
(1 > 2) or (2 < 3)
True
(1 == 2) or (2 == 3) or (4 == 4)
True
x = True
y = False
print(not x)
print(not y)
False True
For more:-¶
Variable¶
Python Variable is containers that store values.
A variable is created the moment we first assign a value to it.
A Python variable is a name given to a memory location or we can say a reference or pointer to an object. Once an object is assigned to a variable, we can refer to the object by that name.
It is the basic unit of storage in a program.
# Assigning a variable n whose value is 300
n = 300
print(n)
This assignment creates an integer object with the value 300 and assigns the variable n** to point to that object.
Now consider the following statement:
m = n
What happens when it is executed? Python does not create another object. It simply creates a new symbolic name or reference, m, which points to the same object that n points to.
m = n
Next, suppose we do this:
m = 400
Now Python creates a new integer object with the value 400, and m becomes a reference to it.
Lastly, suppose this statement is executed next:
n = “foo”
Now Python creates a string object with the value “foo” and makes n reference that.
There is no longer any reference to the integer object 300. It is orphaned, and there is no way to access it.An objectâs life begins when it is created, at which time at least one reference to it is created.
An object stays alive, as it were, so long as there is at least one reference to it.
When the number of references to an object drops to zero, it is no longer accessible. At that point, its lifetime is over. Python will eventually notice that it is inaccessible and reclaim the allocated memory so it can be used for something else. In computer lingo, this process is referred to as garbage collection.
Rules for Python variables¶
- A Python variable name must start with a letter or the underscore character.
**OR**
Officially, variable names in Python can be any length and can consist of uppercase and lowercase letters (A-Z, a-z), digits (0-9), and the underscore character (_). An additional restriction is that, although a variable name can contain digits, the first character of a variable name cannot be a digit.
- A Python variable name cannot start with a number.
- Variable in Python names are case-sensitive (name, Name, and NAME are three different variables).
Object Identity¶
In Python, every object that is created is given a number that uniquely identifies it. It is guaranteed that no two objects will have the same identifier during any period in which their lifetimes overlap.
Once an objectâs reference count drops to zero and it is garbage collected, as happened to the 300 object above, then its identifying number becomes available and may be used again.
The built-in Python function id() returns an objectâs integer identifier.
Using the id() function, we can verify that two variables indeed point to the same object:
n = 300
print(id(n))
m = n
print(id(m))
m = 400
print(id(m))
hex(id(n))
bin(id(n))
Advanced¶
Deep Dive: Caching Small Integer Values¶
From what you now know about variable assignment and object references in Python, the following probably wonât surprise you:
m = 300
n = 300
id(m)
60062304
id(n)
60062896
With the statement m = 300, Python creates an integer object with the value 300 and sets m as a reference to it. n is then similarly assigned to an integer object with value 300âbut not the same object. Thus, they have different identities, which you can verify from the values returned by id().
m = 30
n = 30
id(m)
1405569120
id(n)
1405569120
Here, m and n are separately assigned to integer objects having value 30. But in this case, id(m) and id(n) are identical!n
For purposes of optimization, the interpreter creates objects for the integers in the range [-5, 256] at startup, and then reuses them during program execution. Thus, when you assign separate variables to an integer value in this range, they will actually reference the same object.
Great Job !!¶
User Inputs¶
The input() function takes input from the user and returns it.
First_Name = input("What is your First Name ")
print(First_Name)
Family_Name = input("What is your Family Name ")
print(Family_Name)
print (First_Name + " " + Family_Name )
Name = input("What is your Name ")
print("Hi" + " " + First_Name )
## STRING FUNCTIONS
## Upper - Converts the String to Capital Letters.
Name = 'DataMantra'
print(Name.upper())
## Lower - Converts the String to small Letters.
Name = 'DataMantra'
print(Name.lower())
OR¶
Name = 'DataMantra'
print(Name.casefold())
Name = 'DataMantra'
print(Name.title())
OR¶
Name = 'DataMantra'
print(Name.capitalize())
# Lets find the age & Solve the Error
birth_year = input("What is your Birth year")
Age = 2023- (birth_year)
print((Age))
type(birth_year)
#type(Age)
# Using int function will do this
birth_year = input("What is your Birth year")
Age = 2023- int(birth_year)
print((Age))
# Check the Length of String - Similiar Use case in SQL,Tableau & Power BI
Name ='Python'
len(Name)
# Single Inverted Comma's or Double ?
course = 'Python's Course for Beginners'
# Recommended to use double Inverted Commas
course = "Python's Course for Beginners"
print(course)
# Tip
Email = '''
Hi Tarun
Here is our first email to you
Thanks
Contact Team - DataMantra
'''
print(Email)
if else & elif Conditions¶
If the if condition around the block of the statements is TRUE, then it will be executed; otherwise, the else block of the statements will be executed.
Below is the if-else syntax in python.¶
if expression
Statement
else
Statement
Quick Note: Indentation, the whitespace at the beginning of a line, plays an important role while working with if else in python programming. It is often used to define the scope of the program, while in other programming languages, we often make use of curly brackets to serve the purpose. It is important to take proper care of the indentation while coding with if – elif – else; otherwise, you will encounter IndentationError while executing the code.
Python relies on indentation (whitespace at the beginning of a line) to define scope in the code.
if 1 < 2:
print('Yep!')
Yep!
Else¶
The else keyword catches anything which isn’t caught by the preceding conditions.
if 1 < 2:
print('first')
else:
print('last')
first
if 1 > 2:
print('first')
else:
print('last')
last
a = 33
b = 200
if b > a:
print("b is greater than a")
# Python relies on indentation (whitespace at the beginning of a line) to define scope in the code.
a = 33
b = 200
if b > a:
print("b is greater than a") # you will get an error
Elif¶
The elif keyword is Python’s way of saying “if the previous conditions were not true, then try this condition”.
if 1 == 2:
print('first')
elif 3 == 3:
print('middle')
else:
print('Last')
middle
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
## The and keyword is a logical operator, and is used to combine conditional statements:
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
b is greater than a
# The or keyword is a logical operator, and is used to combine conditional statements.
a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")
# The not keyword is a logical operator, and is used to reverse the result of the conditional statement.
a = 33
b = 200
if not a > b:
print("a is NOT greater than b")
a is NOT greater than b
# if statements cannot be empty,but for some reason you have an if statement with no content, put in the pass statement to
# avoid getting an error.
a = 33
b = 200
if b > a:
pass
# Python program to illustrate short hand if
i = 10
if i < 15: print("i is less than 15")
Great Job !!¶
Congrats, you have completed the Basics.