While Sentence in Python

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值