What to use instead of BREAK ( PYTHON ) - python

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

Related

Can't create an while infinite loop

I'm trying to build a loop in PyCharm to force the user to submit only integers to the program.
But so far, I've only got the input in loop.
What should I do?
You have to cast the input(). In case the user provides a non-integer number, int() will throw a ValueError you you can subsequently handle as below
while True:
try:
num = int(input("Insert an integer number: "))
except ValueError:
print("Sorry, you must enter an integer.")
continue
else:
print(f"The number is: {num}")
break
This is because input always returns a string. What you can do is to try and convert this string into an int, catch the exception raised when this conversion fails, and ask user to try again. For example, like this:
x = None
while x is None:
try:
x = int(input("Enter Number:"))
except ValueError:
print("Oops, this doesn't seem right, try again!")

Try-Except block - Did I do this correctly?

We are learning exception handling. Did I do this correctly? Is ValueError the correct exception to use to catch strings being typed instead of numbers? I tried to use TypeError, but it doesn't catch the exception.
Also, is there a more efficient way to catch each exception in my four inputs? What is best practice here?
#Ask user for ranges. String inputs are not accepted and caught as exceptions. While loop repeats asking user for input until a float number is input.
while True:
try:
rangeLower = float(input("Enter your Lower range: "))
except ValueError:
print("You must enter a number!")
else:
#Break the while-loop
break
while True:
try:
rangeHigher = float(input("Enter your Higher range: "))
except ValueError:
print("You must enter a number!")
else:
#Break the while-loop
break
#Ask user for numbers. String inputs are not accepted and caught as exceptions. While loop repeats asking user for input until a float number is input.
while True:
try:
num1 = float(input("Enter your First number: "))
except ValueError:
print("You must enter a number!")
else:
#Break the while-loop
break
while True:
try:
num2 = float(input("Enter your Second number: "))
except ValueError:
print("You must enter a number!")
else:
#Break the while-loop
break
Here you are experiencing what is called, WET code Write Everything Twice, we try to write DRY code, i.e. Don't Repeat Yourself.
In your case what you should do is create a function called float_input as using your try except block and calling that for each variable assignment.
def float_input(msg):
while True:
try:
return float(input(msg))
except ValueError:
pass
range_lower = float_input('Enter your lower range: ')
...

Python 3.Beginner confused with multiple error handling.i.e. Try and Except

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

'<' not supported between cases - Number guessing game

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

Python how to only accept numbers as a input

mark= eval(raw_input("What is your mark?"))
try:
int(mark)
except ValueError:
try:
float(mark)
except ValueError:
print "This is not a number"
So I need to make a python program that looks at your mark and gives you varying responses depending on what it is.
However I also need to add a way to stop random text which isn't numbers from being entered into the program.
I thought I had found a solution to this but it won't make it it past the first statement to the failsafe code that is meant to catch it if it was anything but numbers.
So pretty much what happens is if I enter hello instead of a number it fails at the first line and gives me back an error that says exceptions:NameError: name 'happy' is not defined.
How can I change it so that it can make it to the code that gives them the print statement that they need to enter a number?
remove eval and your code is correct:
mark = raw_input("What is your mark?")
try:
int(mark)
except ValueError:
try:
float(mark)
except ValueError:
print("This is not a number")
Just checking for a float will work fine:
try:
float(mark)
except ValueError:
print("This is not a number")
Is it easier to declare a global value than to pass an argument,
In my case it's also gives an error.
def getInput():
global value
value = input()
while not value.isnumeric():
print("enter a number")
value = input("enter again")
return int(value)
getInput()
print(value)
#can't comment :)
You can simply cae to float or int and catch the exception (if any). Youre using eval which is considered poor and you add a lot of redundant statements.
try:
mark= float(raw_input("What is your mark?"))
except ValueError:
print "This is not a number"
"Why not use eval?" you ask, well... Try this input from the user: [1 for i in range (100000000)]
you can use the String object method called isnumeric. it's more efficient than try- except method. see the below code.
def getInput(prompt):
value = input(prompt)
while not value.isnumeric():
print("enter a number")
value = input("enter again")
return int(value)
import re
pattern = re.compile("^[0-9][0-9]\*\\.?[0-9]*")
status = re.search(pattern, raw_input("Enter the Mark : "))
if not status:
print "Invalid Input"
Might be a bit too late but to do this you can do this:
from os import system
from time import sleep
while True:
try:
numb = float(input("Enter number>>>"))
break
except ValueError:
system("cls")
print("Error! Numbers only!")
sleep(1)
system("cls")
but to make it within a number range you can do this:
from os import system
from time import sleep
while True:
try:
numb = float(input("Enter number within 1-5>>>"))
if numb > 5 or numb < 1:
raise ValueError
else:
break
except ValueError:
system("cls")
print("Error! Numbers only!")
sleep(1)
system("cls")
Actually if you going to use eval() you have to define more things.
acceptables=[1,2,3,4,5,6,7,8,9,0,"+","*","/","-"]
try:
mark= eval(int(raw_input("What is your mark?")))
except ValueError:
print ("It's not a number!")
if mark not in acceptables:
print ("You cant do anything but arithmetical operations!")
It's a basically control mechanism for eval().

Categories