检查用户输入python

2024-05-23 15:11:10 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的inputCheck函数中,当用户输入被检查后通过时,是否可以接受输入应该由打印消息确认,然后运行另一个函数-但是它没有这样做,我也不知道为什么-你能建议如何解决问题吗?非常感谢!

def main():
    print('WELCOME TO THE WULFULGASTER ENCRYPTOR 9000')
    print('==========================================')
    print('Choose an option...')
    print('1. Enter text to Encrypt')
    print('2. Encrypt text entered')
    print('3. Display Encrypted Text!')
    menuChoice()

def menuChoice():
    valid = ['1','2','3']
    userChoice = str(input('What Would You Like To Do? '))
    if userChoice in valid:
        inputCheck(userChoice)
    else:
        print('Sorry But You Didnt Choose an available option... Try Again')
        menuChoice()

def inputCheck(userChoice):
    if userChoice == 1:
        print('You Have Chosen to Enter Text to Encrypt!')
        enterText()
    if userChoice == 2:
        print('You Have Chosen to Encypt Entered Text!')
        encryptText()
    if userChoice == 3:
        print('You Have Chosen to Display Encypted Text!')
        displayText()

def enterText():
    print('Enter Text')

def encryptText():
    print('Encrypt Text')

def displayText():
    print('Display Text')


main()

Tags: to函数textyouifdefhavedisplay
1条回答
网友
1楼 · 发布于 2024-05-23 15:11:10

将用户的输入转换为字符串(str(input('What ...'))),但将其与inputCheck中的整数进行比较。由于在inputCheck中没有else路径,因此当您输入“有效”选项时不会发生任何事情。

另外,如果您使用的是Python 2,那么使用input并不是您想要的,raw_input是一种方法(请参见,例如What's the difference between raw_input() and input() in python3.x?)。

除此之外,每当用户输入非法选择时递归调用menuChoice可能是一个很糟糕的主意:输入非法选择数十万次,程序就会崩溃(除了浪费大量内存之外)。您应该将代码放入循环中:

while True:
    userChoice = str(raw_input('What Would You Like To Do? '))
    if userChoice in valid:
        inputCheck(userChoice)
        break
    else:
        print('Sorry But You Didnt Choose an available option... Try Again')

相关问题 更多 >