preface
This time mainly explains the circular statements, including the use of if statements and their nested statements, for statements and while statements.
1, IF statement
people = 20 cats = 30 dogs = 15 if people < cats: print("Too many cats! The world is doomed!") if people > cats: print("Not many cats! The world is saved!") if people < dogs: print("The world is drooled on!") if people > dogs: print("The world is dry!") dogs += 5 if people >= dogs: print("People are greater than or equal to dogs.") if people <= dogs: print("People are less than or equal to dogs.") if people == dogs: print("People are dogs.")
Additional exercises
1. What do you think if does to the code below it?
The if statement creates a "branch" in the code, which is a bit similar to turning to the corresponding page in an adventure book. If you choose different answers, you will go to different places. The if statement tells the script to run the following code if the Boolean expression is True, otherwise it will be skipped.
2. Why if does the following code indent four spaces?
A colon at the end of a line of code tells python that you are creating a new code block, and then indents four spaces to tell Python what is in the code block. This is the same as the function you learned in the first half of this book.
3. What happens if there is no indentation?
If there is no indentation, you are likely to receive an error message. Python usually lets you indent something under a line of code with:.
4. Can you put some Boolean expressions into the if statement? have a try.
if True: print("This is True") if False: print("This is False") if True and False: print("false") if True or False: print("false")
5. What happens if you change the initial values of people, cats and dogs?
people = 15 cats = 30 dogs = 20 if people < cats: print("Too many cats! The world is doomed!") if people > cats: print("Not many cats! The world is saved!") if people < dogs: print("The world is drooled on!") if people > dogs: print("The world is dry!") dogs += 5 if people >= dogs: print("People are greater than or equal to dogs.") if people <= dogs: print("People are less than or equal to dogs.") if people == dogs: print("People are dogs.")
people = 30 cars = 40 trucks = 15 if cars > people: print("We should take the cars.") elif cars < people: print("We should not take the cars.") else: print("We can't decide.") if trucks > cars: print("That's too many trucks.") elif trucks < cars: print("Maybe we could take the trucks.") else: print("We still can't decide.") if people > trucks: print("Alright, let's just take the trucks.") else: print("Fine, let's stay home then.")
Additional exercises
1. Try to guess what elif and else do?
Else and elif statements can also be called clauses because they cannot be used independently. They both appear inside if, for and while statements. Else clause can add a choice; Elif clause is used when more conditions need to be checked. It is used together with if and else. Elif is the abbreviation of else if.
2. Change the values of cars, people, and trucks, and then trace each if statement to see what will be printed.
people = 25 cars = 18 trucks = 30 if cars > people: print("We should take the cars.") elif cars < people: print("We should not take the cars.") else: print("We can't decide.") if trucks > cars: print("That's too many trucks.") elif trucks < cars: print("Maybe we could take the trucks.") else: print("We still can't decide.") if people > trucks: print("Alright, let's just take the trucks.") else: print("Fine, let's stay home then.")
3. Try some more complex Boolean expressions, such as cars > people or trucks < cars.
people = 25 cars = 18 trucks = 30 if cars > people or trucks < cars : print("We should take the cars.") print("Maybe we could take the trucks.") elif cars < people and trucks > cars: print("We should not take the cars.") print("That's too many trucks.") else: print("We can't decide.") print("We still can't decide.") if people > trucks: print("Alright, let's just take the trucks.") else: print("Fine, let's stay home then.")
common problem
What happens if multiple elif blocks are True? Python starts at the top and then runs the first block of code that is True, that is, it only runs the first one.
1.IF nested use
print("""You enter a dark room with two doors.Do you go through door #1 or door #2?""") door = input("> ") if door == "1": print("There's a giant bear here eating a cheese cake.") print("What do you do?") print("1. Take the cake.") print("2. Scream at the bear.") bear = input("> ") if bear == "1": print("The bear eats your face off. Good job!") elif bear == "2": print("The bear eats your legs off. Good job!") else: print(f"Well, doing {bear} is probably better.") print("Bear runs away.") elif door == "2": print("You stare into the endless abyss at Cthulhu's retina.") print("1. Blueberries.") print("2. Yellow jacket clothespins.") print("3. Understanding revolvers yelling melodies.") insanity = input("> ") if insanity == "1" or insanity == "2": print("Your body survives powered by a mind of jello.") print("Good job!") else: print("The insanity rots your eyes into a pool of muck.") print("Good job!") else: print("You stumble around and fall on a knife and die. Good job!")
Additional exercises
Add some new content to the game and change the decisions users can make. Expand the game as much as possible until it becomes funny.
print("""You enter a dark room with two doors.Do you go through door #1 or door #2 or door #3?""") door = input("> ") if door == "1": print("There's a giant bear here eating a cheese cake.") print("What do you do?") print("1. Take the cake.") print("2. Scream at the bear.") bear = input("> ") if bear == "1": print("The bear eats your face off. Good job!") elif bear == "2": print("The bear eats your legs off. Good job!") else: print(f"Well, doing {bear} is probably better.") print("Bear runs away.") elif door == "2": print("You stare into the endless abyss at Cthulhu's retina.") print("1. Blueberries.") print("2. Yellow jacket clothespins.") print("3. Understanding revolvers yelling melodies.") insanity = input("> ") if insanity == "1" or insanity == "2": print("Your body survives powered by a mind of jello.") print("Good job!") else: print("The insanity rots your eyes into a pool of muck.") print("Good job!") elif door == "3": print("What do you want to do?") print("1. Watching TV.") print("2. eating fruits.") print("3. Sleeping.") insanity = input("> ") if insanity == "1" : print("It is a good choice.") print("Good job!") elif insanity == "2": print("It is good for you.") print("Good job!") else: print("You are a good boy.") else: print("You stumble around and fall on a knife and die. Good job!")
common problem
1. Can I replace elif with a series of if statements?
In some cases, but it depends on how each if/else is written. If so, it also means that Python will check every if else combination, instead of checking that the first one is false, as if elif else combination.
2. How to represent the interval of a number?
There are two ways: one is the traditional representation of 0 < x < 10 or 1 < = x < 10, and the other is that the interval of X is (1, 10).
3. What if you want to put more choices in the if elif else code block?
Add more elif blocks for each possible choice.
2, FOR statement
the_count = [1, 2, 3, 4, 5] fruits = ['apples', 'oranges', 'pears', 'apricots'] change = [1, 'pennies', 2, 'dimes', 3, 'quarters'] # this first kind of for-loop goes through a list for number in the_count: print(f"This is count {number}") # same as above for fruit in fruits: print(f"A fruit of type: {fruit}") # also we can go through mixed lists too # notice we have to use {} since we don't know what's in it for i in change: print(f"I got {i}") # we can also build lists, first start with an empty one elements = [] # then use the range function to do 0 to 5 counts for i in range(0, 6): print(f"Adding {i} to the list.") # append is a function that lists understand elements.append(i) # now we can print them out too for i in elements: print(f"Element was: {i}")
common problem
1. How do I create a 2D list?
You can use the list in this list: [[1,2,3], [4,5,6]]
2. Aren't lists and arrays the same thing?
It depends on the language and implementation method. In traditional terms, lists and arrays are implemented differently. They are called arrays in Ruby and lists in python. So we call these lists.
3. Why can for loop use an undefined variable?
The variable is defined at the beginning of the for loop, and it is initialized to the current element at each loop iteration.
4. Why does i in range(1, 3) cycle only twice instead of three times?
The range() function only handles the first to last number, but does not include the last number, so it ends at 2. This is a common practice for such cycles.
5,element. What is the function of append()?
It just appends things to the end of the list. Open the Python shell and create a new list.
3, while statement
Now let's look at a new loop: while loop. As long as a Boolean expression is True, while loop will always execute the code block below it.
While loop, which does the same test as if statement, but it does not only run the code block once, but returns to the top where while is right and repeats until the expression is False.
But while loop has a problem: sometimes they can't stop. If your goal is to keep the program running until the end of the universe, that's really awesome. But in most cases, you definitely need your cycle to stop eventually.
To avoid these problems, you have to follow some rules:
1. Use while loop conservatively, and it is usually better to use for loop.
2. Check your while statement to make sure that the Boolean test will eventually result in False at some point.
3. When you encounter problems, print out the test variables at the beginning and end of your while loop to see what they are doing.
i = 0 numbers = [] while i < 6: print(f"At the top i is {i}") numbers.append(i) i = i + 1 print("Numbers now: ", numbers) print(f"At the bottom i is {i}") print("The numbers: ") for num in numbers: print(num)
common problem
1. What is the difference between for loop and while loop?
For loop can only iterate (loop) a collection of things, while while while loop can iterate (loop) anything of any type. However, while loop is difficult to use, and you can usually do a lot of things with for loop.
2. Circulation is so difficult. How should we understand them?
The main reason people don't understand loops is that they can't keep up with the code. When a loop runs, it goes through the code block and jumps to the top at the end. In order to visualize this process, you can print out the whole process of the loop with print, and write the print line in the front, top, middle and end of the loop. Study the output and try to understand how it works.
Branches and functions
from sys import exit def gold_room(): print("This room is full of gold. How much do you take?") choice = input("> ") if "0" in choice or "1" in choice: how_much = int(choice) else: dead("Man, learn to type a number.") if how_much < 50: print("Nice, you're not greedy, you win!") exit(0) else: dead("You greedy bastard!") def bear_room(): print("There is a bear here.") print("The bear has a bunch of honey.") print("The fat bear is in front of another door.") print("How are you going to move the bear?") bear_moved = False while True: choice = input("> ") if choice == "take honey": dead("The bear looks at you then slaps your face") elif choice == "taunt bear" and not bear_moved: print("The bear has moved from the door.") print("You can go through it now.") bear_moved = True elif choice == "taunt bear" and bear_moved: dead("The bear gets pissed off and chews your leg.") elif choice == "open door" and bear_moved: gold_room() else: print("I got no idea what that means.") def cthulhu_room(): print("Here you see the great evil Cthulhu.") print("He, it, whatever stares at you and you go insane.") print("Do you flee for your life or eat your head?") choice = input("> ") if "flee" in choice: start() elif "head" in choice: dead("Well that was tasty!") else: cthulhu_room() def dead(why): print(why, "Good job!") exit(0) def start(): print("You are in a dark room.") print("There is a door to your right and left.") print("Which one do you take?") choice = input("> ") if choice == "left": bear_room() elif choice == "right": cthulhu_room() else: dead("You stumble around the room until you starve.") start()
common problem
1. Why do you use while True?
This builds an infinite loop.
2. What is exit(0) for?
In many operating systems, a program can end with exit(0), where the number passed in represents whether there is an error. If you use exit(1) to represent an error, exit(0) means that the program exits normally. It is different from the usual Boolean logic (0==False) because you can use different numbers to represent different error results. You can use exit(100) to express the error result different from exit(2) or exit(1).
3. Why is input() sometimes written as input('>')?
The input parameter is a string, so you need to add a prompt before getting the user's input. Here > can also be changed to the text you want to prompt the user.
summary
This article mainly explains the three common loops of for, if and while, and gives examples to understand their working principle.