Python IF statements

Python IF statements

 

 

An if statement is a programming conditional statement that, if proved true, performs a function or displays information. For example in the code below if the score entered is over 90 you get an A*, if it is over 80 you get a grade A. If the score is under 60 you fail.

Task

  • Run the program below and check that this works.
  • See if you can extend the code to allow for grades D-F.
  • See if you can improve the code to prevent errors if the wrong type of data is entered (i.e. text data, float numbers, numbers over 100). This is called validation, if you need help look at the if statements used on some of the python challenge pages.
  • Build an if statement yourself that asks a person to enter their age. Then display different messages depending on whether or not they would be too young for school, at primary school, at secondary school, too old for school or retired.

 

score=int(input("Enter your score: "))
if score>90:
    print("Grade A*")
elif score>80:
          print("Grade A")
elif score>70:
          print("Grade B")
elif score>60:
          print("Grade C")
else:
          print("Fail")

 

Next: Look again at the python challenges to see differnet applications of IF statements. Continue developing your code on the python challenge you were working on.

Ext: The python ideas page gives you problems to work on but no code to edit. You need to try to work these problems out for yourself!