【问题标题】:How to break while loop in python? [duplicate]如何打破python中的while循环? [复制]
【发布时间】:2021-07-02 11:05:49
【问题描述】:

我希望在输入数据为 5 时打破内部 while 循环,但如果输入不是 5,则会再次执行循环。在这段代码中,我输入的每个数字的输入值都打印为 X = 1:

x = 1
while True:
    def state():
        x = input("Enter Your number:")

    while True:
        print(x)
        if x==5:
            print('x=5')
            break
        state() 

在这段代码中,我试图解决这个问题,但也没有成功。

condition = True
x = 1
while True:
    def state():
        x = input("Enter Your number:")

    while condition:
        print(x)
        if x==5:
            print('x=5')
            condition = False
        state() 

有人帮我吗?

【问题讨论】:

  • 这里有多个问题。 1) state() 中x 的范围仅限于该函数(最好使用返回值或使用global 关键字)。 2)input 返回一个字符串,"5" 永远不会等于数字5

标签: python python-3.x while-loop


【解决方案1】:
  • 您正在 while 循环中定义您的函数。
  • 函数中 x 的范围也是本地的,返回值或在 while 循环中使用输入
  • 而表达式 x==5 永远不会为真

试试这个:

    while True:
       x = input("Enter Your number:")
       if x=="5":
          print('x=5')
          break

【讨论】:

    【解决方案2】:

    我假设您希望您的程序不断要求用户输入数字,如果他输入 5,则循环中断。

    input 函数将输入的值存储为字符串,因此您必须使用 int() 将其转换为 int。

    您可以使用单个 while 循环来实现此目的。 试试这个:-

    while True:
        x = int(input("Enter Your number:"))
        print(x)
        if x==5:
            print('x=5')
            break
    

    【讨论】:

      【解决方案3】:

      如果您想确保输入是一个数字,您应该尝试将其转换为 int:

      while True:
          inpt = input("Enter Your number:")
          try:
              x = int(inpt)
          except:
              print('Not a number.')
          print(f'x = {x}')
          if x==5:
              break
               
      

      【讨论】:

      • 谢谢,解决了。但我在您的代码中编辑 x=='5'。
      • @mehdializade 确实,你是对的。随意选择有帮助的并选择您选择的答案。
      猜你喜欢
      • 2020-03-28
      • 1970-01-01
      • 2022-11-13
      • 1970-01-01
      • 2016-01-20
      • 1970-01-01
      • 2012-12-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多