Monday, July 10, 2023

If, Elif, Else, For, While, Pass, Break and Continue

IF-ELIF-ELSE

If-Elif-Else is a class of statements that are known as conditional statements.

They accept a conditional expression (which we can also call as only ‘condition’ or only ‘expression’), and process a piece of code based on that.

A conditional statement evaluates to True or False.

Note: In Python, 0 is considered as False and 1 is considered as True.

IF-ELSE Statement in Code

Simple if-else program to check voter eligibility:

age = int(input("Enter your age: "))

if age >= 18:

print("Eligible to vote")

else:

print("Not eligible to vote")

# One more example

a = 9

b = 2

if a > b :

print("a is greater than b")

ELIF

We know about IF.

If the condition is met, execute the IF block.

If the condition is not met, execute the ELSE block.

But there is a third possibility: of checking a second condition if the first condition is not met.

In this case if the second condition is met (after the first condition is not met), the ELIF block executes.

ELIF Statement in Code (Part 1)

# Elif stands for "else if"

a = 33

b = 32

if b > a:

print("b is greater than a")

elif a == b:

print("a and b are equal")

else:

print(" b is less than a")

ELIF Statement in Code (Part 2)

day = input("Enter a week day's name: ")

if day == "Sunday":

print(1)

elif day == "Monday":

print(2)

elif day == "Tuesday":

print(3)

elif day == "Wednesday":

print(4)

elif day == "Thursday":

print(5)

elif day == "Friday":

print(6)

elif day == "Saturday":

print(7)

else:

print("Enter a valid day like Sunday, Monday,...")

Problem

What is the output of the following code:

var = 0

if var:

print("In If")

else:

print("In Else")

var = 1

if var:

print("In If")

else:

print("In Else")

Shorthand If-Else

# Shorthand if else statment

# This technique is known as Ternary Operators, or Conditional Expressions

a = 2

b = 330

print("A") if a > b else print("B")

Here four lines of code have been reduced to one.

For Loop

Purpose of For loop is pure iteration.

For example: if we want to print first 10 natural numbers then we would simply iterate over those numbers using the range() built-in.

Code:

#1

for i in range(1, 11):

print(i)

#2

l = ['Ashish', 'Lijiya', 'Bala']

for i in l:

print(i)

Ashish

Lijiya

Bala

Q2: Python program to print all the even numbers within the given range.

x = int(input("input range: "))

for i in range(1, x):

if i % 2 == 0:

print(i)

Q3: Write a program to read 10 numbers from the keyboard and find their sum and average.

#Write a program to read 10 numbers from the keyboard and find their sum and average.

Sum() and Average() : Way 1

l = []

for i in range(10):

l.append(int(input("Enter the number: ")))

s = sum(l)

print(s)

avg = sum(l) / len(l)

print(avg)

Sum() and Average() : Way 2 (Using statistics module)

import statistics

#Write a program to read 10 numbers from the keyboard and find their sum and average.

l = []

for i in range(10):

l.append(int(input("Enter the number: ")))

s = sum(l)

print(s)

m = statistics.mean(l)

print(m)

While Loop

While loop is an entry controlled loop.

First thing we need is a variable to control our while loop.

Second thing a while loop requires is a condition (or conditional expression).

if True:

pass

And a condition requires: a variable and some test on it that would result in True or False.

Generally:

We let our variable to start with something like: i = 1

We let our condition be something like: i < 10

Printing first ten natural numbers

For 10 natural numbers

Let: i = 1

Condition: i <= 10

Third thing is modification of variable used in the condition above.

i += 1

Three steps described here are:

1. initialization

2. condition

3. change

Infinite Loop

You can create infinite loop by manipulating these three steps of a while loop:

1. initialization

2. condition

3. change

while (True):

# Do something infinite number of times

Break: breaks out of the normal flow of the code

Continue: it skips the current iteration on encountering this keyword and continues with the next iteration.


“pass” Statement

>>> x = 5

>>> print("less than 10") if x < 10 else print("greater than or equal to 10")

less than 10

>>> x = 15

>>> print("less than 10") if x < 10 else print("greater than or equal to 10")

greater than or equal to 10

>>> x = 5

>>> if(x < 10):

... x = x + 10

... else:

... pass

...

>>> x

15

>>>

‘pass’ with ‘if-else’

passing_marks = 33

student_marks = int(input("Enter student's marks:"))

grace_marks = 10

if student_marks < passing_marks:

student_marks += grace_marks

else:

pass

print("Final marks are:", student_marks)

‘pass’ with ‘for’ loop

# Print first 20 natural numbers leaving the multiples if 5 (inc. 5).

for i in range(1, 21):

if i % 5 == 0:

pass

else:

print(i)

‘pass’ with ‘try-except’

# A question worth 3 marks was wrong in the exam. So we have to give 3+ marks to each student.

try:

student_marks = int(input("Enter the student's marks: "))

if student_marks > 97:

print("Raising exception...")

raise Exception

student_marks += 3

except ValueError as e:

# invalid literal for int() with base 10: 'alpha beta gamma'

print(e)

except Exception as e:

pass

print("Final student marks: ", student_marks)

Defining an empty class

# Defining an empty class

class Person:

pass

No comments:

Post a Comment