【问题标题】:why Break is not Breaking out of loop for this small piece of code?为什么 Break 没有打破这一小段代码的循环?
【发布时间】:2018-12-16 05:00:08
【问题描述】:

列表项

# To put values in list till user want
#comparing value entered with the ascii value ofenter
# key , if enter then come out of infinite loop
# why break is not breaking out on enter press
#if value is not enter_key thn put this value in list
x=1
lis=[]
while x == 1 :
    var = str(input())
    if var == chr(10):  
        break                     
    lis.append(var)    

print("i m free now from infinite loop")
print(lis)

【问题讨论】:

  • 因为如果用户只是点击输入结果是一个空字符串,而不是换行符。输入的结果也已经是一个字符串了。
  • 你为什么要和chr(10)比较???当input 提示时,您是否真正查看过只需按 Enter 键返回的内容?
  • str 中的 str(input()) 是多余的。 input() 返回一个字符串。

标签: python python-3.x infinite-loop break


【解决方案1】:

如果用户在str(input()) 提示时按下回车键而不输入任何内容,则返回值将为空字符串。因此,您不应将varchr(10) 进行比较,后者是换行符(\n)。试试这个:

x=1
lis=[]
while x == 1 :
    var = str(input())
    if var == "":            #Compare to an empty string!
        break                     
    lis.append(var)    

print("i m free now from infinite loop")
print(lis)

【讨论】:

    【解决方案2】:

    我认为用户想要的是在一个空字符串上停止。所以我将代码如下

    a_list=[]
    
    while True :
        var = input('What is your input: ')
        if not var:
            break
        a_list.append(var)
    
    print("I'm free now from the infinite loop")
    print(a_list)
    

    【讨论】:

    • 输入已经返回一个字符串,不需要str(input(....))if not var:break 将起到相同的作用,因为空字符串是虚假的 - 请参阅falsy truthy python values
    猜你喜欢
    • 2017-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-07
    相关资源
    最近更新 更多