Exercise 29: if (IF)
Here is the job you want to write, this section introduces you to the "if statement". Put the input in so that it can be executed correctly. And then we'll see if you've got something to gain.
1People = 202Cats = 303Dogs = 154 5 6 ifPeople <Cats:7 Print "Too Many cats! the world is doomed!"8 9 ifPeople >Cats:Ten Print "Not many cats! the world is saved!" One A ifPeople <Dogs: - Print "The world is drooled on!" - the ifPeople >Dogs: - Print "The world is dry!" - - +Dogs + = 5 - + ifPeople >=Dogs: A Print "people is greater than or equal to dogs." at - ifPeople <=Dogs: - Print "people is less than or equal to dogs." - - - ifPeople = =Dogs: in Print "people is dogs."
View Code
The results you should see
Bonus points Exercise
Guess what the "if statement" is and what it's useful for. Before doing the next exercise, try to answer the following questions in your own words:
- What do you think if it does the code for its next line?
- Why does the next line of an if statement require 4 spaces for indentation?
- What happens if you don't indent?
- Is it possible to put the other Boolean expressions in Exercise 27 in the "if statement"? Try it.
- What happens if I change the initial value of the variable people, Cats, and dogs ?
Exercise Exercises
1.
The IF statement.
if sentence1: sentence2
The sentence one is the judgment part , of course, it can also be a Boolean expression of the previous lesson.
The white space in front of the statement two is also part of the IF statement, and using indentation is a unique style of python.
The IF statement executes the following procedure:
The statement is executed first, and if the judgment statement is true, statement two is executed.
As for the nesting of if else,if statements, the following course will speak.
2.
+ =.
The author calls it a bonus , and you can use this concept to remember the usage. But hopefully you'll understand how it works.
The operators have the binding nature, including the left binding and right binding.
Most operators are right-associative , that is, the operations are all right-to-left, including the + and = numbers (the = sign is the symbol used to assign values, and we generally understand that the equal equals sign is = =).
So for the interpreter, A + = B is equivalent to a = a + B.
3.
Do not indent
Stupid way to learn python (29)