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
.