how can i limit the input for srj imbetween 1 and 0 and it just restarts the whole program
def gen0(): # input all the initial data
while True: # this will loop infinitely if needed
try: # this will try to take a float from the user
j=int(input('how many juveniles are there in generation 0? '))
srj=float(input('what is the survival rate of juveniles '))
break # if the user gives a number then break the loop
except ValueError: #if the user does not give a number then the user will be told to retry
print("Sorry, there was an error. Please enter a positive number")
Since you are breaking within a try/except, you can simple raise a ValueError if the data is incorrect.
if srj > 1.0 or srj < 0.0:
raise ValueError
put the if statement if srj > 1 or srj < 0:gen0() before the break line
:^)
Related
I've been trying to work with this while loop so I ask for the user input, specifically a number between 99 and 1000. I've been trying to make it so that if your input is within those perimeters, it continues, and if it's not within those perimeters, the input question repeats until it receives a valid input.
while True:
try: #lttr = level two top range
lttr = int(input('Enter a triple digit number between 100 and 1000: '))
if lttr in range(99,1000):
continue
if lttr not in range(99,1000):
break
except:
print("That's not a valid option!")
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
I have been trying to improve my guessing game in Python by limiting the guess input
between 2 numbers(1 and 100) and asking if the guess input is a number or not. I have been trying to do this both at the same time. Is there anyway I can do this by minimum coding?
You can use a while loop to keep asking the user for a valid input until the user enters one:
while True:
try:
assert 1 <= int(input("Enter a number between 1 and 100: ")) <= 100:
break
except ValueError, AssertionError:
print("Input must be an integer between 1 and 100.")
while True:
try:
number = raw_input("Enter a number between 1 and 100: ")
if number.isdigit():
number=int(number)
else:
raise ValueError()
if 1 <= number <= 100:
break
raise ValueError()
except ValueError:
print("Input must be an integer between 1 and 100.")
it is a small improvement over the answer by #blhsing , so that the program does not crash on string input
I am trying to create a number guessing game in Python for a school project. I have made a basic game that will work fairly well, but I want to add in some exception handling in case the user enters something incorrectly. For example, this is a section of my code:
def Normal_Guess():
number = round(random.uniform(0.0, 100.0),2)
guess = ""
while guess != number:
try:
guess = float(input("Please guess a number between 0 and 100: "))
except ValueError or TypeError:
print ("That isn't even a number!")
if guess < number and guess >= 0:
print ("You need to guess higher!")
elif guess > number and guess <= 100:
print ("You need to guess lower!")
elif guess == number:
print("Congratulations! You guessed the number!")
elif guess < 0 or guess > 100:
print ("The number you guessed is not between 0 and 100")
else:
print("That isn't even a number!")
New_Game()
This works fine when the user enters a float or integer value as "guess", and the Try-Except clause I have seems to catch if the user enters anything but a number at first, but the program seems to also carry on to the "if" statements. I am getting a TypeError saying that "'<' not supported between instances of 'str' and 'float'".
I have tried encompassing the entire loop in a Try-Except clause, and that doesn't work. I have no clue what I am doing wrong. Any help is much appreciated.
First off, the way you are catching the exception is invalid. The value of the expression ValueError or TypeError is always just going to be ValueError because that is how short-circuiting works with two non-False arguments. To get both types of errors to trigger the block, use a tuple, like (ValueError, TypeError).
The problem is that even if an exception is caught in your code, it will continue on to the if block. You have four simple options to avoid this:
Use a continue statement in the except block to tell the loop to move on without processing the following if structure:
try:
guess = float(input("Please guess a number between 0 and 100: "))
except (ValueError, TypeError):
print ("That isn't even a number!")
continue
This is probably the cleanest and easiest of the four options.
Do not use an except block to respond to the error. Instead, rely on the fact that the value of guess is still "". For this to work, you will have to pre-initialize guess with every iteration of the loop instead of once outside the loop:
while guess != number:
guess = ""
try:
guess = float(input("Please guess a number between 0 and 100: "))
except (ValueError, TypeError):
pass
if guess == "":
print ("That isn't even a number!")
elif guess < number and guess >= 0:
...
Personally, I am not a fan of this approach because it requires an initialization in every loop. This is not bad, just not as clean as option #1.
A variation on this option is to check directly if guess is an instance of str. You can then initialize it to the user input, making the conversion operation cleaner:
while guess != number:
guess = input("Please guess a number between 0 and 100: ")
try:
guess = float(guess)
except (ValueError, TypeError):
pass
if isinstance(guess, str):
print ("That isn't even a number!")
elif guess < number and guess >= 0:
...
Use the else clause that is one of the possible elements of a try block. This clause gets executed only if no exception occurred:
try:
guess = float(input("Please guess a number between 0 and 100: "))
except (ValueError, TypeError):
print ("That isn't even a number!")
else:
if guess < number and guess >= 0:
...
While this option creates an added layer of indentation, it is a possibility worth keeping in mind for those cases where a plain continue won't work. This happens sometimes when you need to do additional processing for both error and non-error cases, before you branch.
Put the entire if block into the try block. This way it will only be executed if there is no error. This is my least favorite option because I like my try blocks to be as trimmed-down as possible to avoid catching exceptions I did not intend to. In Python, try is relatively less of a performance-killer than in a language like Java, so for your simple case, this is still an option:
try:
guess = float(input("Please guess a number between 0 and 100: "))
if guess < number and guess >= 0:
...
except (ValueError, TypeError):
print ("That isn't even a number!")
Try using an else statement.
Your except catch print, but let script continue running. It will continue to all of if statements even when the catch is hit. What you want to do is skip the main logic of your function when the except is hit. Use the ELSE clause of the try-catch-else-finally block.
import random
def Normal_Guess():
number = round(random.uniform(0.0, 100.0),2)
guess = ""
while guess != number:
try:
guess = float(input("Please guess a number between 0 and 100: "))
except (ValueError, TypeError):
print ("That isn't even a number!")
else:
if guess < number and guess >= 0:
print ("You need to guess higher!")
elif guess > number and guess <= 100:
print ("You need to guess lower!")
elif guess == number:
print("Congratulations! You guessed the number!")
elif guess < 0 or guess > 100:
print ("The number you guessed is not between 0 and 100")
else:
print("That isn't even a number!")
Normal_Guess()
I need to limit the number of invalid inputs allowed so that after the given amount of tries the program exits.
Invalid is defined by the input being less than zero.
The number of attempts let say is 3.
def number():
number = float(input('please enter a number (must be greater thatn zero): '))
if number >= 0 :
print ('you choose number:', number)
else:
print ('invalid input')
return
number()
How would I limit the number of invalid input attempts and make it so that the code would return to asking the question again and prompt for input but still keep track of previous attempts?
You have to use a loop, in this case a while loop will be convinient. You have to declare a variable invalid_attempts to keep the count of how many invalid inputs the user has given.
The condition to finish the loop will be when invalid_attempts, which is increased when you get an invalid input, is greater or equal to 3. You may want to change 3 to fit your requirements:
def get_input():
invalid_attempts = 0
while invalid_attempts < 3:
number = float(input('please enter a number (must be greater thatn zero): '))
if number >= 0 :
print ('you choose number:', number)
return number # so you can call the method as 'some_variable = get_input()'
else:
print ('invalid input')
invalid_attempts += 1
Note: Since number is the name of the method, you shouldn't call a variable inside with the same name (because if you do, you won't be able to use that function inside, if it's necessary), in this case I'm calling the method get_input.
Use whilie loop before number = ..., for instance:
count = 0
while count < 3:
# do rest of the stuffs
count += 1
Actually, I think a for loop looks nicer:
for retry in range(5): # number of retries
try:
choice = float(input('please enter a number (must be greater thatn zero): '))
except ValueError:
print('Please enter an actual number')
continue
if choice >= 0:
print('You chose ', choice)
break
else:
print('Number must be >= 0')
continue
else:
print('Too many failures: be more cooperative')
(This is called a for-else construct; the else runs only if the for loop did not break).
You can also do it slightly more elegantly using recursion:
def get_number(max_tries, count = 0)
if count < max_tries:
valid_input = False
number = 0
try:
number = float(input('Please enter a number > 0'))
if number > 0:
valid_input = True
except:
pass
if valid_input:
return number
else:
return get_numbers(max_tries, count+1)
else:
print('Sorry, Too many Tries!)
return None
Whether you use a while loop or recursion is usually a matter of taste. They're functionally equivalent in many situations, of which this is on. This example also accounts for what happens if the user enters something that isn't a number, which will cause the float cast to throw.
Update:
To clarify a question asked by the OP:
def get_numbers(max_tries, count = 0)
Defines a function get_numbers, which takes two inputs, max_tries and count. count is given a default value, count = 0, which means if you call the function without specifying the count parameter, it will automatically assign it to be 0. max_tries is left without a default value, meaning you need to specify it every time you call the function or python will throw an error. If you usually have the same number of maximum tries, you could also assign this a default value, which would allow you to simply do number = get_numbers() and have it work as expected.
Recursion, to over-simplify, is basically when a function calls itself during its execution. Let's assume we did the following:
number = get_number(10)
And the user enters -1, which will cause the code to reach:
else:
return get_numbers(max_tries, count+1)
Since we said get_numbers(10), max_tries = 10, and count = 0, so this line becomes:
else:
return get_numbers(10, 1)
This causes the function to return the result of calling get_numbers again. Eventually the user will either enter valid input, or count > max_tries, which will cause the function to finally return a value.
Read the wiki I liked to, recursion is hard to explain without drawing it, but hopefully that helps.