if else conditions | Loops

 Conditional statement:

# if else conditional statement

x = 2

# As you can see that a block is created to indentate the statement.
# if else conditional statement
if x == 1:
    print("x is 1")
else:
    print("x is not 1")

print("Outide of if conditional statement")

# if elif else conditional statement
# you can have multiple elif statements
hour = 13
if hour < 12:
    print("Good Morning")
elif hour < 18:
    print("Good Afternoon")
else:
    print("Good Evening")

Assignment:
"""
Create a variable grade holding an integer between 0 and 100.
Code if, elif, else statements to print the letter grade.
Grades:
A=90-100
B=80-89
C=70-79
D=60-69
F=0-59
If the grade is not between 0 and 100, print "Invalid grade".
"""

grade = 85

if grade >= 90 and grade <= 100:
    print("A")
elif grade >= 80 and grade <= 89:
    print("B")
elif grade >= 70 and grade <= 79:
    print("C")
elif grade >= 60 and grade <= 69:
    print("D")
elif grade >= 0 and grade <= 59:
    print("F")
else:
    print("Invalid grade")

Loops:

For and While loop usage will be shown below.
# Loops

my_list = [1, 2, 3, 4, 5]
sumofLoop = 0

for iterator in my_list:
    sumofLoop += iterator
    print(iterator)

print("Sum of loop:", sumofLoop)


for i in range(1, 10):
    print(i)

for i in range(1, 10, 2):
    print(i)

for i in range(10, 1, -1):
    print(i)

myList= ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
for i in myList:
    print(f"Happy {i}!")

# while loop
# if we don't have update condition in while loop then it will run infinite times
i = 0
while i < 10:
    i += 1
    if i == 9:
        break
    elif i == 3:
        continue
    else:
        print(i)
   
else:
    print("Loop is completed. Value of i = ",i)

print("i=",i)


Assignment:
"""
myList = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

create a while loop to prints all elements of mylist variable 3 times.

while printing the elements, us a for loop to print the elements
However, if the element of the for loop is equal to Monday, continue without printing.

"""

myList = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

i=0
while i <3:
    for day in myList:
        if day == "Monday":
            continue
        print(day)
    i += 1



Comments

Popular posts from this blog

Post Request with Pydantic usage (input validator)

Code Scalability and Routing

CRUD Assignment