Python 有没有一种方法可以只允许一种类型的输入,例如只允许来自input()调用的float、int?
在这种情况下,是否有一种方法只允许整数传递到if语句,而不是引发ValueError?Python 有没有一种方法可以只允许一种类型的输入,例如只允许来自input()调用的float、int?,python,python-3.x,Python,Python 3.x,在这种情况下,是否有一种方法只允许整数传递到if语句,而不是引发ValueError? import random import string def password(input): letters = string.ascii_letters return ''.join(random.choice(letters) for i in range(input)) while True: print("welcome to daniel's password g
import random
import string
def password(input):
letters = string.ascii_letters
return ''.join(random.choice(letters) for i in range(input))
while True:
print("welcome to daniel's password generator!")
length = int(input("how long do you want your password to be?: "))
if length == 1:
print("your newly generated password is " + password(1))
elif length == 2:
print("your newly generated password is " + password(2))
elif length == 3:
print("your newly generated password is " + password(3))
elif length == 4:
print("your newly generated password is " + password(4))
elif length == 5:
print("your newly generated password is " + password(5))
elif length == 6:
print("your newly generated password is " + password(6))
else:
print("unknown error!")
- 你不能强迫
接受一个类型,它总是返回一个字符串,然后你必须处理它,你可以使用循环,直到内容是数字李>input()
- 如果s,也不需要
,只需使用
变量即可length
- 您可以使用
进行多项选择random.sample
为什么不直接打印(“新生成的密码是”+密码(长度))?您不需要IFSY,您可以使用
try
和,除了do while
循环中的块,只有在获得正确的输入时才退出。如果您不希望引发ValueError,也不希望到达if
语句,您希望发生什么?如果input
的结果始终是str
。您现在可以考虑接受答案或注释以获取详细信息;)奖励那些为你付出时间的人;)也不需要生成器,只需使用random.sample
:return'.join(random.sample(string.ascii_字母,长度))
@DeepSpace我没有查看该方法,刚刚过去
def password(length):
return ''.join(random.sample(string.ascii_letters , length))
if __name__ == '__main__':
print("welcome to daniel's password generator!")
while True:
value = ""
while not value.isnumeric():
value = input("how long do you want your password to be?: ")
length = int(value)
print("your newly generated password is " + password(length))