0% found this document useful (0 votes)
23 views38 pages

Unit2L1 2 3

Uploaded by

mohitlpu739811
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views38 pages

Unit2L1 2 3

Uploaded by

mohitlpu739811
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 38

Unit 2

Lessons 1,2 and 3


Python provides special constructs to control the execution of one or more statements
depending on a condition. Such constructs are called as control statements or control-flow
statements.

The control-flow statements are of three types:


The general syntax of if statement in Python is,
If test expression:
statement(s)

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

B. a and b are equal.

C. a and b are equal a and b are not equal

D. a and b are not equal.


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

B. a and b are equal.

C. a and b are equal a and b are not equal

D. a and b are not equal.


Practice Questions

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.

syntax for the if-else statement :


if(expression): if x%2 == 0:
body of If
print (x, “is even”)
else:
else:
body of else
print (x, “is odd”)
The alternatives are called branches.
Since the condition must be true or false, exactly one of the alternatives will be executed.
The alternatives are called branches, because they are branches in the flow of execution.
Write a program to check whether the marks obtained by the student got
distinction or not. Take marks as input from the user which of type int.

Follow the below conditions while writing the program.


• If marks > distinction _marks print the message as User secured distinction
• Otherwise print the message User did not secure distinction
Print the result to the console as shown in the examples.
Solution:
distinction_marks = 75
# write your code here
marks=int(input("Enter marks obtained: "))
if(marks>distinction_marks):
print("User secured distinction")
else:
print("User did not secure distinction")
Take an integer as input from the console using input() function.
Write a program to check the given input amount is greater or less
than the minimum balance.

Follow the given instructions while writing the program and print
the output as shown in the example.

Assume minimum balance is 1000


• If input >= 1000 print Sufficient balance
• Otherwise the message should print on the console is Balance is
Low
Solution:

balance=int(input("Enter balance in your account: "))


if(balance>=1000):
print("Sufficient balance")
else:
print("Balance is low")
Both are correct, but b is better as condition is tested only once

Practice Programs:

1. Write a program that checks if a student has passed or failed an exam


2. Create a program that takes an integer as input and determines if it is odd or even
3. Create a program that checks if a person is eligible to drive
4. Write a program that checks a bank account balance before withdrawal: Accept the current balance and
the withdrawal amount as input. If the withdrawal amount is less than or equal to the balance, print
"Transaction successful“ Else, print "Insufficient funds"
5. Create a program that checks if a given day is a weekend or a weekday.
6. Write a program that checks if a given letter is a vowel or a consonant
7. Create a program that gives advice based on the weather condition: Accept the weather
condition (like "rainy", "sunny", "cloudy") as input. If it's "rainy", print "Take an umbrella” Else,
print "Enjoy your day!"
8. Create a program to check if a user can access the library: Accept the user's membership
status (like "member" or "non-member") as input. If the user is a "member", print "Access
granted” Else, print "Access denied“
9. Create a program that greets the user based on the time of day: Accept the hour (in 24-
hour format) as input.
If the hour is less than 12, print "Good morning“ Else, print "Good afternoon".
10. Create a program that classifies a person into an age group: Accept a person's age as input.
If the age is less than 13, print "Child” Else, print "Teenager or Adult".
Write a program to calculate the income tax as follows
Step 1: get all deductions (80c, 80cc, HRA, Medical)
Step 2: Add all the deductions to standard deduction 150000
Step 3: Get Gross Income
Step 4: Get taxable income (as Gross Income - Deductions)
Step 5: Calculate Income Tax based on taxable income as follows
Solution:
# Deductions
Ded_std = 150000
# Request Inputs
Ded_80c = int(input("Enter Amount to be deducted under 80c: "))
Ded_80cc = int(input("Enter Amount to be deducted under 80cc: "))
Ded_hra = int(input("Enter Amount to be deducted under HRA: "))
Ded_med = int(input("Enter Amount to be deducted under Medical: "))
Gross_Income = int(input("Enter Gross Income: "))
Ded_tot = (Ded_std + Ded_80c + Ded_80cc + Ded_hra + Ded_med)
Tax_Income = Gross_Income - Ded_tot
# complete the missing code
if (Tax_Income > 0):
if (Gross_Income <= 500000):
Income_Tax = (Tax_Income * 0.1)
if (Gross_Income <= 1000000) and (Gross_Income > 500000):
Income_Tax = 25000 + ((Gross_Income - 500000)*0.2)
if (Gross_Income > 1000000):
Income_Tax = 75000 + ((Gross_Income - 1000000) *0.3)
print ("Gross Income is" ,Gross_Income)
print ("Total Deductions =",Ded_tot)
print ("Income Tax =",Income_Tax)
else:
if-elif-else Structure
if Statement:
• The if statement checks a condition.
• If the condition evaluates to True, the code block under the if statement is executed.
• If the condition evaluates to False, the program moves to the next elif (if any).
elif Statement (short for "else if"):
• You can have multiple elif statements after an if to check additional conditions.
• If the if condition is False, the elif condition is checked next.
• If the elif condition is True, the code block under that elif is executed.
• If elif is False, the program moves to the next elif (if any).
else Statement:
• The else block is optional and can be used as a "catch-all."
• If none of the preceding if or elif conditions are True, the else block will be executed.
Example:
temperature = 25
if temperature > 30:
print("It's hot outside.")
elif temperature > 20:
print("It's warm outside.")
elif temperature > 10:
print("It's cool outside.")
else:
print("It's cold outside.")
if-elif-else

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

Multi-way if-elif-else statement to assign a grade.


What is the output of the following?

if (10 < 0) and (0 < -10): A: A


print("A") B: B
elif (10 > 0) or False: C:C
D: Error
print("B")
else:
print("C")
Predict output of the following python program.
a, b, c = 5, 1, 15

if (a < b) and (a < c):


print("A is minimum") A: A is minimum
elif (b < a) and (b < c): B: B is minimum
print("B is minimum") C:C is minimum
else: D: Error
print("C is minimum")
Important Points:

• 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.

• Indentation is used for each of the if-elif-else blocks


if vs. if-elif-else:

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.

1 - 100 unit - 1.5/-


101-200 unit - 2.5/-
201-300 unit - 4/-
300 - 350 unit - 5/-
above 350 - 15 /-

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.

if bmi < 18.5


print("Underweight")
bmi = weightInKilograms / (heightInMeters * heightInMeters)
if bmi < 25
print("Normal")
if bmi < 30
print("Overweight")
else
print("Obese")
3. Suppose you shop for rice and find it in two different sized packages. You would like to
write a program to compare the costs of the packages. The program prompts the user to
enter the weight and price of each package and then displays the one with the better
price. Here is a sample run:

4. Write a Python program to check a triangle is equilateral, isosceles or scalene.

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

if pricePerKilo1 > pricePerKilo2:


print("Package 1 has the better price.")
elif pricePerKilo2 > pricePerKilo1:
print("Package 2 has the better price.")
else:
print("Both have a good price")
Solution 4
x,y,z=eval(input("Enter three sides:"))
# _Check for equilateral triangle
if x == y == z:
print("Equilateral Triangle")

# Check for isosceles triangle


elif x == y or y == z or z == x:
print("Isosceles Triangle")

# Otherwise scalene triangle


else:
print("Scalene Triangle")

You might also like