python-3.x 如果用户输入其他数据类型,如何给予自定义响应?

dced5bon  于 2022-12-05  发布在  Python
关注(0)|答案(1)|浏览(115)
response = input("Do you want some food? (Y/N): ")

if response == "Y":
    print("Come! There is pizza for you")
elif response == "N":
    print("Alright, let us do Sisha instead.")
elif response == range(999):
    print("The required response is Y/N.")
else:
    print("I do not understand the prompt")

Q1:用户输入数字而不是字符串时如何反馈?

A1:我看了一下python文档,但似乎range不能在if语句中使用?
我尝试修改代码,

deret_angka = int or float
for n in deret_angka:
  print("The required response is Y/N.")

和第三IFS条件,以便:

elif response == deret_angka:
    print("The required response is Y/N.")

但出现TypeError:'type'对象不是可反覆运算的

问题2:如何给予Y和N值,即使是小写的y/n?

A2:我试着输入“Y”或“y”,但不起作用,只是传递到下一个if条件。

xpszyzbs

xpszyzbs1#

这很简单,在python中你可以通过很多方式给予反馈。假设用户输入了一个数字,我们可以尝试转换输入的type,看看它是否会引发如下错误:

response = input("Do you want some food? (Y/N): ")
try:
    float(response)
    int(response)
except ValueError: #it a string or a bool
    print("The required response is Y/N.")

如果你想检查一个特定范围内的数字,你可以这样做:

if response in [range(999)]:
    pass

不能只选中range(999),因为它是一个对象。需要将此对象转换为列表才能在其上循环。
要检查小写,您可以通过以下几种方式进行检查:

response = input("Do you want some food? (Y/N): ")

if response in ['Y', 'y']:
    pass
elif response in ['N', 'n']:
    pass

#or like that:

if response.lower = 'y': # Just convert the input to lower
    pass
if response.upper = 'N': # You can also do this vice versa and convert to upper and check.
    pass

相关问题