An If statement is used to decision in the program depending on different variables, it allows selection to take place.
First off lets get some input from the user that we can use in the if statement. I will do it in the context of test grades.
score = int(input("Please enter your score out of 100: "))
We now have the user score stored in the variable "score" as an integer.
Now lets look at the operators for a if statement.
- == Is used for equal to.
- <= Is used for less than or equal to.
- >= Is used for greater than or equal to.
- != Is used for not equal to.
- and can be used for 2 comparisions.
if ( score >= 90 ):
print("A")
elif ( score >= 80 and score < 90 ):
print("B")
elif ( score >= 70 and score < 80 ):
print("C")
elif ( score < 70 ):
print("Fail")
Now if we run this code with the score as 85 it should print out a "B" to the screen.
No comments:
Post a comment