Search this site
Embedded Files
Python Jedi
  • Chapters
    • Fork/Clone
    • 1 Version Control
    • 2 Python Console
    • 3 Input/Output
    • 4 Conditionals
    • 5 Looping
    • 6 Num. Systems
    • 7 Graphics
    • 8 Lists/Strings
    • 9 Functions
    • Prisoner's Dilemma
    • 10 Classes
    • 11 Animation
    • 12 User Control
    • 13 Libraries/Modules
    • 14 Game Design
      • 14 Sprites
      • 14 Shooting
      • 14 Explosions
      • 14 Levels
      • 14 Aiming Trig
      • 14 Walls
      • 14 View Port
      • 14 Grids
    • 15 Data Analysis
Python Jedi
  • Chapters
    • Fork/Clone
    • 1 Version Control
    • 2 Python Console
    • 3 Input/Output
    • 4 Conditionals
    • 5 Looping
    • 6 Num. Systems
    • 7 Graphics
    • 8 Lists/Strings
    • 9 Functions
    • Prisoner's Dilemma
    • 10 Classes
    • 11 Animation
    • 12 User Control
    • 13 Libraries/Modules
    • 14 Game Design
      • 14 Sprites
      • 14 Shooting
      • 14 Explosions
      • 14 Levels
      • 14 Aiming Trig
      • 14 Walls
      • 14 View Port
      • 14 Grids
    • 15 Data Analysis
  • More
    • Chapters
      • Fork/Clone
      • 1 Version Control
      • 2 Python Console
      • 3 Input/Output
      • 4 Conditionals
      • 5 Looping
      • 6 Num. Systems
      • 7 Graphics
      • 8 Lists/Strings
      • 9 Functions
      • Prisoner's Dilemma
      • 10 Classes
      • 11 Animation
      • 12 User Control
      • 13 Libraries/Modules
      • 14 Game Design
        • 14 Sprites
        • 14 Shooting
        • 14 Explosions
        • 14 Levels
        • 14 Aiming Trig
        • 14 Walls
        • 14 View Port
        • 14 Grids
      • 15 Data Analysis

Fork/Clone Ch.04 Conditionals Jedi Training

If Statements

How do we tell if a player has beat the high score? How can we tell if he has run out of lives? How can we tell if she has the key required to open the locked door?

A program can test for these conditions with an if statement. An if statement is also known as a conditional statement if you want to impress everyone how smart you are. The if statement allows a computer to make a decision. Is it hot outside? Has the Millennium Falcon been hit by an asteroid? Has too much money been withdrawn from the account?

Basic Comparisons

Here are a few examples of if statements. The first section sets up two variables (a and b) for use in the if statements. Then two if statements show how to compare the variables to see if one is greater than the other. Create a new Python file to practice with the code in this chapter.

# Variables used in the example if statements

a = 4

b = 5


# Basic comparisons

if a < b:

    print("a is less than b")


if a > b:

    print("a is greater than b")


print("Done")


Run Output:

a is less than b

Done

Since a is less than b, the first statement will print out if this code is run. If the variables a and b were both equal to 4, then neither of the two if statements above would print anything out. The number 4 is not greater than 4, so the if statement would fail.

Flowcharting

To show the flow of a program a flowchart may be used. Most people can follow a flowchart even without an introduction to programming. 

This book skips an in-depth look at flowcharting because it is boring. But if you want to be a superstar programmer, please read more about it at: http://en.wikipedia.org/wiki/Flowchart


The prior example checked for greater than or less than. Numbers that were equal would not pass the test. To check for values greater than or equal, the following examples show how to do this:

if a <= b:

    print("a is less than or equal to b")


if a >= b:

    print("a is greater than or equal to b")


Run Output:

a is less than or equal to b

The <= and >= symbols must be used in this order, and there cannot be a space between them. For example, =<  and =>will not work.

The next set of code checks to see if two items are equal or not. The operator for equal is == and the operator for not equal is !=. Here they are in action.

# Equal

if a == b:

    print("a is equal to b")


# Not equal

if a != b:

    print("a and b are not equal")


Run Output:

a and b are not equal

It is very easy to mix up when to use == and =. Use == if you are asking if they are equal, use = if you are assigning a value. The two most common mistakes in mixing the = and == operators are demonstrated below. Please, Please, Please study the difference and have a good grasp of this concept. It will save you a lot of trouble in the future.

# This is wrong

a == 1


# This is also wrong

if a = 1:

    print("A is one")

Indentation

Indentation matters. Each line under the if statement that is indented will only be executed if the statement is true. Indentation is 4 spaces. Notice also the : at the end of the if line.

if a == 1:

    print("If a is one, this will print.")

    print("So will this.")

    print("And this.")


print("This will always print because

it is not indented.")

Indentation must be the same. This code doesn't work.

if a == 1:

  print("Indented two spaces.")

    print("Indented four. This will generate an error.")

   print("The computer will want

you to make up your mind.")

Once an if statement has been finished, it is not possible to re-indent to go back to it. The test has to be performed again.

if a == 1:

    print("If a is one, this will print.")

    print("So will this.")


print("This will always print

because it is not indented.")

    print("This will generate an error.

Why is it indented?")

***You can highlight multiple lines of code and click Tab to indent the entire section. You can also un-indent an entire section by highlighting the section and clicking Shift+Tab.

Using And/Or

An if statement can check multiple conditions by chaining together comparisons with and and or. These are also considered to be operators just like + or - are.

# And

if a < b and a < c:

    print("a is less than b and c")


# Non-exclusive or

if a < b or a < c:

    print("a is less than either b or c (or both)")

A common mistake is to omit a variable when checking it against multiple conditions. The code below does not work because the computer does not know what to check against the variable c. It will not assume to check it against a.

# This is not correct

if a < b or < c:

    print("a is less than b and c")

Boolean Variables

Python supports Boolean variables. What are Boolean variables? Boolean variables can store either a value of True or a value of False. Boolean algebra was developed by George Boole back in 1854. If only he knew how important his work would become as the basis for modern computer logic!

An if statement needs an expression to evaluate to True or False. What may seem odd is that it does not actually need to do any comparisons if a variable already evaluates to True or False.

# Boolean data type. This is legal!

a = True

if a:

    print("a is true")

The following code uses the not to flip the value of "a" between true and false. Think about it as saying, "If 'a' is not True..." which means "If 'a' is False".

# How to use the not function

if not a:

    print("a is false")

Else and Else If (Elif)

Colons are required at the end of the if and else statements. The indentation tells the Python interpreter which block of code belongs to that if or else block. Always use four spaces for each level of indentation.

Copy the following code into your editor and run it. This code will get the temperature from the user and print if it is hot.

temperature = int(input("What is the temperature in Fahrenheit? "))

if temperature > 90:

    print("It is hot outside")

print("Done")

If the programmer wants code to be executed if it is not hot, she can use the else statement. Notice how the else is lined up with the i in the if statement, and how it is followed by a colon just like the if statement.

In the case of an if...else statement, one block of code will always be executed. The first block will be executed if the statement evaluates to True, the second block if it evaluates to False.

temperature = int(input("What is the temperature in Fahrenheit? "))

if temperature > 90:

    print("It is hot outside")

else:

    print("It is not hot outside")

print("Done")

It is possible to chain several if statements together using the else...if statement. Python abbreviates this as elif.

temperature = int(input("What is the temperature in Fahrenheit? "))

if temperature > 90:

    print("It is hot outside")

elif temperature < 30:

    print("It is cold outside")

else:

    print("It is not hot outside")

print("Done")

In the code below, the program will output "It is hot outside" even if the user types in 120 degrees. FIX THIS CODE!

temperature = int(input("What is the temperature in Fahrenheit? "))

if temperature > 90:

    print("It is hot outside")

elif temperature > 110:

    print("Oh man, you could fry eggs on the pavement!")

elif temperature < 30:

    print("It is cold outside")

else:

    print("It is ok outside")

print("Done")

Text Comparisons

It is possible to use an if statement to check text.

jedi = input("Who is the greatest Jedi Master? ")

if jedi == "Yoda":

    print("Greatest, he is!")

else:

    print("Incorrect")

The prior example will only match if the user enters "Yoda". It will not work if the user enters "yoda" or "YODA".

A common mistake is to forget the quotes around the string being compared. In the example below, the computer will think that user_name is a variable that stores a value. It will flag an error because it has no idea what is stored in the variable username.

jedi = input("Who is the greatest Jedi Master? ")

if user_name == Yoda:

# The above does not work because quotes are missing

    print("Greatest, he is!")

else:

    print("Incorrect")

When comparing a variable to multiple possible strings of text, it is important to remember that the comparison must include the variable. For example:

# This does not work!

if jedi == "Yoda" or "Windu":

Instead, the code should read:

# This does work

if jedi == "Yoda" or jedi == "Windu":

If the program needs to match regardless as to the case of the text entered, the easiest way to do that is to convert everything to lower case. This can be done with the lower command.

Learn to be insensitive!

The example below will take whatever the user enters, convert it to lower case, and then do the comparison. Important: Don't compare it against a string that has uppercase. If the user input is converted to lowercase, then compared against uppercase letters, there is no way a match can occur.

jedi = input("Who is the greatest Jedi Master? ")

if jedi.lower() == "yoda":

    print("Greatest, he is!")

else:

    print("Incorrect")


Run Output:

Who is the greatest Jedi Master? YoDa

Greatest, he is!

QUIZ MASTER PROJECT

      Time for you to grow up and be the teacher for a change. One of the Jedi Tasks in the repository is for you to create an interactive quiz.  Please create your own original questions. I like to be entertained while I check these programs. The criteria/pseudo code are below.

  1. Create your own quiz with 7 or more questions. Ask at least one of each of the following types of questions:

    • a number as an answer (e.g., What is 1+1?)

    • text as an answer (e.g. Who created C3PO?)

    • a multiple choice (Which of these choices are correct? A, B, or C?)

  2. When the user enters non-numeric answers, think and cover the different ways a user could enter a correct answer. For example, if the answer is "a", would "A" also be acceptable?

  3. Let the user know if he or she gets the question correct. Print the correct answer if the user gets it wrong.

  4. You need to keep track of how many questions they get correct.

  5. At the end of the program print the percentage of questions the user gets right and their letter grade.

  6. Keep the following in mind when creating the program:

    • Variable names should start with a lower case letter. Upper case letters work, but it is not considered proper.

    • To create a running total of the number correct, create a variable to store this score. Set it to zero. With an if statement, add one to the variable each time the user gets a correct answer. (How do you know if they got it correct? Remember that if you are printing out "correct" then you have already done that part. Just add a line there to add 1 to the number correct.)

    • Calculate the percentage by using a formula at the end of the game. Don't just add a certain percentage for each question the user gets correct. If you add a certain percentage each time, then you have to change the program in all of those places if some day you want to add another question. With a formula, you only need 1 change.

    • To print a blank line so that all the questions don't run into each other, use the following code: 

print( )

    • Remember the program can print multiple items on one line. This can be useful when printing the user's score and grade at the end.

print("The value in x is", x)

    • Separate out your code by using blank lines to group sections together. For example, put a blank line between the code for each question.

    • Sometimes it makes sense to re-use variables. Rather than having a different variable to hold the user's answer for each question, you could reuse the same one.

    • Use descriptive variable names. x is a terrible variable name. Instead use something like number_correct.

    • You must have at least two other people take your quiz to give you feedback before officially demonstrating it to your instructor for completion

Quick Lookup:How to download and turn in Jedi Tasks
Syllabus
Marc C. Hermon - Python Jedi InstructorUrbandale High School, Urbandale, Iowahermonm@urbandaleschools.comWebsite: EngineeringU.com
Google Sites
Report abuse
Google Sites
Report abuse