First, I ned to give an example to explain what is the while cycle sentence
#print(1)
#print(2)
#print(3)
......
#print(9)
x = 0
while x <= 9
print(x)
x += 1
This code shows the number 1 to 9. And if we want to utilize print to show 1 to 9, we need to code 9 lines. It is too verbose for us to repeat the same sentences. So we always use while cycle sentence to avoid coding verbose sentence. It is significantly effective, 9 lines are instead of 4 simple lines.
Then we can add while cycle sentence to the mini-game guess age.
age_of_programmer = 18
guess_age = int(input("Programmer's age:"))
while guess_age != age_of_programmer:
if guess_age > age_of_programmer:
print("TRY SMALLER!!")
guess_age = int(input("Programmer's age:"))
else:
print("TRY BIGGER!!")
guess_age = int(input("Programmer's age:"))
if guess_age == age_of_programmer:
print("you are right!")
And in this program, I want to alert you that you had better to separate the part which responds to wrong answer from the part which responds to right answer when you add the while sentence. Because the player just need to answer again when their last answer is wrong, we just need to add the wrong answer responded part into while sentence.
When we figure the logic in above code, we can make the feature of the code more powerful.
There are two projects
- A changeable rectangle
- Draw a multiplication table
length = int(input("Length:"))
width = int(input("Width:"))
while length > 0:
r_width = width
while r_width > 0:
print("#", end="")
r_width -= 1
print()
length -= 1
num1 = 1
while num1 <= 9:
num2 = 1
while num2 <= num1:
print(num1*num2, end=" ")
num2 += 1
print()
num1 += 1