MSc CF – Python
Today’s Program
- Program to check if the input number is prime or not
- Simple Calculator by using Functions
for loop
The for statement in Python has the ability to iterate over the items of any sequence, such as a list or a string.
Syntax
for iterating_var in sequence: statements(s)>>> range(5) range(0, 5)
Example
range() generates an iterator to progress integers starting with 0 upto n-1. To obtain a list object of the sequence, it is typecasted to list(). Now this list can be iterated using the for statement.
>>> for var in list(range(5)):
print (var)source: https://www.tutorialspoint.com/python3/python_for_loop.htm
#How to give user input
#Sum of two nos.
print(“Enter first no.”)
a=input()
print(“Enter second no.”)
b=input()
c=a+b
print(c)
#With format()
#Sum of two nos.
num1= input(“Enter first no. “)
num2= input(“Enter second no. “)
sum=float(num1)+float(num2)
print(“The sum of {0} and {1} is {2}”.format(num1,num2,sum))
The if statement
The if statement is used to check a condition: if the condition is true, we run a block of
statements (called the if-block), else we process another block of statements (called the
else-block). The else clause is optional.
Example (save as if.py )
number = 24
guess = int(input(“Enter an integer : “))
if guess == number:
# New block starts here
print(“Congratulations, you guessed it.”)
# New block ends here
elif guess < number:
# Another block
print(“No, it is a little higher than that”)
# You can do whatever you want in a block …
else:
print(“No, it is a little lower than that”)
# you must have guessed > number to reach hereprint(“Done”)
# This last statement is always executed,
# after the if statement is executed.
#Day of week
n=input(“Enter the day number”)
if(n==1):
print(“Sunday”)
elif(n==2):
print(“Monday”)
elif(n==3):
print(“Tuesday”)
elif(n==4):
print(“Wednesday”)
elif(n==5):
print(“Thursday”)
elif(n==6):
print(“Friday”)
elif(n==7):
print(“Saturday”)
else:
print (‘Not a valid day number’)