ValueError validation loop [duplicate] - python

This question already has answers here:
How can I check if string input is a number?
(30 answers)
Closed 3 years ago.
I'm starting out with Python after taking a class that taught us pseudocode. How could I make a validation loop to continue the function if a user inputted a decimal rather than a whole number? At its current state, I've gotten it to recognize when a user enters a number outside of the acceptable range, but if the user enters a decimal number, it crashes. Is there another validation loop that can recognize a decimal?
def main():
again = 'Y'
while again == 'y' or again == 'Y':
strength_score = int(input('Please enter a strength score between 1 and 30: '))
# validation loop
while strength_score < 1 or strength_score > 30 :
print ()
print ('Error, invalid selection!')
strength_score = int(input('Please enter a whole (non-decmial) number between 1 and 30: '))
# calculations
capacity = (strength_score * 15)
push = (capacity * 2)
encumbered = (strength_score * 5)
encumbered_heavily = (strength_score * 10)
# show results
print ()
print ('Your carrying capacity is' , capacity, 'pounds.')
print ('Your push/drag/lift limit is' , push, 'pounds.')
print ('You are encumbered when holding' , encumbered, 'pounds.')
print ('You are heavyily encumbered when holding' , encumbered_heavily, 'pounds.')
print ()
# technically, any response other than Y or y would result in an exit.
again = input('Would you like to try another number? Y or N: ')
print ()
else:
exit()
main()

Depending on what you want the behavior to be:
If you want to accept non-integer numbers, just use float(input()). If you want to accept them but turn them into integers, use int(float(input())) to truncate or round(float(input())) to round to the nearest integer.
If you want to print an error message and prompt for a new number, use a try-catch block:
try:
strength_score = int(input('Please enter a strength score between 1 and 30: '))
except ValueError:
again = input("Invalid input, try again? Y / N")
continue # skip the rest of the loop

That is because you have strength_score as an int, and not a float.
Try changing
strength_score = int(input('Please enter a strength score between 1 and 30: '))
to
strength_score = float(input('Please enter a strength score between 1 and 30: '))
Tested with 0.1 and 0.0001 and both are working properly.

Related

Fixing While Loops Python

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}!')

Python: Input validation against a float and a string

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

My while loop should be running until the user wants to stop it but ends after the 2nd input

I feel like the question is not well worded for a question, but this is what I really want:
I am writing this code where a 'user' can enter as many integers from 1 to 10 as he/she wants. Every time after the user has entered an integer, use a yes/no type question to ask whether he/she wants to enter another one. Calculate and display the average of the integers in the list.
Isn't 'while' supposed to running part of a program over and over and over again until it stops when it is told not to?
num_list = []
len()
integer_pushed = float(input("Enter as many integers from 1 to 10"))
num_list.append(integer_pushed)
again = input("Enter another integer? [y/n]")
while integer_pushed < 0 or integer_pushed > 10:
print('You must type in an integer between 0 and 10')
integer_pushed = float(input("Enter as many integers from 1 to 10"))
num_list.append(integer_pushed)
again = input("Enter another integer? [y/n]")
while again == "y":
integer_pushed = float(input("Enter as many integers from 1 to 10"))
num_list.append(integer_pushed)
again = input("Enter another integer? [y/n]")
print ("Number list:", num_list)
while again == "y":
integer_pushed = float(input("Enter as many integers from 1 to 10"))
num_list.append(integer_pushed)
again = input("Enter another integer? [y/n]")
print ("Number list:", num_list)
It stops after the 2nd time even if the user types in 'y'. It then gives me the 'Number List: ".
Once again, you guys have been great assisting my classmates and I. Im in an introduction to Python course and we are learning about loops and lists.
One while loop is sufficient to achieve what you want.
num_list = []
again = 'y'
while again=='y':
no = int(input("Enter a number between 1 and 10: "))
if not 1 <= no <= 10:
continue
num_list.append(no)
again = input("Enter another? [y/n]: ")
print("Average: ", sum(num_list) / len(num_list))
The while loop runs as long as again == 'y'. The program asks for another number if the user inputs an integer not between 1 and 10.
Try this:
num_list = []
again = "y"
while again == "y":
try:
integer_pushed = float(input("Enter as many integers from 1 to 10"))
if integer_pushed > 0 or integer_pushed <= 10:
num_list.append(integer_pushed)
again = input("Enter another integer? [y/n]")
print("Number list:", num_list)
else:
print('You must type in an integer between 0 and 10')
except ValueError:
print('You must type in an integer not a str')
I'm not sure why you had two different while loops, let alone three. However, this should do what you want. It will prompt the user for a number, and try and convert it to a float. If it can't be converted, it will prompt the user again. If it is converted it will check to see if it's between 0 and 10 and if it is, it will add it to the list, otherwise, it will tell the user that that's an invalid number.

How to Separate a Range of Odd and Even Numbers Through Searching the Array While Skipping Numbers

I'd like to challenge myself and develop my programming skills. I would like to create a program that asks for the user to enter a range of numbers where odd and even numbers should be separated (preferably through search) and also separated by a specified jump factor.
Also the user should be allowed to choose whether or not they would like to continue. And if so they can repeat the process of entering a new range.
for example when the program is run a sample input would be:
"Please enter the first number in the range": 11
"Please enter the last number in the range": 20
"Please enter the amount you want to jump by": 3
and the program would output:
"Your odd Numbers are": 11,17
"Your even Numbers are": 14,20
"Would you like to enter more numbers(Y/N)":
So far what I have for code is this but am having trouble putting it together and would appreciate some help.
import sys
print("Hello. Please Proceed to Enter a Range of Numbers")
first = int(input("please enter the first number in the range: "))
last = int(input("please enter the last number in the range: "))
jump = int(input("please enter the amount you want to jump by: "))
def mylist(first,last):
print("your first number is: ",first,"your last number is: ",last,"your jump factor is: ",jump)
def binarySearch (target, mylist):
startIndex = 0
endIndex = len(mylist) – 1
found = False
targetIndex = -1
while (not found and startIndex <= endIndex):
midpoint = (startIndex + endIndex) // 2
if (mylist[midpoint] == target):
found = True
targetIndex = midpoint
else:
if(target<mylist[midpoint]):
endIndex=midpoint-1
else:
startIndex=midpoint+1
return targetIndex
print("your odd Numbers are: ")
print("your even Numbers are: ")
input("Would you like to enter more numbers (Y/N)?")
N = sys.exit()
Y = first = int(input("please enter the first number in the range"))
last = int(input("please enter the last number in the range"))
jump = int(input("please enter the amount you want to jump by: "))
question - "So far what I have for code is this but am having trouble putting it together and would appreciate some help."
answer -
As a start, it seems like a good idea to group your inputs and outputs into functions! Then putting it together is a snap!
def get_inputs():
bar = input('foo')
def process_inputs():
bar = bar + 1
def print_outputs():
print(bar)
if '__name__' == '__main__':
get_inputs()
process_inputs()
print_outputs()
You could even toss in something like if input('more? (Y/N):') == 'Y': in a while loop.
Maybe I'm missing something but couldn't you replace your binary search with the following?
>>> list(filter(lambda x: x%2 == 1, range(11, 20 + 1, 3)))
[11, 17]
>>> list(filter(lambda x: x%2 == 0, range(11, 20 + 1, 3)))
[14, 20]

Checking input is a number in python

I need help, my program is simulating the actions of a dice. I want to an error check to occur checking if the input string is a number and if it isn't I want to ask the question again again until he enters an integer
# This progam will simulate a dice with 4, 6 or 12 sides.
import random
def RollTheDice():
print("Roll The Dice")
print()
NumberOfSides = int(input("Please select a dice with 4, 6 or 12 sides: "))
Repeat = True
while Repeat == True:
if not NumberOfSides.isdigit() or NumberOfSides not in ValidNumbers:
print("You have entered an incorrect value")
NumberOfSides = int(input("Please select a dice with 4, 6 or 12 sides")
print()
UserScore = random.randint(1,NumberOfSides)
print("{0} sided dice thrown, score {1}".format (NumberOfSides,UserScore))
RollAgain = input("Do you want to roll the dice again? ")
if RollAgain == "No" or RollAgain == "no":
print("Have a nice day")
Repeat = False
else:
NumberOfSides = int(input("Please select a dice with 4, 6 or 12 sides: "))
As a commenter disliked my first answer with try: except ValueError and the OP asked about how to use isdigit, that's how you can do it:
valid_numbers = [4, 6, 12]
while repeat:
number_of_sides = 0
while number_of_sides not in valid_numbers:
number_of_sides_string = input("Please select a dice with 4, 6 or 12 sides: ")
if (not number_of_sides_string.strip().isdigit()
or int(number_of_sides_string) not in valid_numbers):
print ("please enter one of", valid_numbers)
else:
number_of_sides = int(number_of_sides_string)
# do things with number_of_sides
the interesting line is not number_of_sides_string.strip().isdigit(). Whitespace at both ends of the input string is removed by strip, as a convenience. Then, isdigit() checks if the full string consists of numbers.
In your case, you could simply check
if not number_of_sides_string not in ['4', '6', '12']:
print('wrong')
but the other solution is more general if you want to accept any number.
As an aside, the Python coding style guidelines recommend lowercase underscore-separated variable names.
Capture the string in a variable, say text. Then do if text.isdigit().
Make a function out of:
while NumberOfSides != 4 and NumberOfSides != 6 and NumberOfSides != 12:
print("You have selected the wrong sided dice")
NumberOfSides = int(input("Please select a dice with 4, 6 or 12 sides: "))
And call it when you want to get input. You should also give an option to quit e.g. by pressing 0. Also you should try catch for invalid number. There is an exact example in Python doc. Note that input always try to parse as a number and will rise an exception of it's own.
You can use type method.
my_number = 4
if type(my_number) == int:
# do something, my_number is int
else:
# my_number isn't a int. may be str or dict or something else, but not int
Or more «pythonic» isinstance method:
my_number = 'Four'
if isinstance(my_number, int):
# do something
raise Exception("Please, enter valid number: %d" % my_number)

Categories