So I need to gather input from a user but I have to ensure that they can only enter a number between 1 and 0 before the program accepts their input.
Here is what I've got so far:
def user_input():
try:
initial_input = float(input("Please enter a number between 1 and 0"))
except ValueError:
print("Please try again, it must be a number between 0 and 1")
user_input()
Could someone edit this or explain to me how I can add another rule as well as the ValueError so that it only accepts numbers between 1 and 0?
You can't check the value in the same line as you catch the exception.
Try this:
def user_input():
while True:
initial_input = input("Please enter a number between 1 and 0")
if initial_input.isnumeric() and (0.0 <= float(initial_input) <= 1.0):
return float(initial_input)
print("Please try again, it must be a number between 0 and 1")
EDIT
Removed the try/except and used isnumeric()instead.
Related
We want to create a program that prompts the user to enter a number between 1 and 10. As long as the number is out of range the program reprompts the user for a valid number. Complete the following steps to write this code.
a.Write a line of code the prompts the user for number between 1 and 10.
number = float(input("Enter a number between 1 and 10: "))
b. Write a Boolean expression that tests the number the user entered by the code in step "a." to determine if it is not in range.
x = (number > 10 or number < 1)
c.Use the Boolean expression created in step b to write a while loopthat executes when the user input is out of range. The body of the loop should tell the user that they enteredan invalid number and prompt them for a valid number again.
while x == True:
print("you printed an invalid number")
number = float(input("please enter the number again, this time between 1 and 10"))
d.Write the code that prints a message telling the user that they entered a valid number.
if x == False:
print("wow, you printed a number between 1 and 10!")
I answered the stuff for the question, but my problem is that whenever the user enters a wrong number on their first try and a correct number on their second try, the program still considers it as an invalid input. How do I fix this???
Rewrite this line in the while loop:
x = (number > 10 or number < 1)
so it becomes
while x == True:
print("you printed an invalid number")
number = float(input("please enter the number again, this time between 1 and 10"))
x = (number > 10 or number < 1)
This changes the value of x so it doesn't stay at True
If you use a while True construct, you won't need to repeat any code. Something like this:
LO, HI = 1, 10
while True:
input_ = input(f'Enter a number between {LO} and {HI}: ')
try:
x = float(input_)
if LO <= x <= HI:
print(f'Wow! You entered a number between {LO} and {HI}')
break
print(f'{input_} is not in range. Try again')
except ValueError:
print(f'{input_} is not a valid number. Try again')
Note:
When asking for numeric input from the user, don't assume that their input can always be converted properly. Always check
The following code snippet should do all you need:
number = float(input("Please input a number: "))
while (number > 10 or number < 0):
number = float(input("Error. Please input a new number: "))
Use an infinite loop, so that you can prompt for the input only once.
Use break to terminate the loop after the number in the correct range is entered.
Use f-strings or formatted string literals to print the message.
while True:
num = float(input('Enter a number between 1 and 10: '))
if 1 <= num <= 10:
print('Wow, you printed a number between 1 and 10!')
break
else:
print(f'You printed an invalid number: {num}!')
I'm processing integer inputs from a user and would like for the user to signal that they are done with inputs by typing in 'q' to show they are completed with their inputs.
Here's my code so far:
(Still very much a beginner so don't flame me too much)
def main():
print("Please enter some numbers. Type 'q' to quit.")
count = 0
total = 0
num=[]
num = int(input("Enter a number: "))
while num != "q":
num = int(input("Enter a number: "))
count += 1
total += num
del record[-1]
print (num)
print("The average of the numbers is", total / count)
main()
Any feedback is helpful!
You probably get a ValueError when you run that code. That's python's way of telling you that you've fed a value into a function that can't handle that type of value.
Check the Exceptions docs for more details.
In this case, you're trying to feed the letter "q" into a function that is expecting int() on line 6. Think of int() as a machine that only handles integers. You just tried to stick a letter into a machine that's not equipped to handle letters and instead of bursting into flames, it's rejecting your input and putting on the breaks.
You'll probably want to wrap your conversion from str to int in a try: statement to handle the exception.
def main():
num = None
while num != "q":
num = input("Enter number: ")
# try handles exceptions and does something with them
try:
num = int(num)
# if an exception of "ValueError" happens, print out a warning and keep going
except ValueError as e:
print(f'that was not a number: {e}')
pass
# if num looks like an integer
if isinstance (num, (int, float)):
print('got a number')
Test:
Enter number: 1
got a number
Enter number: 2
got a number
Enter number: alligator
that was not a number: invalid literal for int() with base 10: 'alligator'
Enter number: -10
got a number
Enter number: 45
got a number
Enter number: 6.0222
that was not a number: invalid literal for int() with base 10: '6.0222'
I'll leave it to you to figure out why 6.02222 "was not a number."
changing your code as little as possible, you should have...
def main():
print("Please enter some numbers. Type 'q' to quit.")
count = 0
total = 0
num=[]
num.append(input("Enter a number: "))
while num[-1] != "q":
num.append(input("Enter a number: "))
count += 1
try:
total += int(num[-1])
except ValueError as e:
print('input not an integer')
break
print (num)
print("The average of the numbers is", total / count)
main()
You may attempt it the way:
def main():
num_list = [] #list for holding in user inputs
while True:
my_num = input("Please enter some numbers. Type 'q' to quit.")
if my_num != 'q':
num_list.append(int(my_num)) #add user input as integer to holding list as long as it is not 'q'
else: #if user enters 'q'
print(f'The Average of {num_list} is {sum(num_list)/len(num_list)}') #calculate the average of entered numbers by divide the sum of all list elements by the length of list and display the result
break #terminate loop
main()
I want to force the users input to be between two numbers e.g. 5-15 and if it isn't between or equal too these numbers say please enter a number between these two and request another input.
I already have an input that forces you to enter an interger.
while True:
try:
# asking for race length
race_length = int(input("Choose the Length You Would Like You Race To Be (Between 5 and 15)"))
except ValueError:
print("Sorry, I didn't understand that.")
#if an interger isn't entered do loop above to avoid and error
continue
else:
#race length succesfully found
#finished the loop
break
Use if-else to check if the value is within the required range or not if yes then assign it to the race_length
if not ask user to enter again.
if(x>5 and x<15):
race_length = x
else:
input('Choose the Length You Would Like You Race To Be (Between 5 and 15)')
You can do it raise an error using assert <bool> and handle AssertionError
See the following code,
while True:
try:
race_length = int(input("Choose the Length You Would Like You Race To Be (Between 5 and 15) : "))
assert 5 < race_length < 15
except ValueError:
print("Sorry, I didn't understand that.")
except AssertionError:
print("Please Enter a number between 5 and 15")
else:
break
This code takes the users input and changes it to an integer and then checks if the int is between 0 and 10. I would also like this code to validate the users input against floats and non-numerical strings and loop back if the user enters a bad input. EX: user inputs 3.5 or "ten" and gets an Error and loops again.
pyramid = int(input("Please enter an integer between 0 and 10 to begin the sequence: "))
while pyramid < 0 or pyramid > 10:
print("That value is not in the correct range. Please try again.")
pyramid = int(input("Please enter an integer between 0 and 10 to begin the sequence: "))
I'd suggest to try to:
loop indefinitely (while 1)
Cast the input to a float, if this succeeds you can check if it has any decimals (pyramid % 1 != 0) and print the appropriate error in this case.
Cast the input to a integer and break the loop, if it is.
print an error that the input is not an integer
while 1:
str_in = input("Please enter an integer between 0 and 10 to begin the sequence: ")
try:
pyramid = float(str_in)
if(pyramid % 1 != 0):
print("That value is a float not an integer. Please try again.")
continue
except:
pass
try:
pyramid = int(str_in)
if pyramid >= 0 and pyramid <= 10:
break
except:
pass
print("That value is a string not an integer. Please try again.")
print("Your value is {}".format(pyramid))
I have 2 inputs to type and I want to loop through them if the user would enter incorrect input. What I did is I set while True and then try and except and then continue. However in case of second input if the input is wrong then whole loop is repeated from the start - that is from the first input. I would like it to be repeated from the second input. The only thing that I can think of is to put break in the code after first correct input and then set another while True for the second input. What are better ways to do this?
while True:
try:
a = int(input("Type positive integer: "))
except ValueError:
print(" Enter a positive NUMBER!")
continue
if a <= 0:
print("Input can't be 0 or negative!")
continue
else:
try:
b = int(input("Type second positive integer: "))
except ValueError:
print(" Enter a positive NUMBER!")
continue
if b <= 0:
print("Input can't be 0 or negative!")
continue
else:
break
Since your condition is the same for each loop, you could try storing the try-except part as a function which returns the value (or a bool indicating success or failure with a parameter for the value), running the lambda in a for loop for each input you require, storing the result in a list and then getting what you need out as a tuple.
E.g.
def try_get_number_input():
try:
value = int(input("Type positive integer: "))
except ValueError:
print(" Enter a positive NUMBER!")
return False, 0
if value <= 0:
print("Input can't be 0 or negative!")
return False, 0
return True, value
# We require 2 inputs from the user
required_inputs = 2
received_inputs = []
for num in range(0, required_inputs):
values = try_get_number_input()
while not values[0]:
values = try_get_number_input()
received_inputs.append(values[1])
This ensures that the code is DRY (doesn't repeat itself) and is easily changeable (if you require 3 inputs instead, you can easily change it rather than having to add another branch of your while loop)
def getNumber(second=False):
while True:
try:
if second:
number = int(input("Type second positive integer: "))
else:
number = int(input("Type positive integer: "))
except ValueError:
print(" Enter a positive NUMBER!")
continue
if number <= 0:
print("Input can't be 0 or negative!")
continue
return number
a, b = getNumber(second=False), getNumber(second=True)
print(a,b)
You asked what a for loop would look like, here's one example:
vals = []
for msg in ['', 'second ']:
while True:
try:
n = int(input(f"Type {msg}positive integer: ")) # PY3.6
# n = int(input("Type {}positive integer: ").format(msg))) # <=PY3.5
except ValueError:
print(" Enter a positive NUMBER!")
continue
if n <= 0:
print("Input can't be 0 or negative!")
continue
vals.append(n)
break
a, b = vals
you can use decorator for retry logic and single function to read int value
def retry(func):
def wrapper(msg):
while True:
try:
return func(msg)
except Exception as e:
print(e)
return wrapper
#retry
def read_int(msg):
try:
a = int(input(msg))
except:
raise ValueError('Invalid Number')
else:
if a < 0:
raise ValueError('Number should be positive')
return a
a = read_int('type valid positive number: ')
b = read_int('type other valid positive number: ')
print(a, b)