Python
Python
Basics
Why Python ?
Supportive
Open Simple Flexible community with
Language plenty of
Source Syntax documentation
Syntax:
print(message1,message2,…)
Example:
print(‘Good Morning’,’Everyone’)
Output:
Good Morning Everyone
Smallest Building block
in any
programming language
Can’t be a keyword
Unlimited Length
Examples of…
Valid Identifiers Invalid Identifiers
true True
_Geeta True&
Num123 if
One_123 5num
LEN 5_Num
Len Num 123
FALSE Y*8
O1N2 T_
END class
If int
X=10
Y=20
X,Y=10,20
Identifier
Tokens
Declaration X=10;Y=20
X=Y=20
+ (Addition)
- (Subtraction)
* (Multiplication)
Tokens
print("Hena"!="Heena") True
print("Bharat">"bharat") False
print("60"<"66") True
Tokens
Operators
Logical
not and or
Example
Program Output
Num1=90
Num2=34
print(Num1>10 and Num2<34) False
X=9
Y=45
print(X!=Y and not Y<X) True
Example
Program Output
a = 13 False
b = 33
# a > b is False True
print(a > b) False
# a < b is True
print(a < b)
True
# a == b is False False
print(a == b) True
# a != b is True
print(a != b)
# a >= b is False
print(a >= b)
# a <= b is True
print(a <= b)
Tokens
Augmented
Assignment
Operators Membership
not in
is
Tokens
Operators Identity
not is
() Brackets, list display, dictionary display, set
display
** Exponentiation
*, /, //, % Multiplication, Division, Floor Division,
Remainder (All same, evaluated which
comes from left to right)
+,- Addition, Subtraction ((All same, evaluated
Tokens
() [] {}
Delimiters
space, comma,
semicolon, colon, , : . ;
and any other
character
Example
Program: of swapping two numbers
One Way Other Way
X,Y=10,20 X,Y=10,20
Z=X X,Y=Y,X
X=Y print(X,Y,sep=‘*’)
Y=Z
print(X,Y,sep=‘*’) 20*10
input() : Used to accept data
• Accepts string data by default
• Message can be provided with function
Example of accepting string
X=input('Enter First Name')
Y=input('Enter Last Name')
print(X,Y)
Example Output
X=12;Y=20
print(X,Y,sep=‘and’) 12and20
print(X+Y,end=‘printed’) 32printed
X=12;Y=20
print(X,Y,sep=‘+’,end’=’)
print(X+Y) 12+20=32
Conditional Statement
• if
• if else
• if elif else
Syntax
if <condition> : Block starts if <condition> : Block starts
….statements…. ….statements….
else: Block for else
….statements….
Conditional Statement
Syntax
if <condition1> : Block starts
….statements….
elif <condition2>: Block for elif
Note
Else not compulsory
….statements….
As soon as the True condition is found,
elif <condition3>: Block for elif the rest of the conditions are ignored
….statements….
.
.
else: Block for else
….statements….
Conditional Statement
Nested if Example
if <condition1> : Program to Display grade
if <condition>: 90-100 A1
if <condition>: 80-90 A2
….statements…. 70-80 B1
else: 60-70 B2
….statements….
50-60 C1
else:
40-50 C2
….statements….
<40 D
else:
….statements….
Single Liner if statement
<statement if True condition> if condition else <statement if False>
Example
#Program to check if number accepted is even or odd
A=int(input())
print("Even") if A%2==0 else print("Odd")
Examples
name = "John"
age = 23
if name == "John" and age == 23:
print("Your name is John, and you are also 23 years
old.")
if name == "John" or name == “Rick":
print("Your name is either John or Rick.")
Examples
# Code to check for odd or even
x = int(input("Please enter first integer: "))
if x%2 == 0:
print(“ x is even”)
else:
print(“x is odd”)
Questions
Sample Output
Enter choice(1/2/3/4): 3
Enter first number: 15
Enter second number: 14
15 * 14 = 210
Loops
for while
Can never go into
Can go into infinite case
infinite case
sum = 1+2+3+...+n
pass
Practically does nothing. Continues with the rest
of the statements in loop.
Continue
Jumps for the next iteration.
Example
pass Continue break
print("--Using print("--Using print("--Using
\"pass\"--") \"continue\"--") \"break\"--")
for n in range(1,6): for n in range(1,6): for n in range(1,6):
if n == 3: if n == 3: if n == 3:
pass continue break
print(n) print(n) print(n)
Note: The else of a loop will get executed if the loop completes all the
iterations, which means the break is not encountered
Nested Loop
Loop inside another loop
For every value of outer loop the inner loop is executed completely
Used to solve Pattern Questions
1 1 1234 1234 4321 1
12 21 234 123 321 23
123 321 34 12 21 456
1234 4321 4 1 1 78910
1 4 1111 1111 * 5
22 33 222 2222 ** 1015
333 222 33 3333 *** 202530
4444 1111 4 4444 **** 35404550
Nested Loop
Basic Rule :
Outer Loop for number of rows
Inner Loop for number of values in each row
I J
for I in range(1,3):
for J in range(1,3):
1 1
print(I,J,sep='+',end=',') 2
print()
1+1,1+2,2+1,2+2, 2 1
2
Iterable
Mutable Immutable
List L=[1,3,5,7]
Tuple T=(4,8,1,2)
Dictionary D={‘a’:12,’b’:90 }
String S=‘Data‘
Set S={5,8,9 }
Mutable
List
Data is stored within Square Brackets.
It is a heterogenous collection of data.
Each value is called Element
Each element is extracted using index number starting from 0
iterable.[start:end:step]
String Functions
capitalize(): Returns a copy of this string with only the first character capitalized.
title(): Returns string by capitalizing first letter of every word in the string
S=
lower(): Returns string by converting every character to lowercase
list.append()
The method list.append(x) will add an item (x) to the
end of a list.
list.insert()
The list.insert(i,x) method takes two arguments,
with i being the index position you would like to
add an item to, and x being the item itself.
>>> fruits.insert(1,'pear')
>>> print (fruits)
['banana', 'pear', 'apple', 'mango', 'orange',
'watermelon', 'grapes', 'Pineapple']
FUNCTIONS/METHODS IN LIST
list.extend()
If we want to combine more than one list, we can use
the list.extend method, which takes in a second list
as its argument.
list.remove()
This method removes the first item in a list whose value is
equivalent to x.
>>> fruits.remove('orange')
>>> print(fruits)
['banana', 'pear', 'apple', 'mango', 'watermelon',
'grapes', 'Pineapple', 'cherry', 'strawberry']
>>> fruits.remove('Mango')
Traceback (most recent call last):
File "<pyshell#21>", line 1, in <module>
fruits.remove('Mango')
5 / GS2
ValueError: list.remove(x): x not in list
FUNCTIONS/METHODS IN LIST
list.pop()
The list.pop([i]) method returns the item at the given index
position from the list and then removes that item. The
square brackets around the i for index indicates that this
parameter is optional, so if we don’t specify an index , the
last item will be returned and removed.
>>> fr = fruits.pop(3)
>>> print(fr)
mango
>>> fru = fruits.pop()
>>> print(fru)
strawberry
FUNCTIONS/METHODS IN LIST
list.index()
list.index(x), where x is equivalent to an item
value, to return the index in the list where that
item is located. If there is more than one item with
value x, this method will return the first index
location.
>>> print(fruits.index('grapes'))
4
>>> x = fruits.index('grapes')
>>> print(x)
4
FUNCTIONS/METHODS IN LIST
list.copy()
list.reverse()
We can reverse the order of items in a list by using
the list.reverse() method.
>>> fruits.reverse()
>>> print(fruits)
list.count()
The list.count(x) method will return the number of
times the value x occurs within a specified list.
>>> print(fruits.count('cherry'))
1
>>> fruits.append("cherry")
>>> print(fruits.count('cherry'))
2
FUNCTIONS/METHODS IN LIST
list.sort()
0 1 2 3 4
A=[[1,4,5,3],[5,22,51],[7,34,6],89,90]
0 1 2 3 0 1 2 0 1 2
A=[[1,4,5,3],[5,22,51],[7,34,6],89,90]
for i in A: [1, 4, 5, 3]
if type(i)==list: [5, 22, 51]
print(i)
[7, 34, 6]
else:
Not a List
print(“Not a list”)
Not a List
FUNCTIONS/METHODS IN TUPLE
L=(2,3,4)
print(len(L)) #3
print(len((2,4,5)))#3
S=len(L)
W=len(L*3)
print(S,W) #3 9
FUNCTIONS/METHODS IN TUPLE
tuple ( )
Converts a given iterable into a list. If no iterable,
then blank list is created.
Tuple(iterable object)
a=tuple()
print(a) #( )
c=[1,2]
print(tuple(c))#(1,2)
b=12
#print(tuple(b)) #Not allowed
FUNCTIONS/METHODS IN TUPLE
Tuple.count(value)
L=(1,2,3,3,2,2,1,3,5)
print(L.count(3)) #3
print(L.count(1)) #2
print(L.count(2)) #3
print(L.count(9)) #0
L=(1,2,3,(1,3),2,2,1,3,5)
print(L.count((1,3))) #1
FUNCTIONS/METHODS IN TUPLE
L=(1,2,3,5,2,11,6,5)
print(L.index(5))
print(L.index(5,0,3)) Output
print(L.index(5,0,4)) ?
print(L.index(6))
Nested Tuple
0 1 2 3 4
A=([1,4,5,3],(5,22,51),[7,34,6],89,90)
0 1 2 3 0 1 2 0 1 2
A=([1,4,5,3],(5,22,51),[7,34,6],89,90)
Not a List
for i in A:
(5, 22, 51)
if type(i)==tuple:
Not a Tuple
print(i)
Not a Tuple
else: Not a Tuple
print(“Not a tuple”)
Mutable
Dictionary
D={'a':1,'b':2,'a':22,'a':11,'b':1}
print(D) #{'a': 11, 'b': 1}
D={'a':1,'b':2,'a':22,'a':11,'b':1,'c':6,'b':"tt"}
print(D) #{'a': 11, 'b': 'tt', 'c': 6}
Common Functions in String, List, Tuple, Dictionary
len(String) len(List) len(Tuple) len(Dictionary)
#returns length of string #returns length of List #returns length of Tuple #returns length of Dictionary
sum(Tuple)
have homogenous values in key
USER DEFINED
BUILT-IN FUNCTIONS
FUNCTIONS (created
(For eg sqrt(), random()
using def keyword)
etc
CREATING USER DEFINED FUNCTIONS
POINTS TO REMEMBER
● Multiple values are returned in the form of Tuple, if parentheses are not
specified
● To designate multiple value returning, you need to to enclose them in
appropriate brackets.
Out func 10
Output: in funct 20
Out func 10
Rules for accessing the Local/Global Variables
1. Priority is always given to local variables
3. But the value of the global variable is not allowed to get changed
in local variable until explicitly specified.
c=12
print("The Value of C : ", c)
Fun()
print("The Value of C now :",c)
Can Local and Global variables with same name be
used in same function?
NO
def Fun(): ERROR!!!!
a,b,c=4,5,17
print(a,b,c)
global c (A variable cannot be
c=a+b both local and global
print(a,b,c) inside a function)
c=12
print("The Value of C : ", c)
Fun()
print("The Value of C now :",c)
Interesting Programs to try in Python
import pywhatkit
pywhatkit.sendwhatmsg(‘+911234567890','Hello',18,5)