1/23/23, 10:00 AM 1.
Python Keywords
Keywords are the reserved words in python
We can't use a keyword as variable name, function name or any other identifier
Keywords are case sentive
In [1]: #Get all keywords in python 3.6
import keyword
print(keyword.kwlist)
print("Total number of keywords ", len(keyword.kwlist))
['False', 'None', 'True', '__peg_parser__', 'and', 'as', 'assert', 'async', 'awai
t', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finall
y', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'no
t', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
Total number of keywords 36
Identifiers
Identifier is the name given to entities like class, functions, variables etc. in Python. It helps
differentiating one entity from another.
Rules for Writing Identifiers:
1. Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or
digits (0 to 9) or an underscore (_).
2. An identifier cannot start with a digit. 1variable is invalid, but variable1 is perfectly fine.
3. Keywords cannot be used as identifiers.
In [2]: global = 1
Input In [2]
global = 1
^
SyntaxError: invalid syntax
We cannot use special symbols like !, @, #, $, % etc. in our identifier.
In [3]: abc12 = 10 #can't use special symbols as an identifier
In [4]: 21_abc12 =10
Input In [4]
21_abc12 =10
^
SyntaxError: invalid decimal literal
localhost:8888/nbconvert/html/Desktop/DATA WRANGLING/PYTHON/1.2 python for data science introduction/1.2.ipynb?download=false 1/2
1/23/23, 10:00 AM 1.2
In [5]: a=10;
b=20;
print("the value of a is {} and b is {} ".format(a,b))
the value of a is 10 and b is 20
In [6]: a@ = 10
Input In [6]
a@ = 10
^
SyntaxError: invalid syntax
localhost:8888/nbconvert/html/Desktop/DATA WRANGLING/PYTHON/1.2 python for data science introduction/1.2.ipynb?download=false 2/2
1/23/23, 11:48 AM 1_3
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.
In [1]: #Print Hello, world to console
print("Hello, world 2")
Hello, world 2
Multi Line Comments
If we have comments that extend multiple lines, one way of doing it is to use hash (#) in the
beginning of each line.
In [2]: #This is a long comment
#and it extends
#Multiple lines
Another way of doing this is to use triple quotes, either ''' or """.
In [3]: """This is also a
perfect example of
multi-line comments"""
'This is also a\nperfect example of\nmulti-line comments'
Out[3]:
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.
In [4]: def double(num):
"""
function to double the number
"""
return 2 * num
localhost:8888/nbconvert/html/Desktop/DATA WRANGLING/PYTHON/1.2 python for data science introduction/1_3.ipynb?download=false 1/3
1/23/23, 11:48 AM 1_3
print (double(10))
20
In [5]: print (double.__doc__) #Docstring is available to us as the attribute __doc__ of th
function to double the number
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.
In [6]: for i in range(10):
print (i)
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
In [8]: if True: print ("Machine Learning"); c = "AAIC"
Machine Learning
Python Statement
Instructions that a Python interpreter can execute are called statements.
Examples:
In [9]: a = 1 #single statement
localhost:8888/nbconvert/html/Desktop/DATA WRANGLING/PYTHON/1.2 python for data science introduction/1_3.ipynb?download=false 2/3
1/23/23, 11:48 AM 1_3
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
In [11]: print (a)
36
In [12]: #another way is
a = (1 + 2 + 3 +
4 + 5 + 6 +
7 + 8)
print (a)
36
In [13]: a = 10; b = 20; c = 30 #put multiple statements in a single line using ;
localhost:8888/nbconvert/html/Desktop/DATA WRANGLING/PYTHON/1.2 python for data science introduction/1_3.ipynb?download=false 3/3
1/23/23, 11:51 AM 1_4
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"
In [3]: a = b = c = "AI" #assign the same value to multiple variables at once
Storage Locations
In [4]: x = 3
print(id(x)) #print address of variable x
1910655641968
In [5]: y = 3
print(id(y)) #print address of variable y
1910655641968
Observation:
x and y points to same memory location
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.
In [7]: a = 5 #data type is implicitly set to integer
print(a, " is of type", type(a))
5 is of type <class 'int'>
In [8]: a = 2.5 #data type is changed to float
print(a, " is of type", type(a))
2.5 is of type <class 'float'>
In [9]: a = 1 + 2j #data type is changed to complex number
print(a, " is complex number?")
print(isinstance(1+2j, complex))
(1+2j) is complex number?
True
Boolean
Boolean represents the truth values False and True
In [10]: a = True #a is a boolean type
print(type(a))
<class 'bool'>
Python Strings
String is sequence of Unicode characters.
We can use single quotes or double quotes to represent strings.
Multi-line strings can be denoted using triple quotes, ''' or """.
A string in Python consists of a series or sequence of characters - letters, numbers, and
special characters.
Strings can be indexed - often synonymously called subscripted as well.
Similar to C, the first character of a string has the index 0.
localhost:8888/nbconvert/html/Desktop/DATA WRANGLING/PYTHON/1.2 python for data science introduction/1_4.ipynb?download=false 2/5
1/23/23, 11:51 AM 1_4
In [11]: s = "This is Online AI course"
print(s)
This is Online AI course
In [12]: print(s[0])
#last char s[len(s)-1] or s[-1]
In [13]: #slicing
s[5:]
'is Online AI course'
Out[13]:
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.
Declaring a list is , Items separated by commas are enclosed within brackets [ ].
In [14]: a = [10, 20.5, "Hello"]
print(a[1]) #print 1st index element
20.5
Lists are mutable, meaning, value of elements of a list can be altered.
In [15]: a[1] = 30.7
print(a)
[10, 30.7, 'Hello']
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.
In [16]: t = (1, 1.5, "ML")
In [17]: print(t[1]) #extract particular element
1.5
In [18]: t[1] = 1.25
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [18], in <cell line: 1>()
----> 1 t[1] = 1.25
TypeError: 'tuple' object does not support item assignment
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.
In [19]: a = {10, 30, 20, 40, 5}
print(a)
{20, 5, 40, 10, 30}
In [20]: print(type(a)) #print type of a
<class 'set'>
We can perform set operations like union, intersection on two sets. Set have unique values.
In [21]: s = {10, 20, 20, 30, 30, 30}
print(s) #automatically set won't consider duplicate elements
{10, 20, 30}
In [22]: print(s[1]) #we can't print particular element in set because
#it's unorder collections of items
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [22], in <cell line: 1>()
----> 1 print(s[1])
TypeError: 'set' object is not subscriptable
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.
In [24]: d = {'a': "apple", 'b': "bat"}
print (d['a'])
apple
Conversion between Datatypes
We can convert between different data types by using different type conversion functions
like int(), float(), str() etc.
In [25]: float(5) #convert interger to float using float() method
5.0
Out[25]:
In [26]: int(100.5) #convert float to integer using int() method
100
Out[26]:
In [27]: str(20) #convert integer to string
localhost:8888/nbconvert/html/Desktop/DATA WRANGLING/PYTHON/1.2 python for data science introduction/1_4.ipynb?download=false 4/5
1/23/23, 11:51 AM 1_4
'20'
Out[27]:
Conversion to and from string must contain compatible values.
In [28]: int('10p')
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Input In [28], in <cell line: 1>()
----> 1 int('10p')
ValueError: invalid literal for int() with base 10: '10p'
In [29]: user = "satish"
lines = 100
print("Congratulations, " + user + "! You just wrote " + str(lines) + " lines of co
#remove str and gives error
Congratulations, satish! You just wrote 100 lines of code
We can convert one sequence to other
In [30]: a = [1, 2, 3]
print(type(a)) #type of a is list
s = set(a) #convert list to set using set() method
print(type(s)) #now type of s is set
<class 'list'>
<class 'set'>
In [31]: list("Hello") #convert String to list using list() method
['H', 'e', 'l', 'l', 'o']
Out[31]:
In [ ]:
localhost:8888/nbconvert/html/Desktop/DATA WRANGLING/PYTHON/1.2 python for data science introduction/1_4.ipynb?download=false 5/5
1/23/23, 11:53 AM 1_5
Python Input and Output
Python Output
We use the print() function to output data to the standard output device
In [1]: print("Hello World")
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.
print("The value of a is {} and b is {}".format(a, b)) #default
The value of a is 10 and b is 20
In [4]: a = 10; b = 20 #multiple statements in single line
print("The value of b is {1} and a is {0}".format(a, b)) #specify position of argum
The value of b is 20 and a is 10
In [5]: #we can use keyword arguments to format the string
print("Hello {name}, {greeting}".format(name="satish", greeting="Good Morning"))
Hello satish, Good Morning
In [6]: #we can combine positional arguments with keyword arguments
print('The story of {0}, {1}, and {other}'.format('Bill', 'Manfred',
other='Georg'))
The story of Bill, Manfred, and Georg
Python Input
want to take the input from the user. In Python, we have the input() function to allow this.
In [7]: num = input("Enter a number: ")
print (num)
Enter a number: 10
10
In [ ]:
localhost:8888/nbconvert/html/Desktop/DATA WRANGLING/PYTHON/1.2 python for data science introduction/1_5.ipynb?download=false 1/1
1/23/23, 11:55 AM 1_6
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
2. Comparison (Relational) operators
3. Logical (Boolean) 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.
+ , -, *, /, %, //, ** are arithmetic operators
Example:
In [1]: x, y = 10, 20
#addition
print(x + y)
#subtraction(-)
#multiplication(*)
#division(/)
#modulo division (%)
#Floor 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.
>, <, ==, !=, >=, <= are comparision operators
In [2]: a, b = 10, 20
print(a < b) #check a is less than b
#check a is greater than b
#check a is equal to b
#check a is not equal to b (!=)
#check a greater than or equal to b
#check a less than or equal to b
True
Logical Operators
Logical operators are and, or, not operators.
In [3]: a, b = True, False
#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
&, |, ~, ^, >>, << are Bitwise operators
In [4]: a, b = 10, 4
#Bitwise AND
print(a & b)
#Bitwise OR
#Bitwise NOT
localhost:8888/nbconvert/html/Desktop/DATA WRANGLING/PYTHON/1.2 python for data science introduction/1_6.ipynb?download=false 2/4
1/23/23, 11:55 AM 1_6
#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)
#subtract AND (-=)
#Multiply AND (*=)
#Divide AND (/=)
#Modulus AND (%=)
#Floor Division (//=)
#Exponent AND (**=)
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
localhost:8888/nbconvert/html/Desktop/DATA WRANGLING/PYTHON/1.2 python for data science introduction/1_6.ipynb?download=false 3/4
1/23/23, 11:55 AM 1_6
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).
In [9]: lst = [1, 2, 3, 4]
print(1 in lst) #check 1 is present in a given list or not
#check 5 is present in a given list
True
In [10]: d = {1: "a", 2: "b"}
print(1 in d)
True
localhost:8888/nbconvert/html/Desktop/DATA WRANGLING/PYTHON/1.2 python for data science introduction/1_6.ipynb?download=false 4/4
1/23/23, 12:04 PM if-elif-else
Python if ... else Statement
The if…elif…else statement is used in Python for decision making.
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.
If the text expression is False, the statement(s) is not executed.
Python interprets non-zero values as True. None and 0 are interpreted as False.
Flow Chart
title
Example
In [1]: num = 10
# try 0, -1 and None
if None:
print("Number is positive")
print("This will print always") #This print statement always print
#change number
This will print always
if ... else Statement
Syntax:
if test expression:
Body of if
else:
localhost:8888/nbconvert/html/Desktop/DATA WRANGLING/PYTHON/1.2 python for data science introduction/if-elif-else.ipynb?download=false 1/3
1/23/23, 12:04 PM if-elif-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
localhost:8888/nbconvert/html/Desktop/DATA WRANGLING/PYTHON/1.2 python for data science introduction/if-elif-else.ipynb?download=false 2/3
1/23/23, 12:04 PM if-elif-else
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
Python program to find the largest
element among three Numbers
In [5]: num1 = 10
num2 = 50
num3 = 15
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))
Largest element among three numbers is: 50
In [ ]:
localhost:8888/nbconvert/html/Desktop/DATA WRANGLING/PYTHON/1.2 python for data science introduction/if-elif-else.ipynb?download=false 3/3
1/23/23, 12:02 PM break_continue
Python break and continue Statements
In Python, break and continue statements can alter the flow of a normal loop.
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.
The break and continue statements are used in these cases.
Python break Statement
Syntax:
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
Python Program to check given number is
Prime number or not (using break)
In [ ]: num = int(input("Enter a number: ")) #convert string to int
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
Python Continue Statement
syntax:
continue
Flow Chart
title
title
Example
In [ ]: #print odd numbers present in a list
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num % 2 == 0:
continue
print(num)
else:
print("else-block")
1
3
5
else-block
In [ ]:
localhost:8888/nbconvert/html/Desktop/DATA WRANGLING/PYTHON/1.2 python for data science introduction/break_continue.ipynb?download=f… 2/2
1/23/23, 12:08 PM While_loop
Python while Loop
The while loop in Python is used to iterate over a block of code as long as the test
expression (condition) is true.
Syntax:
while test_expression:
Body of while
The body of the loop is entered only if the test_expression evaluates to True.
After one iteration, the test expression is checked again.
This process continues until the test_expression evaluates to False.
Flow Chart
title
Example
In [1]: #Find product of all numbers present in a list
lst = [10, 20, 30, 40, 60]
product = 1
index = 0
while index < len(lst):
product *= lst[index]
index += 1
print("Product is: {}".format(product))
Product is: 14400000
while Loop with else
Same as that of for loop, we can have an optional else block with while loop as well.
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.
localhost:8888/nbconvert/html/Desktop/DATA WRANGLING/PYTHON/1.2 python for data science introduction/While_loop.ipynb?download=false 1/2
1/23/23, 12:08 PM While_loop
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.
In [2]: numbers = [1, 2, 3,4,5]
#iterating over the list
index = 0
while index < len(numbers):
print(numbers[index])
index += 1
else:
print("no item left in the list")
1
2
3
4
5
no item left in the list
Python Program to check given number is
Prime number or not
In [3]: num = int(input("Enter a number: ")) #convert string to int
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 [ ]:
localhost:8888/nbconvert/html/Desktop/DATA WRANGLING/PYTHON/1.2 python for data science introduction/While_loop.ipynb?download=false 2/2