首页 > 解决方案 > 如何让我的脚本很好地拒绝无效字符

问题描述

目前,如果您在输入中输入字符而不是数字,则会出现丑陋的错误。我希望脚本输出类似“无效字符!请输入数字”之类的内容。我能做些什么来解决这个问题?


import random
import string

string.ascii_letters='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
string.number_symbols='!@#$%^&*()'

userLetterInput = int(input("How many letters would you like in your password?: "))
userSymbolInput = int(input("How many symbols would you like in your password?: "))

letterResult = ''.join([random.choice(string.ascii_letters) for i in range(userLetterInput)])

symbolResult = ''.join([random.choice(string.number_symbols) for i in range(userSymbolInput)])

print("".join(letterResult + symbolResult))


标签: python

解决方案


您可以在循环中使用 try/except 语句来捕获异常并为用户显示消息。try/except 语句捕获用户输入字母字符时引发的异常,而循环重复查询数字,直到用户提供有效输入。

import random
import string

string.ascii_letters='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
string.number_symbols='!@#$%^&*()'

while True: # Repeat the question until valid input is given
    try: # Catch ValueError which gets thrown when letters are entered
        userLetterInput = int(input("How many letters would you like in your password?: "))
        break # Exit the loop if no exception is thrown
    except ValueError:
        print("Invalid character! Please enter a digit.")

while True:
    try:    
        userSymbolInput = int(input("How many symbols would you like in your password?: "))
        break
    except ValueError:
        print("Invalid character! Please enter a digit.")

letterResult = ''.join([random.choice(string.ascii_letters) for i in range(userLetterInput)])

symbolResult = ''.join([random.choice(string.number_symbols) for i in range(userSymbolInput)])

print("".join(letterResult + symbolResult))

除了使用while True循环,您当然还可以声明一个布尔值(例如invalid_input),它True最初是在False用户输入有效数字后设置为。


推荐阅读