4 回答

TA貢獻1820條經驗 獲得超3個贊
基本上,沒有。當您使用 input([prompt]) 時,您的“輸入您的年齡:”+“歲”成為提示。輸入總是在最后接受值。
我的問題變成了,你真的需要“歲”的部分嗎?
你總是可以做這樣的事情:
age = input('How old are you?')
print(f'You are {age} years old!')

TA貢獻1850條經驗 獲得超11個贊
實際上是的,但它不太實用:
x = input(" years old \rAge: ") print(x)
這里的技巧是使用\r
(回車) 將光標返回到行首。
請注意,如果用戶鍵入的內容大于給定的空格數,它將覆蓋文本“歲”。

TA貢獻1802條經驗 獲得超10個贊
您可以使用 的實現getch從用戶讀取單個字符。
這是解決方案:
import sys
print("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))

TA貢獻1890條經驗 獲得超9個贊
是的,但您必須學習如何打印、退格和從那里獲取輸入。處理這個問題的常用方法是準確地表達你的問題:
input("Enter your age in years, a whole number: ")
添加回答
舉報