Skip to main content
 首页 » 编程设计

python之字符串和整数作为 while 循环中的多个条件的问题 (Python)

2025年05月04日1998°冷暖

我是 python 语言的初学者,在编写包含 while 循环的代码时遇到了一些问题,我想检查多个条件,其中一个条件未被检查,并且字符串/整数有问题。

原始代码(第二个代码示例)是我第一次写的,但问题是在一个键满足第一个循环的条件后,它会进入第二个循环,所以如果我在程序中什么都不输入当它运行时,它只会出现错误,而不是请输入 key 。我能想到的解决此问题的唯一方法是更改​​代码,以便它使用一个 while 循环检查多个条件之一。但是我遇到了一些问题,每个条件的变量键都是不同的类型(整数/字符串),并且当我尝试使用 int() 和 str() 时它没有修复。除此之外,代码似乎并未检查所有条件。更改后的代码的一个主要缺点是它不会再告诉用户他们到底做错了什么,例如没有输入任何内容,输入了一个不是数字的字符

代码:

def Key(key): 
    while len(key) < 1 or key.isalpha() == True or ((key > 25) or (key < -25)): 
        print("The key must be a number between numbers 26 and -26") 
        key = int(input("What is the key: ")) 
    print (key) 
 
key = input("What is the key: ") 
Key(key) 

原始代码:

def Key(key): 
    while len(key) < 1: 
        print("Please enter a key") 
        key = int(input("What is the key: ")) 
    while key.isalpha() == True : 
        print("Please enter a number!") 
        key = int(input("What is the key: ")) 
    key=int(key) 
    while (key > 25) or (key < -25): 
        print("The key must be in between numbers 26 and -26") 
        key = int(input("What is the key: ")) 
    print key 
 
key = input("What is the key: ") 
Key(key) 

任何帮助、改进和更好的方法都将非常有帮助 抱歉这篇长得可笑的帖子 谢谢

请您参考如下方法:

问题出在获取用户输入时。 key 需要一个 int 但如果你输入 characters 它将失败。在获取输入时删除 (int(...))

while len(key) < 1: 
     print("Please enter a key") 
     key = int(input("What is the key: ")) 

如果你运行try...except中的代码,你会发现这个错误

Python 3.3 programming. ValueError: invalid literal for int () with base 10

Demo你的工作代码