Unit2L1 2 3
Unit2L1 2 3
Example:
If x > 0:
print ("x is positive“)
Note:
The if-construct is a selection statement, the statements within the block are executed only once when the
condition evaluates to True, Otherwise the control goes to the first statement after the if-construct.
• In Python, the body (block of statements) of the If statement is indicated by indentation.
• Python interprets non-zero values as True. None and 0 are interpreted as False.
Take an integer as input from the console using input() function. Write a program to
check the given integer is divisible by 7 or not, print the result to the console as shown
in the examples.
Case 1
Sample Input and Output 1:
Enter a number: 77
Given number 77 is divisible by 7
End of program
Case 2
Sample Input and Output 2:
Enter a number: 40
End of program
Solution:
#Program to illustrate simple if statement
num = int(input("Enter a number: "))
if(num%7==0):
print("Given number {} is divisible by {}".format(num,7))
print("End of program")
Select the correct output for the below Python code?
a = 27
b = 27.0
if(a == b):
print("a and b are equal")
if(a != b):
print("a and b are not equal")
A. Interpreter Error
A. Interpreter Error
1. Write a program that prints "It's too hot!" if the temperature is greater than 30 degrees.
2. Create a program that prints "Warning: Low Balance" if a bank account balance is below
$100.
3. Write a program that prints "Eligible for voting" if a person's age is 18 or older.
4. Write a Python program that prints "Discount applicable!" if the total purchase amount is
more than $50.
5. Write a program that prints "The number is odd" if a given integer is not divisible by 2.
6. Write a Python program that prints "Positive number" if a given number is greater than 0.
7. Write a program that prints "The number is even" if a given integer is divisible by 2.
8. Write a program that prints "It's the weekend!" if today is Saturday or Sunday.
9. Write a program that prints "Freezing Point Reached!" if the temperature is exactly 0
degrees.
10. Create a program that prints "Congratulations! You are eligible for promotion." if an
employee has worked more than 5 years in the company.
if-else statement
The if-else statement provides two different paths of execution depending on the result of
the condition. The body of if is executed when the condition associated with the expression
is true.
Follow the given instructions while writing the program and print
the output as shown in the example.
Practice Programs:
The if-elif-else construct extends the if-else construct by allowing to chain multiple if constructs as shown
below:
if x < y:
if test expression:
body of if print (x, "is less than", y)
elif test expression: elif x > y:
body of elif
elif test expression: print (x, "is greater than", y)
body of elif
...
else:
elif test expression: print (x, "and", y, "are equal“)
body of elif
else:
body of else
Example to understand if-elif-else
• The if elif else construct is used when we have multiple mutually exclusive
expressions.
• If the condition for if is false, then the condition for the next elif is evaluated and so
on upto the next elif.
• If all the conditions are false, then the body of else is executed.
• Only one block among if elif else blocks is executed based on the condition.
• The if block can have only one else block, but it can have multiple elif blocks.
Multiple if Statements:
When you use multiple if statements, each condition is evaluated independently.
The program will check every single if statement, even if one of the previous if
conditions is already True.
This means that multiple if blocks can be executed if more than one condition is True.
if-elif-else Structure:
The if-elif-else structure is a chain of conditions where only one block is executed.
Once an if or elif condition is found to be True, the corresponding block of code is
executed, and the rest of the conditions are skipped.
The else block, if present, is executed only if none of the preceding if or elif conditions
are True.
This means only one block of code will run in an if-elif-else chain.
Using multiple if
x = 15
if x > 10:
print("x is greater than 10.") # This will execute.
if x > 5:
print("x is also greater than 5.") # This will also execute.
if x > 20:
print("x is greater than 20.") # This will not execute.
Using if-elif-else
x = 15
if x > 10:
print("x is greater than 10.") # This will execute.
elif x > 5:
print("x is greater than 5.") # This will not execute.
elif x > 20:
print("x is greater than 20.") # This will not execute.
else:
print("x is 5 or less.") # This will not execute.
Take character as input from the console using input() function.
Write a program to check whether the given input is a character or
a digit, if the input is 0 exit the program, otherwise print the result
to the console as shown in the examples
Solution:
print("Enter '0' for exit.")
ch=input("Enter any character: ")
if ch == '0':
exit()
elif(ch>='A' and ch<='Z'):
print("Given character {} is an alphabet".format(ch))
elif(ch>='a' and ch<='z'):
print("Given character {} is an alphabet".format(ch))
elif(ch>='1' and ch<='9'):
print("Given character {} is a digit".format(ch))
else:
print("{} is not an alphabet nor a digit".format(ch))
Take an integer num as input from the console using input() function.
Write a program to check the given num is a positive or
a negative one, print the result to the console as shown in the
examples.
Solution:
number=int(input("Enter a number: "))
if(number==0):
print("Zero")
elif(number>0):
print("Positive number")
else:
print("Negative number")
Take an integer year as input from the console using input() function. Write a
program to check the given year is a leap year or not, print the result to the console
as shown in the examples.
Solution:
year=int(input("Enter a year: "))
if(year%4==0 and year%100!=0):
print("{} is a leap year".format(year))
elif(year%400==0):
print("{} is a leap year".format(year))
else:
print("{} is not a leap year".format(year))
Practice Programs:
1. Write a program to calculate the electricity bill, we must understand electricity charges and rates.
2. Write a program that prompts the user to enter a weight in pounds and height in inches and then displays the BMI.
Note that one pound is 0.45359237 kilograms and one inch is 0.0254 meters. Use ladder if concept.
Note :An equilateral triangle is a triangle in which all three sides are equal.
A scalene triangle is a triangle that has three unequal sides.
An isosceles triangle is a triangle with (at least) two equal sides.
Solution 1
units=int(input("Enter number of units:"))
if (units <= 100):
bill= units * 1.5
elif (units <= 200):
bill=((100 * 1.5) +(units - 100) * 2.5)
elif (units <= 300):
bill=((100 * 1.5) +(100 * 2.5) +(units - 200) * 4)
elif (units <= 350):
bill=((100 * 1.5) +(100 * 2.5) +(100 * 4) +(units - 300) * 5)
elif (units>350):
bill = ((100 * 1.5) + (100 * 2.5) + (100 * 4) + (50 * 5)+((units - 350) * 15))
print("Electricity bill is:",bill)
Solution 2
# Prompt the user to enter weight in pounds
weight = eval(input("Enter weight in pounds: "))
# Prompt the user to enter height in inches
height = eval(input("Enter height in inches: "))
KILOGRAMS_PER_POUND = 0.45359237 # Constant
METERS_PER_INCH = 0.0254 # Constant
# Compute BMI
weightInKilograms = weight * KILOGRAMS_PER_POUND
heightInMeters = height * METERS_PER_INCH
bmi = weightInKilograms / (heightInMeters * heightInMeters)
# Display result
print("BMI is", format(bmi, ".2f"))
if bmi < 18.5:
print("Underweight")
elif bmi < 25:
print("Normal")
elif bmi < 30:
print("Overweight")
else:
print("Obese")
Solution 3
w1, p1 = eval(input("Enter weight and price for package 1: "))
w2, p2 = eval(input("Enter weight and price for package 2: "))
pricePerKilo1 = p1 / w1
pricePerKilo2 = p2 / w2