0
score = int(input("Please enter a bowling score between 0 and 300: "))

while score >= 1 and score <= 300:
    scores.append(score)

    score = int(input("Please enter a bowling score between 0 and 300: "))

print(scores)

I want the user to enter 10 integers one at a time in a loop and store all ten in a list called scores.

Ismael Padilla
  • 5,246
  • 4
  • 23
  • 35
keira
  • 27
  • 2

5 Answers5

1

You could do something like this, if you do not need the number entered to be restricted within an interval:

scores = []
for i in range(10):
   scores.append(int(input())

This will repeatedly wait for a user input, and store each value in the scores list. If you want the number to be between 1 and 300, simply place the code you already have in a for loop, or create a counter. You could end up with something like this:

scores = []
for i in range(10): 
   score = 0   
   while score >= 1 and score <= 300:
        score = int(input("Please enter a bowling score between 0 and 300: "))
   scores.append(score)
        
print(scores)
Marsolgen
  • 199
  • 1
  • 8
0

If you're okay assuming that all of the input will be valid, you can simply do:

scores = [int(input("Please enter a bowling score between 0 and 300: ")) for _ in range(10)]

This will raise a ValueError if the input isn't convertable to an int, though, and it also won't check for it being in the range. If you want to re-prompt them on invalid inputs until you have 10 valid inputs, you could make "get a valid score" its own function and then build the list with 10 calls to that:

def get_score() -> int:
    while True:
        try:
            score = int(input("Please enter a bowling score between 0 and 300: "))
            if not (0 <= score <= 300):
                raise ValueError(f"{score} isn't between 0 and 300")
            return score
        except ValueError as e:
            print(f"Error: {e}.  Please try again.")

scores = [get_score() for _ in range(10)]
Samwise
  • 68,105
  • 3
  • 30
  • 44
0

If you want for the user to input in different lines then this should work:

inputList = []
for i in range(10):
    inputList.append(input("Enter: "))

But if you want the user to input all values in same line then use:

inputList = map(int, input("Enter: ").split())
0

Let's do a different approach than "try this" as it looks like you're a beginner.

To ask a user for an input you can use the input() function. It'll give you a string. To convert a string to a number you can utilize int(), float() or other functions depending on the properties the number should have (decimal numbers, precision, etc).

To repeat a certain action you need to use a loop. You know while as seen in your code. The loop keyword can be nested i.e. you can have a loop within a loop and you can arrange it so that it's checking for the amount of numbers outside of the number limit condition e.g.:

mylist = []
while len(mylist) < 10:
    num = int(input("some text"))
    while <your number condition>:
        mylist.append(num)
        ...
    ...

or you can utilize for loop that will execute the block of code only N-times e.g. with range(10):

mylist = []
for _ in range(10):
    num = int(input("some text"))
    while <your number condition>:
        mylist.append(num)
        ...
    ...

With a while loop you need to watch out for cases when it might just infinitely loop because the condition is always true - like in your case:

scores = []
score = < a number between 1 and 300, for example 1>

while score >= 1 and score <= 300:  # 1 >= 1 and 1 <= 300  <=> True and True
    scores.append(score)
    score = int(input("Please enter a bowling score between 0 and 300: "))

print(scores)

which will exit in case you enter a number out of the interval but does not guarantee the N-times (10-times) you want. For that to happen you might want to adjust the loop a bit with break to stop the execution after 10 values are present:

scores = []
score = < a number between 1 and 300, for example 1>

while score >= 1 and score <= 300:  # 1 >= 1 and 1 <= 300  <=> True and True
    scores.append(score)
    score = int(input("Please enter a bowling score between 0 and 300: "))
    if len(scores) >= 10:
        break  # stop the while loop and continue to "print(scores)"

print(scores)

However that doesn't handle cases such as inputting 0 or 1000 let's say as once you choose the number out of the interval, it'll stop the while loop even if the amount of scores is less than 10.

And then there's the obvious ValueError when you simply press Enter / Return without entering a number or supply a non-numeric value such as two which is still a number, but will only crash instead converting to 2 with int().

For the first you'd need to encapsulate the number check in other loop or refactor it into something like this:

mylist = []
while len(mylist) < 10:
    num = int(input("some text"))
    if num >= 1 and num <= 300:
        mylist.append(num)

which handles even wrong numeric input e.g. 1000 and will ask for another number.

To handle non-numeric input there are at least two ways - you either let it fail or you check the value first:

With fail first you pass the invalid value to int() automatically and Python interpreter will generate and raise an Exception.

mylist = []
while len(mylist) < 10:
    try:
        num = int(input("some text"))
    except ValueError as error:
        # do something with the error e.g. print(error)
        # or let it silently skip to the next attempt with "continue"
        continue

    if num >= 1 and num <= 300:
        mylist.append(num)

With value validating you can use isnumeric() method which is present on any string instance (which for your case is the return value of input() function):

mylist = []
while len(mylist) < 10:
    num = input("some text")
    if not num.isnumeric():
        continue

    if num >= 1 and num <= 300:
        mylist.append(num)

And to make it more compact, you can chain the comparison, though with one unnecessary int() call when the value is correct assuming most of the values are incorrect. In that case num.isnumeric() evaluates to False first and prevents all int() calls while if the input is numberic you end up calling isnumeric() and 2x int():

mylist = []
while len(mylist) < 10:
    num = input("some text")
    if num.isnumeric() and 1 <= int(num) <= 300:
        mylist.append(int(num))

or the other way around, assuming most of the values are correct you can go for the edge-case of incorrect value with try which would be slower afaik but should be faster than always asking whether a string isnumeric().

mylist = []
while len(mylist) < 10:
    try:
        num = int(input("some text"))
    except ValueError:
        continue
    if 1 <= num <= 300:
        mylist.append(num)

Each of the approaches has its own trade off. You can strive for readability, performance, compactness or any other trait and depending on the trait there will be a way to measure it e.g. for performance you might want to use time.time and for readability a linter such as pylint.

A minor extra, in case you are creating a CLI tool, you might want to handle Ctrl + C (interrupt/kill program, will raise KeyboardInterrupt) and Ctrl + D (end input, will raise EOFError). Both can be handled with try/except.

Peter Badida
  • 11,310
  • 10
  • 44
  • 90
0

First, you have to define the list 'scores'.

while score >= 1 and score <= 300: means that if the input value does not between 0 and 300, the loop will be over. Therefore, you may not be able to complete the list of 10 integers. You can check this condition by using if instead of while.

The while loop need to check if the scores list has 10 elements or not.

scores = []

while len(scores) < 10:
    score = int(input("Please enter a bowling score between 0 and 300:"))
    if (1 <= score <= 300):
        scores.append(score)
    else: 
        print("Score must be between 0 and 300")
        
print(scores)
kbrk
  • 610
  • 1
  • 9
  • 27