Python
Python is an open source (Freely available), object oriented high level
programming language developed by Guido Van Rossum in Netherlands. Python
is a general purpose programming language that can be used effectively to build
any kind of program that does not require direct access to computers hardware.
Features of Python:
• Easy
• Free and open source
• Expressive Language: Capable of expressing the code’s purpose
(Fewer lines of Code, Simpler Syntax)
• High Level
• Portable
• Object Oriented
• Interpreted
• Large standard Library
• GUI Programming
Installing Python (3.10.4) for windows 8.1 or above.
[Link]
Python IDLE
Python IDLE comprises Python Shell (Interactive Mode) and Python Editor (Script
Mode).
Python Shell:
Python shell is an interactive window where you can type in the Python
code and see the output in the same window. It is an interface between Python
commands and the OS. The three greater than signs (>>>) are called the prompt
or Python command prompt.
Script Mode
In script mode, we can write our code in a text file then save it with a .py
extension which stands for python. After writing the code we run it by clicking
“Run” then “Run Module” or simply press F5.
print () Function
print() function is used to display the specified content on the screen. The
content (Called Arguments) is specified within the parentheses. print () statement
without any arguments will simply jump to the next line.
Syntax of print() function
print(val1, val2, val3,......,sep= ‘ ‘, end=’\n’)
Example:
>>>print(10,20,30,40,sep= ‘*’)
Output:
10*20*30*40
End Parameter with print()
Python’s print() function comes with a parameter called ‘end’, By default
the value of this parameter is ‘\n’ i.e. the new line character. You can end a print
statement with any character / string using this parameter.
Example
>>>print(10,20,30,40,sep= ‘*’, end=’###\n’)
Output:
10*20*30*40###
exit() / quit()
to exit python command prompt type quit() or exit() function/statement
and press enter key.
>>>exit()
Or
>>>quit()
Token:
The smallest individual unit in a program is known as a token or a lexical unit.
Python has following tokens:
i) Keywords
ii) Identifiers (Names)
iii) Literals
iv) Operators
v) Punctuator
Keywords:
Keywords are reserved words that have a special purpose in the language.
Ex. False, if, break, continue, True, for and while.
Identifiers:
Identifiers are the names given to different part of the program. i.e.
variables, object, classes, functions, lists, dictionaries etc.
• Identifier can be start with an alphabet (A to Z or a to z) or an
underscore(_)
• Special symbol or punctuation characters such as @, $ and % cannot be
used in identifier.
• It cannot contain space.
• It cannot be a keyword and it is case sensitive. A=10 a=20
123abc abc# abc_bcd12 first_name while_abc @abc 1_abc True=0
Literals (Constants):
Literals are the fixed values that do not change during program execution.
• String Literals : ‘amit’ “ankit” “112gahj”
“aa222dd”
• Numeric Literals: 20, 50, -30, 2.35, 23.33
• Boolean Literals: True, False
• Special Literal : None
Operators:
Operators are tokens that trigger some computation when applied to a variable
or operands.
• Binary Operators:
Binary operators are those operators that require two operands to
operate upon. Following are some binary operators:
Arithmetic Operators:
+ Addition - Subtraction * Multiplication / Division
% Modulus ** Exponent // Floor Division
Relational Operators:
<Less Than > Greater Than <= Less than equal to == Equal to
!= Not Equal to >=Greater than equal to
Assignment Operator:
= Assignment += Assign Sum *= Assign Product /= assign quotient
%= Assign Remainder -= Assign Difference **= Assign Exponent
//=Assign Floor
Logical Operators:
and (Logical And) or (Logical OR) not (Logical Not)
Punctuators:
Punctuators are symbols that are used in programming language to
organize sentence structures, statements and program structure.
Example : ‘ “ # \ () {} [] @ , : . ;
Escape Sequence:
\n New Line
\t Horizontal Tab
\\ Backslash
\’ Single Quote
\” Double Quote
Structure of a Python Program
Variable:
Variable represents named storage location, whose value can be
manipulated during program execution.
Eg. student = ‘Arpit’
Age = 16
Multiple Assignment:
Assigning same value to multiple variables:
a=b=c=10 it will assign 10 to all three variable a,b,c.
Assigning multiple values to multiple variables:
x, y, z = 10, 20, 30 it will assign 10 to x, 20 to y and 30 to z.
To swap the value of x and y
x, y = y, x after execution x=20 and y=10
The input () Function:
input () function is used to read the data from the keyboard but it returns
as a string.
Syntax:
Variable_name=input(“Message”)
Example1:
>>>name= input(“Enter your name:”)
Enter your name:arpit
>>> print(name)
arpit
Example2:
>>> a=input("enter a:")
enter a:10
>>> b=input("enter b:")
enter b:20
>>> print(a+b)
1020 Example4:
>>> a=input("enter a:")
Example3:
enter a:10
>>> a=int(input("enter a:")) >>> b=input("enter b:")
enter a:10 enter b:20
>>> print(int(a)+int(b))
>>> b=int(input("enter b:"))
30
enter b:20
>>> print(a+b)
30
Q.1 Write a program to read distance in miles and print in kilometre. (1
mile=1.609 km)
Q.2 Write a program to compute “how many days in a million seconds?”
q.3 Write a program to calculate simple interest by entering the value of principle
amount, rate of interest and time period.
q.4 Write a program to calculate the area of a rectangle by entering length and
width.
q.5 Write a program to calculate the area of a triangle by entering height and
base.
q.6 Write a program to enter two integers and perform all arithmetic operations
on them.
q.7 Write a program to swap two numbers using a third variable.
q.8 Write a program to enter three numbers and find their average.
Q.9 Write a program to obtain temperature in Celsius and convert it to Fahrenheit
using formula: °F =(°Cx9/5)+32
Data Types:
Data types are means to identify the type of data and associated operations
of handling it. In Python we are not required to explicitly declare a variable
with its type. Whenever we declare a variable with some value, Python
automatically allocates the relevant data type associated with it. Hence, the
data type of a variable is according to the value it holds.
Eg.
>>> a= 10
The above statement signifies ‘a’ to be of integer type since it has been
assigned an integer value 10.
Data type
Number None Sequences Sets Mapping
Tuple
Floating
Integer Complex String List Dictionary
Point
Boolean
Number or Numeric Data Type
Number data type is used to store numeric values.
• Integer: to store whole numbers. They can be positive or negative.
Eg. 12, 30, 100, -10
o Boolean: Boolean data type is used in situation where comparison to be
made always result in either True(1) or False(0).
• Float/ Floating Point: to store real numbers. They can be represented in
scientific notations where the uppercase or lowercase letter ‘e’ signifies
the 10th power.
>>>3.8e2
380.0
>>>3.8e3
3800.0
>>>0.2534e2
25.34
• String: A string data type lets you hold string data. Characters are written
inside simple quotation marks (Single or double). Eg. ‘Amit’, ‘Boy’, “ford”
etc.
• List: A list in Python represents a list of comma-separated values of any
data type between square brackets.
Eg. a=[‘a’, ’e’, ‘i’, ‘o’, ‘u’]
b=[‘age’, 10.5, 20,’a’, [3,4,5,6],45]
List can be assigned to variables just like other data types and you can
also change individual elements of a list.
• Tuples: Tuples are represented as list of comma-separated values of any
data type within parentheses.
Eg. a=(‘a’, ’e’, ‘i’, ‘o’, ‘u’)
b=(‘age’, 10, 20, 23, 45)
Tuples like list can be assigned to variable but individual elements of
tuples cannot be modified.
• Dictionary: Dictionary is an unordered set of comma-separated
key:value pairs, within {}. In a dictionary no two keys can be the same.
Eg.
>>>a={‘y’: 2 ,‘x’: 1, ‘z’: 3} Here ‘x’: 1 is a key: value pair
>>>a[‘x’]
1
>>>a[‘z’]
3
>>> print(a['x'])
1
>>> a['x']=10
>>> print(a)
{'x': 10, 'y': 2, 'z': 3}
Statement flow control
In a program, statements may be executed sequentially, selectively or iteratively.
Every programming language provides constructs to support sequence, selection
or iteration.
Sequence:
The sequence construct means the statements are being executed sequentially.
This represents the default flow of statements. Every python program begins with
first statement of the program and ends with the execution of the final statement
of the program. Sequence refers to the normal flow of control in a program and
is the simple one.
Selection:
The selection construct means the execution of statement(s) depending upon a
condition test. If a condition evaluates to True, a course-of-action (a set of
statements) is followed otherwise another course-of-action(a different set of
statements)is followed. This construct is called decision construct because it
helps in making decision about which a set-of-statements is to be executed.
Iteration:
The iteration construct means repetition of a set-of-statements depending upon
a condition test. Till the time a condition is True, a set of statements repeated
again and again. As soon as the condition becomes false the repetition stops. The
set of statements that are repeated again and again is called the body of the loop.
Selection Control Statements:
The if statement:
The simplest form of if statement tests a condition and if the condition evaluates
to true, it carries out some instructions and does nothing in case condition
evaluates to false.
The syntax (general form) of if statement is:
if condition :
Statement1 Indentation is must
Statement2
Statement3
Example1:
x= int(input("please enter the value of x"))
y= int(input("please enter the value of y"))
if(x>y):
print("x is greater than y")
Homework:
Write a program to accept three integers and print the largest of the three. Make
use of only simple if statement.
The if-else statement:
The form of if statement tests a condition and if the condition evaluates to true,
it carries out statement indented below if and in case condition evaluates to false,
it carries out statement indented below else.
The syntax (general form) of the if-else statement is as shown below:
if (condition) :
Statement Indentation is must
[Statements]
else:
Statement Indentation is must
[Statements]
Example1:
Write a program that accepts total sales from the user and calculate the discount
as per the following criteria:
If sales>= 10000 discount=10%
If sales<10000 discount =5%
sales= int(input("please enter the sales amount")) 9000
if (sales>=10000):
discount=sales*10/100
else:
discount=sales*5/100
print(discount)
Example2:
Write a program that accepts a number from the user and checks whether the
entered number is even or odd.
num= int(input("please enter the number")) 31
if num%2==0:
print("number is even")
else:
print("number is odd")
Q. WAP that accepts age of a person from the user and find
whether the person is eligible for voter Id or not.
age=int(input("Enter Age:"))
if(age>=18):
print("You are eligible for voter id.")
else:
print("you are not eligible for voter id.")
Q. WAP that accepts a number from the user and check whether the number is even or odd.
Q. WAP that accepts a number from the user and check whether the number is divisible by 3 or not.
num=int(input("Enter number:"))
if(num%3==0):
print("Number is divisible by 3.")
else:
print("Number is not divisible by 3.")
Q. WAP that accepts a character from the user and find whether the entered character is vowel or
consonant.
c=input("Enter character:")
if(c=='a'or c=='e' or c=='i' or c=='o' or c=='u'):
print("Character is Vowel.")
else:
print("Character is Consonant.")
Q. WAP that accepts a number from the user and find whether the number is negative, positive or zero.
Q. WAP that accepts a number from the user and check whether the number is lying between 200 and
500.
num=int(input("Enter Number:"))
if(num>=200 and num<=500):
print("Number Lying between 200 and 500.")
else:
print("Number not Lying between 200 and 500.")
The if-elif statement:
If-elif statement is used when we need to check condition in case the test-
condition of if evaluates to false. It means we need to check a condition when
control reaches to else part i.e. condition test in the form of elif.
The general form of this statement is:
if (condition) :
Statement
[Statements]
elif(condition):
Statement
[Statements]
else:
Statement
[Statements]
Example1:
Write a program that accepts a number from the user and checks whether the
entered number is negative, positive or zero.
num= int(input("please enter the number"))
if (num>0):
print("number is positive")
elif(num<0):
print("number is negative")
else:
print("number is zero")
Example2:
Q. Write a program that read two numbers and an arithmetic operator (+, -, / , *,
%) and displays the computed result.
Q. Write a program to accept a character from the user and display whether it is
vowel or consonant.
Q. Write a program that reads three numbers (integers) and print them in
ascending order.
a=int(input("Enter a:"))
b=int(input("Enter b:"))
c=int(input("Enter c:"))
if(a<b and a<c):
if(b<c):
print(a,b,c)
else:
print(a,c,b)
elif(b<a and b<c):
if(a<c):
print(b,a,c)
else:
print(b,c,a)
elif(c<a and c<b):
if(a<b):
print(c,a,b)
else:
print(c,b,a)
Q. Write a program that accepts a character from the user and check whether it
is an uppercase character, lowercase character, digit or a special character.
The nested if Statement:
A nested if is an if that has another if in its if’s body or in elif’sbody or in its else’s
body.
Syntax
if (condition): if (condition):
if (condition): Statements
Statements elif (condition):
else: if (condition):
Statements Statements
elif (condition): else:
Statements Statements
else: else:
Statements Statements
Example1:
WAP to find the largest value of any three numbers.
WAP to find the largest value of any four numbers.
The range() Function:
The range() function of python generates a list which is a special sequence type.
A sequence in python is a succession of values bound together by a single name.
The syntax of range() is as follows:
range(<lower limit>, <upper limit>, <step-value>) # step value is optional
here, lower limit is included in the list but upper limit is not included in the list.
For example
range(0,5,1) Step value is 1
Will produce the list as [0,1,2,3,4]
range(0,5,2) Step value is 2
Will produce the list as [0,2,4]
Write the output of the following range function:
1) range(10)
2) range(5, 10)
3) range(3,7)
4) range(5,15,3)
5) range(9, 3,-1)
6) range(10, 1, -2)
Iteration/ Loop Statement
The iteration statements or repetition statements allows a set of instructions to
be performed repeatedly until a certain condition fulfilled. The iteration
statements are also called loops or loop statement. Python provides two kinds of
loops: for loop and while loop.
The for loop
The for loop of python is designed to process the items of any sequence, such as
a list or a string, one by one.
The general syntax of for loop is as follows:
for <variable> in <sequence> :
statements_to_repeat (Block of statement)
else:
Body of else
1
Example1: 4
for a in [1,2,3,4,5] : 9
print(a*a) 16
25
Example2: D
e
for a in 'Delhi': l
print(a) h
i
Example3: Write a program to print 1 to 10 natural numbers.
for a in range(1,11):
print(a)
Example4: Write a program to print odd numbers between 1 and 20.
for a in range(1,20,2):
print(a)
Q.1 WAP to access the elements of list.
for a in [1,2,3,4]:
print(a)
Q.2 WAP to find the sum of all the elements of a list.
Q.3 WAP to find the smallest element of the list.
Q.4 WAP to find the largest element of the list.
Q.5 WAP to find the sum of ‘n’ natural numbers.
Q.6 WAP to find the sum of odd numbers between 1 and 30.
The while loop:
A while loop is a conditional loop that will repeat the instructions within itself as
long as a condition remains true.
Syntax
while <logical expression>:
Block of Statement
else:
Body of else
Example1: Program to calculate the factorial of a number:
num=int(input("enter the number")) 5
fact=1
a=1
while a<=num:
fact=fact*a
a+=1
print("the factorial of", num, "is", fact)
Example2: Program to calculate and print the sums of even and odd integers of
the first n natural number:
n=int(input("Up to which natural number?"))
c=1
sum_even=sum_odd=0
while c<=n:
if c%2==0:
sum_even=sum_even+c
else:
sum_odd=sum_odd+c
c+=1
print(“the sum of even integers is”, sum_even)
print(“the sum of odd integers is”, sum_odd)
Practice Programs:
Q.1 WAP to print the even numbers between 1 and 30;
Q.2 WAP to print the odd numbers between 1 and 30;
Q.3 WAP to print the following series 1, 4, 7, 10, 13, 16, 19.
Q.4 WAP to print the following series 1, 8, 27, 64, 125.
Q.5 WAP to find and print the sum of 1 to 10 natural numbers.
Q.6 WAP to find and print the sum of odd numbers between 1 to 20 .
Q.7 WAP to find and print the sum of even numbers between 1 to 20 .
Q.8 WAP to find and print the sum of numbers that are divisible by 3 between 1 to 20 .
Q.9 WAP to find and print the average of 1 to 10 natural numbers.
Q.10 WAP to find and print the average of all even numbers between 1 to 20.
Q.11 WAP to print Fibonacci series: 0,1,1,2,3,5,8,13,21.
Q.12 WAP to enter a number and check if it a prime number or not.
Q. 13 WAP to accept a number and check whether it is an Armstrong number or not.
(Example: 371 is an Armstrong Number: 3**3 + 7**3 +1**3=371)
Q.14 WAP to accept a number and display whether he number is a Palindrome or not.
Q.15 WAP that accept a number from the user and print the sum of its digits.
Nested Loop:
A loop within a loop is known as nested loop.
Or
A loop that contains another loop in its body is known as nested loop.
Syntax:
for <var> in sequence:
for <var> in sequence: Body of Outer Loop
Body of Inner Loop
Example1: Write a program to print the following pattern:
for r in range(1,6): $$$$$
$$$$$
for c in range(1,6): $$$$$
print("$",end=' ') $$$$$
print() $$$$$
Example2: Write a program to print the following pattern:
for r in range(1,6): $
$$
for c in range(1,r+1): $$$
print("$",end=' ') $$$$
print() $$$$$
Example3: Write a program to print the following pattern:
for a in range(1,6): 1
12
for b in range(1,a+1): 123
print(b ,end=' ') 1234
print() 12345
Example4: Write a program to print the following pattern:
for a in range(1,6): 1
22
for b in range(1,a+1): 333
print(a ,end=' ') 4444
print() 55555
Example5: Write a program to print the following pattern:
for r in range(5,0,-1): 55555
4444
for c in range(r, 0,-1): 333
print(r ,end=' ') 22
print() 1
Example6: Write a program to print the following pattern:
for r in range(5,0,-1): 12345
1234
for c in range(1, a+1): 123
print(c ,end=' ') 12
print() 1
Example7: Write a program to print the following pattern:
p=1
for a in range(1,6): 1
23
for b in range(1,a+1): 456
print(p,end=' ') 7 8 9 10
p+=1 11 12 13 14 15
print()
Example8: Write a program to print the following pattern:
ch=65 A
for r in range(1,6): B C
for c in range(1, r+1): D E F
G H I J
print(chr(ch),end=' ') K L MNO
ch=ch+1
print()
Example9: Write a program to print the following pattern:
ch=65 A
for r in range(1,6): BB
for c in range(1, r+1): CCC
DDDD
print(chr(ch),end=' ') EEEEE
print()
ch=ch+1
Example9: Write a program to print the following pattern:
ch=65 A
for r in range(1,6): C C
for c in range(1, r+1): E E E
G G GG
print(chr(ch),end=' ') I I I I I
print()
ch=ch+2
Jump Statements:
Loop statement allows a user to program and repeat task efficiently. In certain
situations, when some particular condition occurs, a user may want to exit from
a loop or skip some statement of the loop before continuing further in the loop.
These requirements can be taken care of by use of break and continue
statements.
break Statement
The break statement terminates the current loop, i.e. the loop in which it appears
and resumes execution at the next statement immediately after the end of that
loop. If break statement is inside a nested loop (loop within a loop), break
terminate the innermost loop.
Syntax:
for var in sequence:
if (condition):
break
# statement(s) inside for loop
# statement(s) outside for loop
Example 1:
print("my string is :-> Delhi Public School")
for a in "Delhi Public School":
if (a=="P"):
break
print(a)
print("\'Public School\' skipped")
Output :
my string is :-> Delhi Public School
D
e
l
h
i
'Public School' skipped
Example 2:
num=0
for num in range(1,10):
if(num==5):
break
print("Num has value", num)
print("Break encountered")
Output
Num has value 1
Num has value 2
Num has value 3
Num has value 4
Break encountered
Example 3:
Find the sum of all the positive numbers entered by the user. As soon as the user
enters a negative, it stops taking any more numbers from the user and display
the sum.
num=sum=0
print("Enter positive numbers to sum or negative number to end")
while True:
num=int(input(“ENTER THE NUMBER:”))
if num<0:
break
sum+=num
print("sum is:",sum)
Output:
Enter positive numbers to sum or negative number to end
23
44
33
55
66
-10
sum is: 221
continue Statement:
When a continue statement is encountered, the control jumps to the beginning
of the loop for next iteration, thus skipping the execution of the statements inside
the body of the loop for the current iteration.
Syntax:
for var in sequence:
# statement(s) inside for loop
if (condition):
continue
# statement(s) inside for loop
# statement(s) outside for loop
Example1:
print("my string is :-> Save Water")
for val in "Save Water":
if (val=="a"):
continue
print(val)
Output :
my string is :-> Save Water
S
v
e
W
t
e
r
pass Statement:
The pass statement is used when a statement is required syntactically but you do
not want any command or code to execute. Suppose, we have a loop or a function
that is not implemented yet, but we want to implement it in future. They cannot
have an empty body. The interpreter would complain. So, we use the pass
statement to construct a body that does nothing.
Syntax
pass
Example:
L=[1,2,3,4,5,6]
for val in L:
pass
Output:
>>>