Python Basics
Python Basics
Python Basics
Python Keywords
Keywords are the reserved words in python
We can't use a keyword as variable name, function name or any other identifier
import keyword
print(keyword.kwlist)
print("Total number of keywords ", len(keyword.kwlist))
Identifiers
Identifier is the name given to entities like class, functions, variables etc. in Python. It helps
differentiating one entity from another.
2. An identifier cannot start with a digit. 1variable is invalid, but variable1 is perfectly fine.
In [2]: global = 1
Input In [2]
global = 1
^
SyntaxError: invalid syntax
Input In [4]
21_abc12 =10
^
SyntaxError: invalid decimal literal
In [5]: a=10;
b=20;
print("the value of a is {} and b is {} ".format(a,b))
In [6]: a@ = 10
Input In [6]
a@ = 10
^
SyntaxError: invalid syntax
Comments are lines that exist in computer programs that are ignored by compilers and
interpreters.
Including comments in programs makes code more readable for humans as it provides
some information or explanation about what each part of a program is doing.
In general, it is a good idea to write comments while you are writing or updating a program
as it is easy to forget your thought process later on, and comments written later may be less
useful in the long term.
Python Comments
In Python, we use the hash (#) symbol to start writing a comment.
Hello, world 2
Another way of doing this is to use triple quotes, either ''' or """.
DocString in python
Docstring is short for documentation string.
It is a string that occurs as the first statement in a module, function, class, or method
definition.
print (double(10))
20
Python Indentation
1. Most of the programming languages like C, C++, Java use braces { } to define a block of
code. Python uses indentation.
2. A code block (body of a function, loop etc.) starts with indentation and ends with the
first unindented line. The amount of indentation is up to you, but it must be consistent
throughout that block.
3. Generally four whitespaces are used for indentation and is preferred over tabs.
0
1
2
3
4
5
6
7
8
9
Indentation can be ignored in line continuation. But it's a good idea to always indent. It
makes the code more readable.
In [7]: if True:
print ("Machine Learning")
c = "AAIC"
Machine Learning
Machine Learning
Python Statement
Instructions that a Python interpreter can execute are called statements.
Examples:
Multi-Line Statement
In Python, end of a statement is marked by a newline character. But we can make a
statement extend over multiple lines with the line continuation character ().
In [10]: a = 1 + 2 + 3 + \
4 + 5 + 6 + \
7 + 8
36
36
Variables
A variable is a location in memory used to store some data (value).
They are given unique names to differentiate between different memory locations. The rules
for writing a variable name is same as the rules for writing identifiers in Python.
We don't need to declare a variable before using it. In Python, we simply assign a value to a
variable and it will exist. We don't even have to declare the type of the variable. This is
handled internally according to the type of value we assign to the variable.
Variable Assignments
In [1]: #We use the assignment operator (=) to assign values to a variable
a = 10
b = 5.5
c = "ML"
Multiple Assignments
In [2]: a, b, c = 10, 5.5, "ML"
Storage Locations
In [4]: x = 3
1910655641968
In [5]: y = 3
1910655641968
Observation:
In [6]: y = 2
print(id(y)) #print address of variable y
1910655641936
Data Types
localhost:8888/nbconvert/html/Desktop/DATA WRANGLING/PYTHON/1.2 python for data science introduction/1_4.ipynb?download=false 1/5
1/23/23, 11:51 AM 1_4
Every value in Python has a datatype. Since everything is an object in Python programming,
data types are actually classes and variables are instance (object) of these classes.
Numbers
Integers, floating point numbers and complex numbers falls under Python numbers
category. They are defined as int, float and complex class in Python.
We can use the type() function to know which class a variable or a value belongs to and the
isinstance() function to check if an object belongs to a particular class.
Boolean
Boolean represents the truth values False and True
<class 'bool'>
Python Strings
String is sequence of Unicode characters.
In [12]: print(s[0])
#last char s[len(s)-1] or s[-1]
In [13]: #slicing
s[5:]
Python List
List is an ordered sequence of items. It is one of the most used datatype in Python and is
very flexible. All the items in a list do not need to be of the same type.
20.5
Python Tuple
Tuple is an ordered sequence of items same as list.The only difference is that tuples are
immutable. Tuples once created cannot be modified.
1.5
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [18], in <cell line: 1>()
----> 1 t[1] = 1.25
Python Set
localhost:8888/nbconvert/html/Desktop/DATA WRANGLING/PYTHON/1.2 python for data science introduction/1_4.ipynb?download=false 3/5
1/23/23, 11:51 AM 1_4
Set is an unordered collection of unique items. Set is defined by values separated by comma
inside braces { }. Items in a set are not ordered.
<class 'set'>
We can perform set operations like union, intersection on two sets. Set have unique values.
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [22], in <cell line: 1>()
----> 1 print(s[1])
Python Dictionary
Dictionary is an unordered collection of key-value pairs.
In Python, dictionaries are defined within braces {} with each item being a pair in the form
key:value. Key and value can be of any type.
apple
5.0
Out[25]:
100
Out[26]:
'20'
Out[27]:
In [28]: int('10p')
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Input In [28], in <cell line: 1>()
----> 1 int('10p')
print("Congratulations, " + user + "! You just wrote " + str(lines) + " lines of co
#remove str and gives error
In [30]: a = [1, 2, 3]
<class 'list'>
<class 'set'>
In [ ]:
Python Output
We use the print() function to output data to the standard output device
Hello World
In [2]: a = 10
print("The value of a is", a) #python 3
print ("The value of a is " + str(a))
The value of a is 10
The value of a is 10
Output Formatting
In [3]: a = 10; b = 20 #multiple statements in single line.
Python Input
want to take the input from the user. In Python, we have the input() function to allow this.
Enter a number: 10
10
In [ ]:
Operators
Operators are special symbols in Python that carry out arithmetic or logical computation.
The value that the operator operates on is called the operand.
Operator Types
1. Arithmetic operators
4. Bitwise operators
5. Assignment operators
6. Special operators
Arithmetic Operators
Arithmetic operators are used to perform mathematical operations like addition,
subtraction, multiplication etc.
Example:
In [1]: x, y = 10, 20
#addition
print(x + y)
#subtraction(-)
#multiplication(*)
#division(/)
#Exponent (**)
30
Comparision Operators
localhost:8888/nbconvert/html/Desktop/DATA WRANGLING/PYTHON/1.2 python for data science introduction/1_6.ipynb?download=false 1/4
1/23/23, 11:55 AM 1_6
Comparison operators are used to compare values. It either returns True or False according
to the condition.
In [2]: a, b = 10, 20
#check a is equal to b
True
Logical Operators
Logical operators are and, or, not operators.
#print a and b
print(a and b)
#print a or b
#print not b
False
Bitwise operators
Bitwise operators act on operands as if they were string of binary digits. It operates bit by
bit
In [4]: a, b = 10, 4
#Bitwise AND
print(a & b)
#Bitwise OR
#Bitwise NOT
#Bitwise XOR
#Bitwise rightshift
#Bitwise Leftshift
Assignment operators
Assignment operators are used in Python to assign values to variables.
a = 5 is a simple assignment operator that assigns the value 5 on the right to the variable a
on the left.
=, +=, -=, *=, /=, %=, //=, **=, &=, |=, ^=, >>=, <<=
are Assignment operators
In [5]: a = 10
a += 10 #add AND
print(a)
20
Special Operators
Identity Operators
is and is not are the identity operators in Python.
They are used to check if two values (or variables) are located on the same part of the
memory.
In [6]: a = 5
b = 5
print(a is b) #5 is object created once both a and b points to same object
#check is not
True
In [7]: l1 = [1, 2, 3]
l2 = [1, 2, 3]
print(l1 is l2)
False
In [8]: s1 = "Satish"
s2 = "Satish"
print(s1 is not s2)
False
MemberShip Operators
in and not in are the membership operators in Python.
They are used to test whether a value or variable is found in a sequence (string, list, tuple,
set and dictionary).
True
True
if statement syntax
if test expression:
statement(s)
The program evaluates the test expression and will execute statement(s) only if the text
expression is True.
Python interprets non-zero values as True. None and 0 are interpreted as False.
Flow Chart
title
Example
In [1]: num = 10
#change number
Syntax:
if test expression:
Body of if
else:
Body of else
Flow Chart
title
Example
In [2]: num = 10
if num > 0:
print("Positive number")
else:
print("Negative Number")
Positive number
if...elif...else Statement
Syntax:
if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else
Flow Chart
title
Example:
In [3]: num = 0
if num > 0:
print("Positive number")
elif num == 0:
print("ZERO")
else:
print("Negative Number")
ZERO
Nested if Statements
We can have a if...elif...else statement inside another if...elif...else statement. This is called
nesting in computer programming.
Example:
In [4]: num = 10.5
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative Number")
Positive number
if (num1 >= num2) and (num1 >= num3): #logical operator and
largest = num1
elif (num2 >= num1) and (num2 >= num3):
largest = num2
else:
largest = num3
print("Largest element among three numbers is: {}".format(largest))
In [ ]:
Loops iterate over a block of code until test expression is false, but sometimes we wish to
terminate the current iteration or even the whole loop without cheking test expression.
break
title
title
Example
In [ ]: numbers = [1, 2, 3, 4]
for num in numbers: #iterating over list
if num == 4:
break
print(num)
else:
print("in the else-block")
print("Outside of for loop")
1
2
3
Outside of for loop
isDivisible = False;
i=2;
while i < num:
if num % i == 0:
isDivisible = True;
print ("{} is divisible by {}".format(num,i) )
break; # this line is the only addition.
i += 1;
localhost:8888/nbconvert/html/Desktop/DATA WRANGLING/PYTHON/1.2 python for data science introduction/break_continue.ipynb?download=f… 1/2
1/23/23, 12:02 PM break_continue
if isDivisible:
print("{} is NOT a Prime number".format(num))
else:
print("{} is a Prime number".format(num))
Enter a number: 16
16 is divisible by 2
16 is NOT a Prime number
continue
Flow Chart
title
title
Example
In [ ]: #print odd numbers present in a list
numbers = [1, 2, 3, 4, 5]
1
3
5
else-block
In [ ]:
Syntax:
while test_expression:
Body of while
The body of the loop is entered only if the test_expression evaluates to True.
Flow Chart
title
Example
In [1]: #Find product of all numbers present in a list
product = 1
index = 0
The else part is executed if the condition in the while loop evaluates to False. The while loop
can be terminated with a break statement.
In such case, the else part is ignored. Hence, a while loop's else part runs if no break occurs
and the condition is false.
else:
print("no item left in the list")
1
2
3
4
5
no item left in the list
isDivisible = False;
i=2;
while i < num:
if num % i == 0:
isDivisible = True;
print ("{} is divisible by {}".format(num,i) )
i += 1;
if isDivisible:
print("{} is NOT a Prime number".format(num))
else:
print("{} is a Prime number".format(num))
Enter a number: 25
25 is divisible by 5
25 is NOT a Prime number
In [ ]: