我正在尝试提出一个问题,并使系统存储该问题的答案并将其打印在Python中



我试图问并回答"你多大了?"这个问题,然后存储用户对该问题的回答并打印出答案。这是我到目前为止所做的:

age = input("How old are you?")
print('How old are you?', word)
agea = input("sixty")

我无法让它存储六十并打印成一个单词。我希望不仅这样做,而且能够将年龄存储和打印为数字。到目前为止,系统只打印答案:

How old are you?

请尽你所能提供帮助。

所以,只是为了添加一些关于你的代码的解释:

age = input("How old are you?") # Read the input from the user and save it to the 'age' variable
print('How old are you?', word) # Print message, using 'word' as a variable. 
# This should throw an error message since 'word' is not assigned anywhere above.
agea = input("sixty") # Print the 'sixty' message, read the user input and save it into 'agea' variable. 
# What I imagine is that you have typing error here. Do you mean 'age' instead of 'agea'?

更正建议

age = input("How old are you?") # Print message and wait for input from the user,
# assigning it to 'age' variable
print(f"You are {age} years old") # Print the message replacing {age} with the variable content.

在python中,像word这样的变量类型没有任何意义。数字是整数或小数,无论其大小如何。该规则有一些例外,但这是一般情况。 现在,对于您的问题 - 函数input()还可以将您的字符串打印到屏幕上,以便用户可以知道他必须输入他的输入。

为了获取用户的年龄,然后打印它,您需要做的是:

age = input("How old are you?")
print("you are ", age, " years old")

这将打印用户的年龄。 如果要将输入转换为int只需写入

age = int(input("How old are you?"))

但要小心这一点,因为如果用户不输入整数,您将收到异常。为了避免这种情况,请执行以下操作:

age = input("How old are you?")
if age.isdigit():
print("you are ", age, " years old")
age = int(age)
else:
print("you must input a number!)

您可以使用字典,如下所示:

num2words = {1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five', 6: 'Six', 7: 'Seven', 8: 'Eight', 9: 'Nine', 10: 'Ten', 
11: 'Eleven', 12: 'Twelve', 13: 'Thirteen', 14: 'Fourteen', 15: 'Fifteen', 16: 'Sixteen', 17: 'Seventeen', 18: 'Eighteen', 
19: 'Nineteen', 20: 'Twenty', 30: 'Thirty', 40: 'Forty', 50: 'Fifty', 60: 'Sixty', 70: 'Seventy', 80: 'Eighty', 
90: 'Ninety', 0: 'Zero'}

def n2w(n):
try:
print (num2words[n])
except KeyError:
try:
print (num2words[n-n%10] + " " + num2words[n%10].lower())
except KeyError:
print ('Number out of range')

if __name__ == "__main__":
a = input("Type you age using numbers:")
n2w(int(a))

在这种情况下,我选择数字作为整数并将其转换为整数。输入和输出为:

Type you age using numbers:55
Fifty five

将变量设置为输入时,变量的值将成为用户在"您多大了?"语句中输入的值。 在这种情况下,如果有人从提示中输入"18",则age等于18,并且会打印You are 18 years old.

age = input("How old are you? ")
print("You are " + age + " years old.")

如果您希望用户输入诸如"sixty"之类的字符串,并且结果类似于You are sixty years old.,那么您可以使输入值只能接受如下所示的字符串值:

age = input("How old are you? ")
if age.isdigit():
print("Invalid")
else:
print("You are " + age + " years old.")
# or # print(f"You are {age} years old")

最新更新