【问题标题】:While Loop with Boolean Value Result in Runtime Error带有布尔值的 While 循环导致运行时错误
【发布时间】:2020-10-05 13:49:14
【问题描述】:

我尝试使用以下代码检查 string s 是否包含任何字母数字字符:

s = input()

bool1 = False

while bool1 == False:
     for i in list(s):
         bool1 = i.isalnum()
print(bool1)

但它导致运行时错误。

为什么会这样?

【问题讨论】:

  • 我运行你的代码没有运行时错误,除了不需要while语句,如果字符串中没有字母数字字符,你将陷入无限循环,所以删除 while 语句。
  • 我使用了 while 循环,以便在找到字母数字字符后停止编程。 (即消除不必要的代码运行)
  • 这似乎不合逻辑,进入while循环后,条件将在for循环完成后再次检查,即每个字符都已检查,即使它发现字母数字字符循环将继续迭代整个字符串和如果字符串中没有字母数字字符,程序将陷入无限循环,那么如果没有字母数字字符,boo1 将如何变为真,我建议您首先了解循环的基本控制流程。请参阅@Babak 的答案,这是要走的路。
  • 还有check this

标签: python while-loop boolean


【解决方案1】:

我运行它。没有错误。 while循环有什么用?

s = input()

bool1 = False

for i in s:
    if bool1 == True:
        break
    bool1 = i.isalnum()
print(bool1)

【讨论】:

    【解决方案2】:

    当字符串不包含任何字母数字字符时,您的代码不起作用,因为您有不定式 while 循环。你应该只使用一个循环。

    s = input()
    
    bool1 = False
    
    for i in s:
        if i.isalnum():
            bool1 = True
            break
    
    print(bool1)
    

    【讨论】:

      猜你喜欢
      • 2015-05-24
      • 2020-08-01
      • 2017-06-04
      • 2011-08-01
      • 1970-01-01
      • 2011-07-24
      • 2017-11-20
      • 2013-12-22
      • 1970-01-01
      相关资源
      最近更新 更多