![](/img/trans.png)
[英]Python: How do you get a programme to prompt the user a certian fixed amount of times for a user input?
[英]How do you get Python to ask the user for an input 'x' amount of times?
我试图让 Python 根据用户确定的“x”向用户询问相同的问题“x”次数。 所以我试图实现 Python 询问用户“你想找到多少个数字的平均值”。
我以为第一行可能是
x = eval(input('How many numbers would you like to find the average for?: '))
然后对于 Python 询问诸如“输入数字”之类的内容 x 次。
不要使用eval
。 将输入转换为int
x = int(input('How many numbers would you like to find the average for?: '))
然后用它来循环
values = []
for i in range(x):
values.append(int(input('Please enter a value')))
x = eval(input('How many numbers would you like to find the average for?: '))
for count in range (x):
amount = input (f"Enter number{count+1}:\n")
这将基本上帮助您根据他们输入的数量要求用户重复输入,并且当程序每次要求用户输入时,它会按如下方式进行:输入数字 1输入数字 2依此类推,直到程序运行完成,您可以将输入数字更改为您喜欢的任何内容。 复制代码,看看这是否是您想要的,如果有什么不成功,请告诉我。 祝项目好运,希望这会有所帮助。 我的意思是我自己刚刚了解到有关循环输入的知识。
在开始时,您可以创建一个空的“数字”列表:
numbers = []
我建议您使用int()
而不是eval()
。
x = int(input('How many numbers would you like to find the average for? '))
然后您可以启动一个for()
循环并在其中输入一个输入:
for i in range(x):
n = int(input('Number ' + str(i+1) + ': '))
然后仍在循环中使用append()
将数字放入列表中:
for i in range(x):
n = int(input('Number ' + str(i+1) + ': '))
numbers.append(n)
然后对于最后的计算,您可以使用sum()
获取列表中所有数字的总和,然后将其除以列表的长度(使用len()
):
final = sum(numbers) / len(numbers)
但是,如果要对最终数字进行四舍五入,请使用round()
:
final = round(sum(numbers) / len(numbers))
这是最终的代码:
numbers = []
x = int(input('How many numbers would you like to find the average for? '))
for i in range(x):
n = int(input('Number ' + str(i+1) + ': '))
numbers.append(n)
final = sum(numbers) / len(numbers)
finalRounded = round(final)
然后你显然会打印出来。
使用 forLoop 语句...
读取 x,然后
for y in range(0, x): 用户输入到这里(y 是一个 int,将显示你进入 for 语句的次数)
主要是这样
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.