[Tutor] python help
boB Stepp
robertvstepp at gmail.com
Sat Sep 12 13:37:13 EDT 2020
Hello!
On Sat, Sep 12, 2020 at 03:35:53PM +0000, trista rayment via Tutor wrote:
>I need to write a code that asks for a number between 5 and 25 and only allows integers and if a non integer is entered it needs to print 'you must enter an integer' or if it types a number less than 5 or more than 25, it needs to re-ask the original question until it gets an appropriate answer
>would it be better to form an else if or a range or is there a more effective function to put in my code?
>my first thought would be:
>print('Enter an integer between 5 and 25')howMany = input()
Are you aware that "input()" can display a prompt to the screen? So what
you have here could be written:
howMany = input("Enter an integer between 5 and 25)
>limit(int(num, minimum = 5, maximum = 25) else ValueError
Have you encountered "try/except" in your course yet? You seem to realize
that if you call "int("I'm not an integer!")" that you will get a
ValueError. So a "try/except" to the above line:
try:
some_variable = int(num)
# If the above works now handle min/max issues.
except ValueError:
# Insert your code for handling this exception.
>if ValueError = print('Enter an integer between 5 and 25')
>or
>for howMany in range (5, 25) print(....
>or
>while howMany = (>=5, <=25): continue
>else return
Note that a fuller structure for the "if/else" construct goes something
like:
if my_main_check:
# Code to handle if this is true
elif my_other_check:
# Code to handle this is true
.
.
.
elif my_last_check:
# Code to hand if this is true
else:
# None of the above was true -- deal with what's left
Hopefully the individual pieces make more sense. Now you need to put them
together sensibly. You realize you need a loop of some kind and you
suggested a "while" loop. So if you use that you have two obvious ways to
use it:
1) while True:
# Put your input and validation code here.
# But don't want an infinite loop!
# So how do you "break" out of the loop once you have good input?
or,
2) while my_check_condition:
# Put your code here. Loop exits when the above condition becomes
# False.
Hope this provides some help!
--
Wishing you only the best,
boB Stepp
More information about the Tutor
mailing list