Python M1
Python M1
(21CSE6044)
Ms. Anusha
CSE Dept
SJEC
Definition:
• Python is a computer programming language
often used to build any website and software.
Modes
• We can run the program in two different modes:
▫ Interactive mode
▫ Script mode
Interactive mode
Output/Result:
num is lesser than 20
If else
num=30
if num<20:
print("num is lesser than 20")
else:
print("num is greater than 20")
Output/Result:
num is greater than 20
If elif else
num=20
if num<20:
print("num is lesser than 20")
elif num>20:
print("num is greater than 20")
else:
print("num is equal to 20")
Output/Result:
num is equal to 20
Looping statement
• for loop and range() function
for loop: if you want to execute a block of code a
certain number of times for is used
range() function returns a sequence of numbers
• Print hello 5 times
print(“hello”)
print(“hello”)
print(“hello”)
print(“hello”)
print(“hello”)
Output/Result: 0 1 2 3 4 5 6 7 8 9
Print numbers from 1 to 9
• 2 parameter
Syntax:
for i in range(start, stop):
print(i)
Example:
for i in range(1, 10):
print(i)
Output/Result: 1 2 3 4 5 6 7 8 9
Print numbers from 1 to 9 with jumping range 2
• 3 parameter
Syntax:
for i in range(start, stop, jump):
print(i)
Example:
for i in range(1, 10, 2):
print(i)
Output/Result: 1 3 5 7 9
• Print numbers in the reverse order
for i in range(10,0,-1):
print(i)
import random
#for i in range(5):
print(random.randint(1, 10))
Note: Includes 1 and 10
While loop
• The code in a while clause will be executed as
long as the while statement’s condition is True.
• spam = 0
while spam < 5:
print('Hello world.')
spam = spam + 1
print(“end of program”)
Output/Result
Hello world
Hello world
Hello world
Hello world
Hello world
End of program
Example2:
countdown = 10
while countdown > 0:
print(countdown)
countdown =countdown- 1
print("Blast off!")
Break statement and Continue
statement
• Both are used inside the looping statement
break
• count = 1
while count <= 5:
print(count)
count = count+1
if count == 3:
break
print("Hi")
print("end of program")
continue
• count = 1
while count <= 5:
print(count)
count = count+1
if count == 4:
continue
print("Hi")
print("end of program")