If and Inline If

 The if statement is one of the most commonly used control flow statements. It allows the program to evaluate if a certain condition is met, and to perform the right action based on the result of it. 


Example

user_input = input("e or h? ")


if user_input == "e":

    print("E is a pretty good letter.")

    print("it was memed a lot back in the day")

elif user_input == "h":

    print("the letter H is superior and has a lot of the funnies")

else: print("you didn't enter any of the two letters you dingus")


The program will first prompt to enter either letters. When input is entered, it is stored in the variable user_input as a string. Since it is stored as a string, the answer will depend on what letter case is used; i.e. if either of the letters are entered in uppercase, it will jump to printing the string "you didn't enter any of the two letters you dingus" since the program will only accept either of the letters in lowercase. If correct input "e" is entered, the statement if user_input == "e": compares user_input with the string "e". If e is entered, the program will execute the strings "E is a pretty good letter." and "it was memed a lot back in the day". If h is entered, it will print the string "the letter H is superior and has a lot of the funnies". For other values it will print "you didn't enter any of the two letters you dingus".


There is also a simpler form of an if statement and is called an inline if statement.


Example

print("E!!!!!!!!!" if e == 15 else "h")

The program will print the string "E!!!!!!!!!" if the variable e equals to 15. Else, it will print the string "h".


No comments:

Post a Comment