当我运行它时,我希望用户在 age: 和 years 之间输入他们的年龄,但是,当我运行它时,用户必须在岁后输入他们的年龄。是否有可能让用户可以在年龄:和年份之间输入他们的年龄
慕尼黑5688855
浏览 167回答 4
4回答
DIEA
基本上,没有。当您使用 input([prompt]) 时,您的“输入您的年龄:”+“岁”成为提示。输入总是在最后接受值。我的问题变成了,你真的需要“岁”的部分吗?你总是可以做这样的事情:age = input('How old are you?')print(f'You are {age} years old!')
您可以使用 的实现getch从用户读取单个字符。这是解决方案:import sysprint("Type your age:", end=" ")sys.stdout.flush()c = getch()print(c + " years old")首先,你得到:Type your age: ▯然后,您按一个字符(您可以使用 2 次调用getch来获取 2 个字符)。它打印:Type your age: 9 years old编辑但是,这样做的经典方法是:while True: try: age = int(input("Type your age: ")) except ValueError: print("This is not an integer") print() else: if 1 <= age <= 120: break print("please, enter your age between 1 and 120 years") print()print("You are {age} years old.".format(age=age))