【问题标题】:Python How to break loop with 0Python如何用0打破循环
【发布时间】:2022-11-16 00:28:18
【问题描述】:

我不明白为什么我的代码不起作用

def random_calculation(num):
    return((num*77 + (90+2-9+3)))


while random_calculation:
    num = int(input("Pleace enter number: "))
    if num == "0":
        break
    else:
        print(random_calculation(num))

你能指导我这里有什么问题吗,我真的不明白

【问题讨论】:

  • 0 是一个整数,"0" 是一个字符串。这些是不同的东西。
  • 因为 num 永远不会是“0”,因为它是一个整数。您可能需要 if num == 0 来代替。
  • 您将来自用户的输入转换为 int,然后将该 int 值与字符串文字 "0" 进行比较。取而代之的是if num == 0:
  • 你的问题在while random_calculation:,改用while True:

标签: python while-loop break


【解决方案1】:

因此,当您开始循环时,它会询问您要输入的数字,然后代码检查数字是否 == 为 0。如果数字等于 0:中断循环。如果数字等于任何其他数字,它会打印“random_calculation”函数

【讨论】:

    【解决方案2】:

    您的代码中有几个错误:

    你不能像这样做while random_calculation。您需要调用该函数,但由于在循环内部您已经在检查中断条件,因此请改用 while True 。

    此外,您正在将输入转换为 int,但随后再次比较字符串“0”而不是 int 0

    这是更正后的代码:

    def random_calculation(num):
        # 90+2-9+3 is a bit strange, but not incorrect.
        return((num*77 + (90+2-9+3)))
    
    
    while True:
        num = int(input("Please enter number: "))
        if num == 0:
            break
        
        # you don't need an else, since the conditional would 
        # break if triggered, so you can save an indentation level
        print(random_calculation(num))
    

    【讨论】:

      猜你喜欢
      • 2020-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-13
      • 1970-01-01
      • 1970-01-01
      • 2022-11-13
      相关资源
      最近更新 更多