while True:
try:
num = int(input("Enter a number [n>2]: "))
if num <= 2:
raise ValueError
break
except ValueError:
print("Not a number. Try again!")
continue
Is it normal that VSCode is giving me an "undefined variable" on num after asking for user input? I mean, num will be defined when the user enters a number.
It is happening because the VS code debug AI is warning you if you use the num variable in the except block, or somewhere else in the code, it will cause an error. To solve it, you can do this
num = 0
while True:
try:
num = int(input("Enter a number [n>2]: "))
if num <= 2:
raise ValueError
break
except ValueError:
print("Not a number. Try again!")
continue
And it should go away since I have defined the variable num to work in all scenarios
Related
I am getting "Name undefined warning while compiling with try-catch block". Please give some idea about this error.
NAME UNDEFINED ERROR IMAGE
# Importing random package
import random
try:
top_range = int(input("Enter the range:"))
except ValueError:
print("Please enter he Integer Number")
# Getting the random number from system
sys_guess = random.randint(0, top_range)
print("System Guess =", sys_guess)
print("Try to GUESS the Number within 3 entries, MAXIMUM 3 guess......!")
# making for increment
guess = 0
# Guessing the number
while sys_guess >= 0:
user_input = int(input("Enter guessed number: "))
if sys_guess != user_input:
# incrementing the wrong value
guess += 1
print("Wrong Guess-->")
if guess == 2:
print("you have only one guess left")
if guess > 2:
print("Maximum number of guess tried, Failed to obtain the guess!!!!!")
break
else:
# incrementing the correct value
guess += 1
print("!HURRAY***CORRECT GUESS***!")
if sys_guess == user_input:
break
# printing the total number of guess
print("Total Guesses=", guess)
Stick the try catch block in a loop that will continue endlessly until the user enters a valid number. If there is an exception at the moment the top_range value is never defined thus the error.
while True:
try:
top_range = int(input("Enter the range:"))
break
except ValueError:
print("Please enter he Integer Number")
question:
Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore it.
Input:
7 ,2 , bob, 10, 4, done.
Desired output:
Invalid input
Maximum is 10
Minimum is 2
Actual output:
Invalid input
Invalid input
Maximum is 10
Minimum is 2
Code:
largest=-1
smallest=None
while True:
num =input("Enter a number: ")
try:
if num == "done" :
break
elif smallest is None:
smallest=int(num)
elif int(num)<smallest:
smallest=int(num)
elif int(num)>largest:
largest=int(num)
else:
raise ValueError()
except ValueError:
print("Invalid input")
print("Maximum is",largest)
print("Minimum is",smallest)
I think there's a more Pythonic way of doing this. Try this:
inputList = []
while True:
num = input("Enter a number:")
try:
num = int(num)
inputList.append(num)
except:
if num == "done":
break
else:
print ("Invalid input. Ignoring...")
print ("Maximum is:",max(inputList))
print ("Minimum is:",min(inputList))
Edit: This code works with Python3. For Python2, you might want to use raw_input() instead of input()
You are already capturing the ValueError in Exception,
So inside, try, you are raising ValueError there you leave the scope for this error.
When you accept input, and it accepts 4 as input, which is neither larger than largest (i.e. 10) nor smaller than the smallest (i.e. 2). So it lands in else part and raises ValueError (as per your code). Hence prints Invalid input twice in your case. So this part is unnecessary as well as makes your solution bogus.
Again, from efficiency point of view -
1 - You are checking smallest == None for every input, which takes O(1) time and is unnecessary if you take it any integer
Here is the solution you are looking for :-
largest=None
smallest=None
while True:
try:
num = input("Enter a number: ")
num = int(num)
if smallest is None:
smallest = num
if largest is None:
largest = num
if num < smallest:
smallest = num
elif num > largest:
largest = num
except ValueError:
if num == 'done':
break
else:
print("Invalid input")
continue
print("Maximum is",largest)
print("Minimum is",smallest)
In this example I was wondering what I could use instead of BREAK
while (True):
try:
guess = ***********
break
except ValueError:
print(***)
You could initialize guess to an invalid value and test for that.
guess = None
while guess is None:
try:
guess = int(input('Please enter your guess for the roll: '))
except ValueError:
print('Only enter a number please')
When there's no error, guess will be set to an integer, which is not None, so the loop will end.
But I prefer your original code, it's clearer.
Please provide a more information.
loop = True
while (loop):
try:
guess = int(input('Please enter your guess for the roll: '))
loop =False
#break
except ValueError:
print('Only enter a number please')
Another approach using a some lesser known but useful python control flows include using a for/else and try/except/else, it still requires a break but i think it's still a neat alternative
MAX_GUESS = 3
for _ in range(MAX_GUESS):
try:
guess = int(input('Input guess: '))
except ValueError:
print("Try again!")
else:
print("Success!")
break
else:
guess = None
print("Max guesses attempted")
The else block tied to the for/else loop is only entered if a break was NOT encountered during the loop, similarly the else of the try/except/else is only entered if an exception was NOT raised during the try
I'm trying to learn about Pythons error handling and I've currently come across the Try and Except statements.
I have found myself stuck with a problem. I need a User to enter an number between 0-24. If a number is not entered (i.e a string), I need to use except to print "not a number". If a number is entered and it is not between 0-24 I need to raise another error and print " not in range 0-24" Otherwise print "Valid number.
I've been playing around with the code and I have ended up here.
error = False
try:
number = int(input("\nEnter an hour: "))
except ValueError:
print("\nNot an number.")
error = True
while error == false:
try:
if number <0 or number >24:
raise ValueError("number not between 0-24")
else:
print ("\nIts a number and its between 0-24")
Please Help or point me in the right direction:)
I would do that like this basically:
try:
num = int(input('hour? '))
if 0 < num < 25:
print('All good')
print('Hour:', num)
else:
print('Invalid hour')
except ValueError:
print('Not a number')
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()