如何使循环运行“轮”次数

问题描述 投票:0回答:2

我不确定使用哪个循环来执行我想做的事情,但我试图让一个循环运行与用户在“回合”中选择的次数相同的次数。

# 1 (code introduction)
print("Welcome to Response Time Tester!")
print("You will be asked to press Enter after random amounts of time.")
print("How close can you get? ")
print()
while True:
    try:
        rounds = int(input("Enter desired number of rounds:  "));
        break
    except ValueError:
        print('Invalid input. Enter a number > 0. ')

2 进入循环(循环)次的循环

python loops variables
2个回答
0
投票

代码:

# 1 (code introduction)
print("Welcome to Response Time Tester!")
print("You will be asked to press Enter after random amounts of time.")
print("How close can you get? ")
print()
while True:
    try:
        rounds = int(input("Enter desired number of rounds: "))
        if rounds <= 0:
            print("Number of rounds must be greater than zero. Try again.")
        else:
            break
    except ValueError:
        print("Invalid input. Enter a number.")
    
    
for i in range(rounds):
    print("round: ",i+1)

输出:

Welcome to Response Time Tester!
You will be asked to press Enter after random amounts of time.
How close can you get? 

Enter desired number of rounds: -1
Number of rounds must be greater than zero. Try again.
Enter desired number of rounds: 0
Number of rounds must be greater than zero. Try again.
Enter desired number of rounds: a
Invalid input. Enter a number.
Enter desired number of rounds: 4
round:  1
round:  2
round:  3
round:  4

0
投票

您可以使用for循环来完成您的工作,您可以使用单个

print()
而不是多个。
/n
可用于打印新行。

print("Welcome to Response Time Tester!/nYou will be asked to press Enter after random amounts of time./nHow close can you get? /n")
while True:
    try:
        rounds_count = int(input("Enter desired number of rounds: "))
        if rounds_count <= 0:
            print("Number of rounds can not be zero. Try again.")
        else:
            break
    except ValueError:
        print("Invalid input. Enter a number.")
    
    
for i in range(rounds_count):
    print("round: ",i+1)
© www.soinside.com 2019 - 2024. All rights reserved.