简体   繁体   中英

How do you get Python to ask the user for an input 'x' amount of times?

I am trying to get Python to ask the user the same question 'x' amount of times depending on what the user determines 'x' to be. So I am trying to achieve for Python to ask the user 'how many numbers would you like to find the average for'.

I thought the first line could be

x = eval(input('How many numbers would you like to find the average for?: '))

and then for Python to ask something like 'Enter a number' an x amount of times.

Do not use eval . Convert the input to int

x = int(input('How many numbers would you like to find the average for?: '))

Then use that to loop

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")

This will basically help you to ask the user for repeated inputs depending on the amount they entered, and also when the program asks the user for input every time it will go as follows: Enter number 1 Enter number 2 and so on until the program is completed and you can change Enter Number to anything you like. Copy the code and see if that's what you wanted, let me know if something doesn't work out. Good luck with the program and hopefully this helped. I mean I just learned this myself about the looped inputs.

At the start you can create a empty "numbers" list:

numbers = []

And I'd recommend for you to use int() instead of eval() .

x = int(input('How many numbers would you like to find the average for? '))

Then you can start a for() loop and put an input inside it:

for i in range(x):
    n = int(input('Number ' + str(i+1) + ': '))

And then still in the loop use append() to put the numbers in the list:

for i in range(x):
    n = int(input('Number ' + str(i+1) + ': '))
    numbers.append(n)

Then for the calculation at the end you can use sum() to get the sum of all the numbers in the list, and then divide it by the length (using len() ) of the list:

final = sum(numbers) / len(numbers)

But if you want to round the final number, use round() :

final = round(sum(numbers) / len(numbers))

And this is the final code:

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)

Then you would obviously print it out.

use a forLoop statement...

read x, then

for y in range(0, x): user input goes here (y is an int that will show how many times youve gone into the for statement)

and thats mainly it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM