首页 > 解决方案 > While 循环,直到输入为数字。Python

问题描述

我的编码帮派怎么了。所以 atm 我正在学习 Python,我完全是一个新手,我面临这个问题。所以我创建了一个单位转换程序,我成功地为单位制作了一个while循环,下面的代码一切正常:

weight = int(input("Weight: "))
unit = input("(K)g or (L)bs ? ")

while unit.upper != ("K" or "L"):
    if unit.upper()=="L":
        converted = weight*0.45
        print(f"You are {round(converted)} kilos")
        break
    elif unit.upper()=="K":
        converted=weight//0.45
        print(f"You are {converted} pounds")
        break
    else:
        print("Invalid unit. Please type K or L: ")
        unit=input()
        continue

但我也想进行更多实验,我还想为权重输入创建一个 while 循环,这样它就会一直运行,直到你输入任何正的浮点数整数,因为当我运行程序并输入权重时,我会不小心输入一个字母 - 我的屏幕上会出现一个大的红色错误,上面写着:

Exception has occurred: ValueError
invalid literal for int() with base 10: 'a'
  line 1, in <module>
    weight = int(input("Weight: "))

因此,当我尝试将其更改为 while 循环时,它不起作用,我的最终结果如下所示:

weight = int(input("Weight: "))

while weight != int():
    if weight==int():
        break
    else:
        print("Invalid unit. Please type a number: ")
        weight=int(input())
        continue

unit = input("(K)g or (L)bs ? ")

while unit.upper != ("K" or "L"):
    if unit.upper()=="L":
        converted = weight*0.45
        print(f"You are {round(converted)} kilos")
        break
    elif unit.upper()=="K":
        converted=weight//0.45
        print(f"You are {converted} pounds")
        break
    else:
        print("Invalid unit. Please type K or L: ")
        unit=input()
        continue

我知道这很糟糕,此时我被卡住了,它只是不断地输入我“无效的单位。请输入一个数字:”我无法摆脱那个循环。我什至不知道该输入什么或该做什么,所以我决定来这里寻求帮助。

我想用这段代码制作,直到你在重量输入中输入一个数字——你将不能更进一步,但是在你正确输入之后——程序将继续输入一个单位。谢谢

标签: pythonloopsinputwhile-loopinteger

解决方案


or操作员不按预期工作。

我建议将其替换为:

while unit.upper() in "KL":

推荐阅读