修复While循环Python


  1. 我们要创建一个程序,提示用户输入1到10之间的数字。只要号码超出了范围,程序就会重新提示用户输入一个有效的号码。完成以下步骤来编写此代码。

。写一行代码,提示用户输入1到10之间的数字。

number = float(input("Enter a number between 1 and 10: "))

b。编写一个布尔表达式,测试用户在步骤"a.&"中输入的数字。以确定它是否不在范围内。

x = (number > 10 or number < 1)

c。使用在步骤b中创建的布尔表达式来编写一个while循环,当用户输入超出范围时执行。循环体应该告诉用户他们输入了一个无效的数字,并提示他们再次输入一个有效的数字。

while x == True:
print("you printed an invalid number")
number = float(input("please enter the number again, this time between 1 and 10"))

d。编写打印消息的代码,告诉用户他们输入了一个有效的数字。

if x == False:
print("wow, you printed a number between 1 and 10!")

我回答了这个问题,但我的问题是,每当用户第一次输入错误的数字,第二次输入正确的数字时,程序仍然认为它是无效的输入。我怎么解决这个问题??

while循环中重写这一行:

x = (number > 10 or number < 1)

变成

while x == True:
print("you printed an invalid number")
number = float(input("please enter the number again, this time between 1 and 10"))
x = (number > 10 or number < 1)

这会改变x的值,使它不再停留在True

如果使用while True结构,则不需要重复任何代码。像这样:

LO, HI = 1, 10
while True:
input_ = input(f'Enter a number between {LO} and {HI}: ')
try:
x = float(input_)
if LO <= x <= HI:
print(f'Wow! You entered a number between {LO} and {HI}')
break
print(f'{input_} is not in range. Try again')
except ValueError:
print(f'{input_} is not a valid number. Try again')

注意:

当要求用户输入数字时,不要假设他们的输入总是可以被正确转换。总是检查

下面的代码片段应该可以满足您的所有需求:

number = float(input("Please input a number: "))
while (number > 10 or number < 0):
number = float(input("Error. Please input a new number: "))

使用无限循环,这样您只能提示输入一次。

输入正确范围内的数字后,使用break终止循环。
使用f字符串或格式化字符串字面值打印消息。

while True:
num = float(input('Enter a number between 1 and 10: '))
if 1 <= num <= 10:
print('Wow, you printed a number between 1 and 10!')
break
else:
print(f'You printed an invalid number: {num}!')

最新更新