gpt4 book ai didi

python - 如何控制用户的输入

转载 作者:太空宇宙 更新时间:2023-11-04 10:06:43 28 4
gpt4 key购买 nike

 name = input('Enter your name please: ')
while name != str:
name = input('Please enter only letters for your name: ')
ss = input('Enter your Social Security Number: ')
while ss != int:
ss = input('Please enter only numbers for your social security number:')

所以我有这个基本程序,它询问用户他的名字和 SS#,我想这样做,用户不能在他应该输入 int 的地方输入 str 或 float。我试过了,但它会永远循环下去,因为 If 语句正在检查输入是数据类型 str 还是 int,我该如何检查变量是 int 还是 str?

最佳答案

您正在尝试将值与类型 进行比较。您应该改为存储名称并检查是否只有字母 (.isalpha()) 并尝试对安全号码进行类型转换。如果失败,则它不是有效输入。使用 isnumeric() 作为 SSN 也是一种选择。像这样的东西:

name = input('Enter your name please: ')
while not name.isalpha():
name = input('Please enter only letters for your name: ')

ss = input('Enter your Social Security Number: ')
try:
int(ss)
valid_ss = True
except ValueError:
valid_ss = False

while not valid_ss:
ss = input('Please enter only numbers for your social security number:')
try:
int(ss)
valid_ss = True
except ValueError:
valid_ss = False

name = input('Enter your name please: ')
while not name.isalpha():
name = input('Please enter only letters for your name: ')

ss = input('Enter your Social Security Number: ')
while not ss.isnumeric():
ss = input('Please enter only numbers for your social security number:')

关于python - 如何控制用户的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40640206/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com