0% found this document useful (0 votes)
34 views12 pages

04-1 (Selection) Part 1

sgfnzsfn

Uploaded by

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

04-1 (Selection) Part 1

sgfnzsfn

Uploaded by

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

Python Conditional Statements: ( if , if else, elif )

Conditional statements in Python are used to make decisions in your code based on certain
conditions. The primary conditional statements in Python are "if," "else," and "elif" (short for
"else if"). These statements allow you to control the flow of your program based on whether
certain conditions are met.

1- if Statement
The "if" statement is used to execute a block of code only if a specified condition is true. If the
condition is false, the code block is not executed.

Syntax
if condition:
# Code to execute if the condition is true

Example: check if a number is positive


# Input a number from the user
Enter a number: 29
number = float(input("Enter a number: "))
The number is positive.
# Check if the number is positive

if number > 0:
print("The number is positive.")
2- if else Statement
if else statement is used for decision-making operations. It contains a body of code which runs
only when the condition given in the if statement is true. If the condition is false, then the
optional else statement runs which contains some code for the else condition. When you want
to justify one condition while the other condition is not true, then you use Python if else
statement.

Syntax
if condition:
# Code to execute if the condition is true
else:
# Code to execute if the condition is false

Example: check whether a number is even or odd.


# Input a number from the user
number = int(input("Enter a number: ")) Enter a number: 17
17 is an odd number.
# Check if the number is even or odd
if number % 2 == 0:
print(f"{number} is an even number.")
else:

print(f"{number} is an odd number.")

In this code:
1- The user is prompted to enter a number using the input() function.
2- The entered value is converted to an integer using int().
3- We use an "if" statement to check if the number is even. This is done by using the modulo
operator % to check if the remainder of the division by 2 is equal to 0. If it is, the number is even,
and the first print statement is executed.
4- If the number is not even, the "else" statement is executed, and it prints that the number is
odd.
Example: determine whether a person is eligible to vote based on their age.
# Input the age of the person Enter your age: 41
age = int(input("Enter your age: ")) You are eligible to vote.

# Check if the person is eligible to vote


if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")

In this example:
1- The user is prompted to enter their age using the input() function.
2- The entered value is converted to an integer using int().
3- We use an "if" statement to check if the person's age is greater than or equal to 18, which is
the legal voting age in many countries. If the condition is true, it prints "You are eligible to vote."
4- If the age is less than 18, the "else" statement is executed, and it prints "You are not eligible
to vote."

Example: check whether a number is positive or negative.


x = -2 x is negative
if x > 0:
print("x is positive")
else:
print("x is negative")

Example: write a program to enter your mark then check the student mark if "Pass" or
"Fail" :
m = int(input("Enter your mark : "))
Enter your mark : 55
if(m >=50): Pass
print("Pass")
else:
Enter your mark : 45
print("Fail") Fail
3- elif Statement
You can also use elif (short for "else if") to add additional conditions to the statement. The
"elif" statement is used to specify multiple conditions in a sequence. It is used after an initial
"if" statement. If the "if" condition is false, the program checks the "elif" conditions one by one
until it finds a true condition or reaches the "else" block.

Syntax
if condition1:
# Code to execute if condition1 is true
elif condition2:
# Code to execute if condition2 is true
else:
# Code to execute if neither condition1 nor condition2 is true

Example: check if a number is positive, negative or zero.


# Input a number from the user
Enter a number: 124
number = float(input("Enter a number: "))
The number is positive.
____________________
# Check if the number is positive or negative
Enter a number: -67
if number > 0:
The number is negative.
print("The number is positive.")
elif number < 0:
print("The number is negative.")

else:
print("The number is zero.")

In this example:
1- The user is prompted to enter a number using the input() function.
2- The entered value is converted to a floating-point number using float().
3- We use an "if" statement to check if the number is greater than 0. If it is, it prints "The number
is positive."
4- If the number is not greater than 0, we use an "elif" statement to check if it's less than 0. If it
is, it prints "The number is negative."
5- If neither the "if" nor "elif" conditions are met, the "else" statement is executed, and it
prints "The number is zero."
Example:
age = 16

if age < 18:


print("You are a minor.") You are a minor.
elif age == 18:
print("You just turned 18.")
else:

print("You are an adult.")

In this example, the value of the age variable is set to 16, the code first checks if age is less than
18. If true, it prints "You are a minor." If not, it checks if age is exactly 18, and if so, it prints "You
just turned 18." If neither condition is met, it goes to the "else" block and prints "You are an
adult."

Short hand if else (Ternary operators)


In Python, you can use a shorthand one-liner for an "if" statement, often referred to as a
"conditional expression" or "ternary operator." It has the following syntax:

Syntax
value_if_true if condition else value_if_false

Example:
#################################################
# short hand if else: one line if else statement
# Ternary operators B
#################################################
a = 7
b = 33
print ("A") if (a>b) else print("=") if a==b else print ("B")

1- The first condition is a > b, which checks if a is greater than b. If this condition is true,
it will print "A."

2- If the first condition is false, it moves to the second condition, a == b, which checks if a is

equal to b. If this condition is true, it will print "=" (an equal sign).

3- If both of the previous conditions are false, it goes to the last part of the expression, which
prints "B."
the equivalent code using "if-elif-else"
a = 7
b = 33
if (a>b):
print("A") B
elif a==b:
print("=")
else :
print ("B")
In this code, we first check if a is greater than b. If it is, we print "A." If not, we move on to the
elif statement and check if a is equal to b. If they are equal, we print "=" (equal). If neither of
these conditions is met, we use the else statement to print "B."

With the values a = 7 and b = 33, the code will print "B" because neither the "if" nor the
"elif" conditions are true in this case.

Python Nested if Statement:


In Python, you can use nested "if" statements to create a hierarchy of conditions. This allows
you to check multiple conditions in a structured way. The inner "if" statement is placed inside
another "if" or "if-else" statement.

Syntax
if condition1:
# Code to execute if condition1 is true
if condition2:
# Code to execute if both condition1 and condition2 are true
else:
# Code to execute if condition1 is true, but condition2 is false
else:
# Code to execute if condition1 is false

The inner "if" statement can have its own "elif" and "else" clauses, creating a more complex
decision-making process.
x = 20
y = -5

if x > y:
print("x is greater than y") x is greater than y
if x % 2 == 0: x is even
print("x is even")
else:
print("x is odd")
else:
print("y is greater than or equal to x")
In this example, the outer "if" statement checks if x is greater than y. If that's true, it prints "x
is greater than y." Then, there's a nested "if" statement that checks if x is even. If it is, it prints
"x is even"; otherwise, it prints "x is odd." If the outer "if" condition is not true, it prints "y is
greater than or equal to x."

Nested "if" statements are useful when you need to make decisions based on multiple
conditions or when you want to check conditions in a hierarchical manner.

Example: categorize a student's exam score into different grades:


score = 85

if score >= 90:


grade = "A"
if score >= 95:
grade += "+"
elif score >= 80:
grade = "B"
Your grade is B+
if score >= 85:
grade += "+"
elif score >= 70:
grade = "C"
if score >= 75:
grade += "+"
elif score >= 60:
grade = "D"
else:
grade = "F"

print(f"Your grade is {grade}")

Example: if a statement without indentation will raise an error


a=33
b=200
if (b > a) : IndentationError
print(b,"is greater than ",a)

Example: Write a single if statement that examines the student's mark if "Passed"?
mark =int(input( "Enter your mark : ")) Enter your mark : 40
if ( mark >=50 ):
print("Passed")

Enter your mark : 75

Passed
Example: Enter two integer numbers and check the relationships that satisfy them.
hint: use relational and equality operators

x=int(input("Enter first number: "))


Enter first number: 8
y=int(input("Enter second number: "))
Enter second number: 6
if ( x >y ):
8 is greater than 6
print(f"{x} is greater than {y}")
8 is greater than or equal
if ( x <y ):
to 6
print(f"{x} is less than {y}")
8 is not equal to 6
if ( x >=y ):
print(f"{x} is greater than or equal to {y}")
if ( x <=y ):
print(f"{x} is less than or equal to {y}")

if ( x ==y ):
print(f"{x} is equal to {y}")
if ( x !=y ):
print(f"{x} is not equal to {y}")

Example: Trace the following programs and show what will be the output?
x, y = 2, 8
x is less than y
if (x < y):
st = "x is less than y"
print(st)

Example: What is the output of the following program?


a=33
b=200 200 is greater than 33
if (b > a) :
print(b,"is greater than ",a)

Example: What is the output of the following program?


a=323
b=200

if (b > a) :
print(b,"is greater than ",a) 200 is less than 323

elif (b==a):
print(b,"is equal to ",a)

elif (b < a ):
print(b,"is less than ",a)
Example:
a=200
b=33
c=500 Both conditions are true
if (a>b)and(c>a):
print("Both conditions are true")

Example:
a=200
b=33 At least one of the conditions is true
c=500
if ( a > b ) or ( c > a ):
print("At least one of the conditions is true")

Example:

x = 41

if x > 10:
print(x," is greater than 10") 41 is greater than 10
if x > 20: and 41 is greater than 20
print("and", x ," is greater than 20 ")
else:
print("but", x," is not greater than 20")
else:
print(x," is less than or equal to 10")

Example: using pass


a = 33
b = 200

if b > a:
pass # pass is a statement that does nothing.
else:
print(" Goodbye")

Example:
x = 5
y = 10

if x < y:
print("x is less than y")
x is less than y
if x == 5:
x is equal to 5
print("x is equal to 5")
else:
print("x is not equal to 5")
else:
print("x is greater than or equal to y")
Example:
x, y = 8, 4

if (x < y):
st = "x is less than y" x is less than y
else: x is equal to 5
st = "x is greater than y"
print(st)

Example:

x, y = 8, 8

if (x < y):
st = "x is less than y"
x is same as y
elif (x == y):
st = "x is same as y"

else:
st = "x is greater than y"
print(st)

Example 4:
x,y = 10,8
st = "x is less than y" if (x < y) else "x is greater than or equal to y"
print(st)
x is greater than or equal to y

Example:
var2 = 200
if (var2 == 500): print("Hello World!")
Equal
if (var2 > 200): print('Python1') 40.0
if (var2 != 200): print('Python2') 200

if (var2 == 200): print('Equal') ; print(var2 / 5); print(var2)


Exercise: What is the output of the following program?
avg = 77
if ( avg <50 ):
print ("Poor")
if (avg>=50 and avg <68 ):
print(" Fair ")
if (avg>=68 and avg <76 ):
print("Good")
if (avg>=76 and avg <84 ):
print("very Good")
if (avg >= 84 and avg <= 100):
print("Excellent")
else :
print ("Please , Enter mark between 0 and 100 ")

Exercise: What is the output of the following program?


avg = 77
if ( avg <50 ):
print ("Poor")
elif (avg>=50 and avg <68 ):
print(" Fair ")
elif (avg>=68 and avg <76 ):
print("Good")
elif (avg>=76 and avg <84 ):
print("very Good")
elif (avg >= 84 and avg <= 100):
print("Excellent")
else :
print ("Please , Enter mark between 0 and 100 ")

Exercise: What is the output of the following program?


#if statement
var1=200
if (var1==200):
print('Equal')
print(var1/5)
print(var1)
quote="Knowledge is power"
print(quote)
if (var1<100):
print ("Less than")
print (var1)
else:
print ('Equal or greater than')
print(quote)
Exercise: What is the output of the following program?
total = 50
#country = "US"
country = "US"
if country == "US":
if total <= 50:
print("Shipping Cost is $50")
print("payment")
elif total <= 100:
print("Shipping Cost is $25")
elif total <= 150:
print("Shipping Costs $5")
else:
print("FREE")
if country == "AU":
if total <= 50:
print("Shipping Cost is $100")
else:
print("FREE")

Exercise: write a program to enter your test result, then print the equivalent char
90-100 A

80-89 B

70-79 C

60-69 D

0-59 F

Exercise: Write a program to do the following :


1- Read three marks from the user
2- Compute the average of the three marks
3- Determine the ranking based on the average according to the following cases :

avg < 35 or avg > 100 → Error


35<= avg <= 49 → Fail
50<= avg <= 67 → Accepted
68<= avg <= 75 → Good
76<= avg <= 84 → Very Good
85<= avg <= 100 → Excellent
4- Display the average and ranking.

You might also like