Reputation: 69
I've written function enterReadings for the user to enter a number and I've got the following verification to ensure it's a positive integer. I'm thinking that there's a simpler way to write this but don't know where to start, any help is massively appreciated!
def enterReadings(message):
while True:
try:
readingsCount = int(input(message))
if readingsCount <= 0:
print("Please enter a positive integer")
continue
break
except ValueError:
print("Please enter a positive integer")
readingsCount = 0
if readingsCount > 0:
readingsCount += readingsCount
return readingsCount
Upvotes: 0
Views: 452
Reputation: 12927
A bit shorter:
def enterReadings(message):
while True:
try:
readingsCount = int(input(message))
assert readingsCount > 0
return readingsCount
except:
print("Please enter a positive integer")
BTW why do you double your readingsCount
? Is that what you intended?
Upvotes: 3
Reputation: 950
In python, int
can also be negative, so you have to check it.
Python 3.8+:
def enterReadings(message):
while True:
try:
if (n := int(input(message))) > 0:
return 2*n
except ValueError:
pass
print("Please enter a positive integer")
Upvotes: 0
Reputation: 77
I think it is absolutely OK, you check if an input is a number (int) and is positive.
Clear is better than clever.
Upvotes: -1