如何在两个不同的行同时提示输入?
我对Python还比较陌生,所以请多多包涵。
我想让下面的输入在控制台中同时出现。
input("Please enter your feet: ")
input("Please enter your inches: ")
我想要的输出:
Please enter your feet:
Please enter your inches:
用户可以同时输入。
每次我查找如何同时获取多个输入时,通常会看到一些不同的答案,建议使用split函数,并把输入分配给两个不同的变量:
x, y = input("Enter two nums: ")
但我觉得这样对用户来说会有点困惑,所以我想能够在不同的行上同时提示他们输入两个不同的内容。
3 个回答
0
你可以使用ANSI转义码(可以参考一下这个问题的回答)。比如说:
# just use print to output your questions
question1 = "Please enter your height in feet: "
print(question1)
question2 = "Please enter your height in inches: "
print(question2, end="") # use end="" so as not to start a new line
# go back up a line (end of question 1)
print("\033[A", end="")
feet = input()
# move to end of question 2
print("\033[C" * len(question2), end="")
inches = input()
print(f"\nYour height is {feet}\' {inches}\"")
0
如果没有其他库的话,这是不可能实现的。如果你真的想要这个功能,可以考虑使用tkinter库来创建图形用户界面(GUI)。
0
如果一个表单让用户需要在不同的行上输入内容,这可能不是最好的用户界面体验。最简单的方式是让用户一个一个地输入,或者让他们在一行中输入所有内容,然后再进行解析。
这里我没有提到错误处理和输入验证,这些也是你需要做的。
下面是两个不同输入的例子:
height_feet = input("Please enter your height in feet: ")
height_inches = input("Please enter your inches: ")
print(f"You are {height_feet}'{height_inches}\" tall.")
你也可以把两个输入放在一行中,用某种分隔符来区分:
height = input("Please enter your height in feet and inches, separated by a space (e.g., '5 11' is 5'11\"): ")
height_feet, height_inches = height.split()
print(f"You are {height_feet}'{height_inches}\" tall.")
更简单的方法是使用一个单位的测量,然后为了显示的方便进行转换。例如:
height = input("Please enter your height in inches: ")
height_feet = int(int(height) / 12)
height_inches = int(height) % 12
print(f"You are {height_feet}'{height_inches}\" tall.")
如果你真的想同时显示两个不同的输入,那就不再是简单的命令行界面了,而是进入了更复杂的界面绘制或文本用户界面的领域。有一些专门处理这个的库,但你需要学习并实现其中一个。