Labels

Arduino (1) Bugs (3) C (1) Install (3) Linux (25) Python (10) Raspberry Pi (4)

Friday, 1 July 2016

Python3:Lesson 3 If statments

If you are new to python you can check out my other lessons to get up to speed.
  1. Lesson 1
  2. Lesson 2
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.
We now need to create our if/elif statement.
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.