如何在Python中存储用户输入而不使用列表?

2024-10-02 08:22:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将用户输入存储为整数,而不将其附加到列表或创建列表。你知道吗

首先,我尝试为每个输入使用5个独立变量(下面的代码),当运行此代码时,它会提供以下内容:

您输入的华氏度是(1、2、3、4、5)

我该怎么去掉那些括号呢?你知道吗

firstFahr = int(input("Please enter a Fahrenheit temperature: "))
secondFahr = int(input("Please enter a Fahrenheit temperature: "))
thirdFahr = int(input("Please enter a third Fahrenheit temperature: "))
fourthFahr = int(input("PLease enter a fourth Fahrenheit temperature: "))
fifthFahr = int(input("Please enter a fifth Fahrenheit temperature: "))

enteredFahrs = firstFahr, secondFahr, thirdFahr, fourthFahr, fifthFahr


print("The fahrenheits you entered are", enteredFahrs)

感谢您的任何帮助,如果这似乎是一个noob问题,道歉,因为我对Python很陌生。你知道吗


Tags: 代码用户列表inputintenterpleasefahrenheit
3条回答

这个怎么样:

prompts = ('first', 'second', 'third', 'fourth', 'fifth')
entered_fahrs = tuple(
   int(input(f'Please enter a {p} Fahrenheit temperature: '))
   for p in prompts
)
print(f'The Fahrenheits you entered are: {", ".join(str(f) for f in entered_fahrs)}')

如果你真的,真的想避免序列,你可以做一个简单的解包:

first_fahr, second_fahr, third_fahr, fourth_fahr, fifth_fahr = entered_fahrs

我怀疑这是真正要求您做的,但是另一种方法是使用生成器表达式来避免完全存储变量。你知道吗

user_inputs = (
   int(input(f'Please enter a {p} Fahrenheit temperature: '))
   for p in ('first', 'second', 'third', 'fourth', 'fifth')
)

print("The fahrenheits you entered are", *user_inputs)

这将解决您的问题:

firstFahr = int(input("Please enter a Fahrenheit temperature: "))
secondFahr = int(input("Please enter a Fahrenheit temperature: "))
thirdFahr = int(input("Please enter a third Fahrenheit temperature: "))
fourthFahr = int(input("PLease enter a fourth Fahrenheit temperature: "))
fifthFahr = int(input("Please enter a fifth Fahrenheit temperature: "))

print("The fahrenheits you entered are", firstFahr, secondFahr, thirdFahr, fourthFahr, fifthFahr)

没有任何列表(也没有括号)。你知道吗

相关问题 更多 >

    热门问题