python - 如何让我的脚本很好地拒绝无效字符
问题描述
目前,如果您在输入中输入字符而不是数字,则会出现丑陋的错误。我希望脚本输出类似“无效字符!请输入数字”之类的内容。我能做些什么来解决这个问题?
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))
解决方案
您可以在循环中使用 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
用户输入有效数字后设置为。
推荐阅读
- php - PHP URL隐藏类别的ID
- typescript - 在 TypeScript 中定义类型之间的相等性
- android - Android Gravity Left vs Right Clipping 差异
- python - 如何获取维基项目的维基百科数据?
- html - Favicon error 404 for local and remote, favicon.ico directory automatically generated in git repo
- microsoft-teams - How to get webHookUrl from Microsoft Teams connector
- google-cloud-firestore - Google Cloud Firestore 控制台读取所有文件和费用
- java - Java中try catch块中可捕获异常的规则是什么?
- django - 我无法删除 Django 应用程序中的包,因为它存储在迁移文件中
- c# - Visual Studio Windows 窗体 C# Interop.Excel - Excel 类对象