0

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 
3
  • if readingsCount > 0 to check for a +ve number should be good enough. Commented Apr 9, 2020 at 10:20
  • 1
    Your last if can be removed and the lines under it should replace the break. I don't think that break does what you mean anyway. Commented Apr 9, 2020 at 10:20
  • 1
    Do you really want to break from the loop and return (implicit) None if a positive integer was entered? Commented Apr 9, 2020 at 10:24

3 Answers 3

3

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?

Sign up to request clarification or add additional context in comments.

4 Comments

Ah amazing thank you. No the doubling of readingsCount is an error on my part!
Suggestion for the first line: def enterReadings(message:str="Enter a positive number: ") -> int:
In the original code readingsCount isn't doubled. The program never reaches that part of the code.
Sure, change int to float.
0

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

Comments

-1

I think it is absolutely OK, you check if an input is a number (int) and is positive.

Clear is better than clever.

1 Comment

It is not okay. Try to print out the returned result for a correct entry.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.