【问题标题】:While loop not taking 'if' statement into accountwhile 循环不考虑 \'if\' 语句
【发布时间】:2023-01-02 21:21:15
【问题描述】:

我正在尝试用 Python 编写一个程序,要求用户输入几个小时,然后以秒为单位开始倒计时,但是我还想确保没有输入浮点数/字符串,如果是,用户需要提示相同的问题并输入正确的值。如果输入一个整数,那么我希望程序跳转到下一条语句(因此在第 4 行“通过”)。然而,无论我输入什么,程序总是跳转到下一条语句,不管它是字符串还是浮点数。

TimeHours = input("Countdown time in hours:")

while isinstance(TimeHours, int) is True:
    pass
    if float(TimeHours) / 1 != int(float(TimeHours)):
        input('Please input a whole number, decimals are not accepted.')
    elif isinstance(TimeHours, str):
            input('Alphabetical letters or unknown characters are not allowed, e.g. A, B, C, (, *')
            continue

我尝试使用 if 语句和定义函数,但我似乎无法使其工作。

【问题讨论】:

  • 你是passing。
  • isinstance(TimeHours, int) 永远不会是 True
  • 如果我删除“通过”,它出于某种原因会做同样的事情。另外,如果答案是整数,我需要它通过,如果不是,我希望它出错并重新启动语句。
  • @erip pass 是空操作在这种情况下无关紧要
  • input() 的返回始终是一个字符串,而不是整数、浮点数或其他任何东西(除非您仍在使用 Python 2)。如果需要数字,则必须自己将字符串转换为数字。

标签: python


【解决方案1】:

float(TimeHours) / 1 返回 float。你是说float(TimeHours) // 1。并且isinstance(TimeHours, str)不能是True,因为只有isinstance(TimeHours, int) is True才会检查它。所以它不会忽略ifelif,只是永远不会进入它们。

边注:

isinstance(TimeHours, int) is True 是多余的,只需使用 isinstance(TimeHours, int) 代替。

【讨论】:

  • 因此,例如,如果输入是 2.5,我希望它返回浮点数,以便打印错误(“不允许小数”)。即使输入是整数,float(TimeHours) 是否返回浮点数?
  • input 总是返回一个字符串(假设您使用的是 python3)。你可以用float(TimeHours)把它转换成float。您可以通过将 '2.5' 转换为浮点数然后再转换为整数来将其转换为整数:int(float(TimeHours))
【解决方案2】:

像这样

while True:
    TimeHours = input("Countdown time in hours:")
    try:
        TimeHours = float(TimeHours)
    except ValueError as e:
        print('Alphabetical letters or unknown characters are not allowed, e.g. A, B, C, (, *')
        continue
    if TimeHours / 1 != int(TimeHours):
        print('Please input a whole number, decimals are not accepted.')

【讨论】:

  • 而且您仍然需要按照Yevhen Kuzmovych所说的那样编辑您的代码
【解决方案3】:

我认为你可以:

  • 获取用户输入
  • 检查它是否为数字(因为输入始终是字符串,您可以使用此方法)
  • 如果不是则打印一条消息并重新开始循环
  • 转换为整数,如果是,则退出循环
while True:
    time_hours = input("Countdown time in hours:")
    if time_hours.isnumeric() is False:
        print("Please input a whole number. Decimals, alphabetical letters or unknown characters are not allowed.")
        continue
    time_hours = int(time_hours)
    break

旁注:

  • python 喜欢 sneak_case
  • 即使使用 \ 进行除法也不总是产生整数(请自行查看,例如 REPL 中的 print(type(2//3.))
  • python 具有强大的(动态的,但这在这里无关紧要)类型,因此您必须明确类型转换

【讨论】:

    猜你喜欢
    • 2015-05-19
    • 2013-06-09
    • 2014-01-21
    • 2015-11-08
    • 2016-01-12
    • 2012-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多