Today i made this function to try and understand the try/except.
If i run this code it should ask for a positive integer x, to roll a dice function x times.
I made the code below but it seems to never get in the "ValueError". I'd like to check if the input (n) is first an integer (digit in the string) and secondly if the integer is positive. if one of these occur, raise the exception.
How can i fix it that it works correctly?
def userInput():
while True:
try:
n=input("How many times do you want to roll the dice? ")
if not n.isdigit():
raise TypeError
n = int(n)
if n < 0:
raise ValueError
else:
break
except ValueError:
#if type is integer but not a positive integer
print("Please enter a positive integer")
except TypeError:
#if type is not an integer
print("Only positive integers allowed")
return n
Stripping out the - doesn't address the issue of some digits not actually being integers, as Matthias's link describes. You would be much better off trying to convert to int without checking isdigit(). If the input can't be converted to an integer, this raises a ValueError with the message "invalid literal for int() with base 10: '...'".
If you want to raise a ValueError with a custom message for your positive number check, you can do raise ValueError("Please enter a positive integer")
Then, in the except block, you can access this message through the .args attribute of the exception:
def userInput():
while True:
try:
n = int(input("How many times do you want to roll the dice? "))
if n < 0:
raise ValueError("Please enter a positive integer")
else:
return n # You probably want to do this instead of just break out of the loop
except ValueError as ex:
print(ex.args[0])
Calling the function gives:
How many times do you want to roll the dice? -5
Please enter a positive integer
How many times do you want to roll the dice? abc
invalid literal for int() with base 10: 'abc'
How many times do you want to roll the dice? 1
To be clear, it would be cheaper to simply print the error message for non-positive integers instead of raising an error only to catch it immediately. That way, you can modify the message that is printed when the int() conversion fails. Consider:
def userInput():
while True:
try:
n = input("How many times do you want to roll the dice? ")
n = int(n)
if n < 0:
print("Please enter a positive integer")
else:
return n # You probably want to do this instead of just break out of the loop
except ValueError as ex:
print(f"Hey, {n} is not a valid integer!")
which would print:
How many times do you want to roll the dice? abc
Hey, abc is not a valid integer!
How many times do you want to roll the dice? 10.5
Hey, 10.5 is not a valid integer!
How many times do you want to roll the dice? -100
Please enter a positive integer
How many times do you want to roll the dice? 100
Your code works perfectly for positive numbers, to handle negative numbers, you need to modify at one place
if not n.lstrip('-').isdigit():
I hope this solves your problem
Related
I am learning about the try and except statements now and I want the program to print out a message when a negative number is inserted but I don't know how to create the order of the statements for this output:
print("how many dogs do you have?")
numDogs= input()
try:
if int(numDogs)>=4:
print("that is a lof of dogs")
else:
print("that is not that many dogs")
except:
print("you did not enter a number")
I want the program to print tje output when the user enters a negative number.
How can I do it?
Just code is like
try:
if no<0:
print("no is negative ")
raise error
And further code will be as it is
Here is what you are trying to achieve.
class CustomError(Exception):
pass
print("how many dogs do you have?")
try:
numDogs = int(input())
if numDogs < 0:
raise CustomError
elif int(numDogs)>=4:
print("that is a lot of dogs")
else:
print("that is not that many dogs")
except CustomError:
print("No Negative Dogs")
except:
print("you did not enter a number")
You can start by creating a custom exception. See https://www.programiz.com/python-programming/user-defined-exception
After which, you should have a condition to first detect the negative value then raise an error from it.
Finally, You can then create multiple excepts to get different error. The first except is raised on input of negative values (as your condition will do for you) whereas the second is used to catch non valid value such as characters.
Note that your int(input) segment should be WITHIN your try block to detect the error
Solution I found is from this SO question
I want the program to print out a message when a negative number is inserted
You can raise a valueError like #Jackson's answer, or you can raise an Exception like in my code below.
elif numDogs < 0:
raise Exception("\n\n\nYou entered a negative number")
def main():
try:
numDogs= int(input("how many dogs do you have? "))
if numDogs >= 4:
print("that is a lot of dogs")
elif numDogs < 0:
raise Exception("\n\n\nYou entered a negative number")
else:
print("that is not that many dogs")
except ValueError:
print("you did not enter a number")
main()
One thing that I though I should point out is that its probably better practice to just check if the number is < 0 or is NAN. But like you said, you're trying to learn about the try and except statements. I thought it was cool that in this code segment:
try:
if numDogs < 0:
raise ValueError
except ValueError:
print("Not a negative Number")
you can throw what error you want and your try will catch it. Guess im still learning a lot too. Only part is, if that happens if your code then one won't know if its a negative number issue or if the number is something like "a", which cannot be converted to one (in this way).
All in all, I think its best to solve this problem with no try / except statements:
def main():
num_dogs = input("# of dogs: ")
if not num_dogs.isnumeric():
return "Error: NAN (not a number)"
num_dogs = int(num_dogs)
return ["thats not a lot of dogs", "that's a lot of dogs!"][num_dogs >= 4] if num_dogs > 0 else "You Entered a negative amount for # of dogs"
print(main())
Notice that I wrapped everything in a `main` function, because that way we can return a string with the result; this is important because if we get an error we want to break out of the function, which is what return does.
How can I check whether the inputted character is number or not and wanted to raise an error for the same in python?
class Error(Exception):
pass
class ValueTooSmallError(Error):
pass
class ValueTooLargeError(Error):
pass
class ValueError(Error):
pass
number = 10
while True:
try:
i_num = float(input("Enter a number: "))
if i_num < number:
raise ValueTooSmallError
elif i_num > number:
raise ValueTooLargeError
break
except ValueTooSmallError:
print("This value is too small, try again!")
print()
except ValueTooLargeError:
print("This value is too large, try again!")
print()
except ValueError: **`this error doesn't reflect`**
print("Input is not a number")
print()
print("Congratulations! You guessed it correctly.")
```
If the input is not a number, it raises ValueError. As such, adding another except statement to catch a ValueError would catch the case when the inputted string is not proper float.
As you are typecasting the given input to float, that statement it self throws an error if given input is not a number.
Ex: float('a') gives following error "ValueError: could not convert string to float: 'a'". So you need to add that exception in your code.
how to find the user input is integer and use same input to compare with existing integer value in python.
class Error(Exception):
"""This is base class for other exceptions"""
pass
class ValueTooSmallError(Error):
"""Exception due to Value is too small"""
pass
class ValueTooLargeError(Error):
"""Exception due to Value is too large"""
pass
number = 10
while True:
try:
i_num = int(input("enter number: "))
if i_num < number:
raise ValueTooSmallError
elif i_num > number:
raise ValueTooLargeError
break
except (ValueTooSmallError):
print("\nValue is too Small, try again")
except (ValueTooLargeError):
print("\nValue is too Large, try again")
print("congratulations, guessed correctly, i.e.", i_num)
How i_num will be validated whether integer value if not should be parsed on exception handling.
If you're asking how do we know if i_num is going to be integer or not, we don't. As python variables are dynamic in nature, whatever value is passed on input will be stored as i_num variable. You have to explicitly add verification methods. Since you're already in a try block and you're using typecast you can easily gather any errors in case input is not an integer(it throws ValueError for typecast mismatches, so you can directly catch that):
while True:
try:
i_num = int(input("enter number: "))
if i_num < number:
raise ValueTooSmallError
elif i_num > number:
raise ValueTooLargeError
break
except ValueError as ve:
print("Parameter passed is incorrect "+str(ve))
except (ValueTooSmallError):
print("\nValue is too Small, try again")
except (ValueTooLargeError):
print("\nValue is too Large, try again")
print("congratulations, guessed correctly, i.e.", i_num)
5.2 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 the number. Enter 7, 2, bob, 10, and 4 and match the output below.
largest = None
smallest = None
while True:
try:
num = input("Enter a number: ")
if num == "done" : break
print(num)
if num > largest:
largest=num
if num < smallest:
smallest=num
except:
print("Invalid input")
print("Maximum is", largest)
print("Minimum is", smallest)
desired output: my output:
Invalid input 2 ← Mismatch
Maximum is 10 4
Minimum is 2 5
maximum is 5(it prints the last input)
minimum is None
I'm a total beginner at programming and python so if the error is obvious pls break it down as much as you could..thank you so much.
The program will never reach print("Invalid input") since there is no error that could be thrown above. If you were to cast num to an integer with num = int(num) after you've checked if num == "done", then the program would catch invalid inputs like "bob"
input() returns a string, so you need to cast the input to integer with int() before comparing it as a number. Also remove your unnecessary print(num).
So change:
print(num)
to:
num = int(num)
The problem is that you are using strings, not numbers. 10 is a number, it is stored as numeric data and you can do things like compare size, add, subtract, etc. Specifically it is an integer, a number with no decimal places (computers store numbers in a lot of different ways). '10' is a string, a set of characters. Those characters happen to represent a number, but the computer doesn't know that. As far as it can tell it is just text.
What you can do to convert a string to an integer is simply num = int(num). If the number can be converted to an integer, it will be. If it can't, you will get an error. That is why the instructions tell you to use a try/catch block. It will catch this error.
Your question already explains what you want to do
If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message
The explanation of why is that you need int(num) after you check for done, to try converting a string to an integer, and catch exception that happens for non integer inputs
I suggest you remove the try except, type anything but a number and observe the behavior
I don't know why i'm getting a syntax error on 'excpet'. All seems well to me! Here's my code:
def length():
gameLength = int(input("How many words do you want to play? You can chose anywhere from 1-40: "))
global gameLength
if gameLength <= 40 and gameLength >= 1:
quit
else:
int(input("Please choose a number between 1 & 40 "))
except ValueError = True:
int(input("Please choose a number between 1 & 40 "))
return gameLength
You need to indent your code correctly, and add a try statement before the except. You also need to evaluate the true with '==' instead of '='.
def length():
global gameLength
gameLength = int(input("How many words do you want to play? You can chose anywhere from 1-40: "))
if gameLength <= 40 and gameLength >= 1:
quit
else:
try:
int(input("Please choose a number between 1 & 40 "))
except ValueError == True:
int(input("Please choose a number between 1 & 40 "))
return gameLength
Solution:
First, you got to indent your function (not the main error). Now on to the next errors:
1. You must have a try statement before having an except. Also, rather than repeating the same function, you should use return ValueError. Here, I modified the code but made it what you desired:
try:
if gameLength <= 40 and gameLength >= 1:
quit
else:
return ValueError
except ValueError: // or except ValueError == true
length()
Look at the line with except ValueError = true:. One equal sign means you are assigning ValueError to equal true, like you say x = 10. Two equal signs mean that you are asking, "does it equal true?", like saying 1 + 5 == 6 will return true, because 1+5 IS 6. Now go back to your ValueError.
Change your except line with: except ValueError == true. Now you're asking, "is the ValueError equal to true?" rather than saying, "ValueError MUST equal true!" You can also say except ValueError because if statements and other statements always go if it returns true. For example, if true: will work or while true will go on forever, but if 1+1==3: will never work, because 1+1==3 returns false.
Assign gameLength as a global variable before assigning it a value.
Put gameLength in the try statement:
try:
gameLength = int(input("How many..."))
Why? Because if you put it before the try statement and the input was, for instance, "hi", you can't make "hi" an integer. Try statements try to do something, and after failing, doesn't just give up and return an error, but does what the programmer wants it to do. In this case, we want it to repeat the function, so we will do length() on the except. And that's
repeating the function over and over.
except ValueError:
print("Please type a number from 1-40.")
length()
Finally, I'll change one more thing:
quit is a function. Make it quit(), or it won't quit, as you expected.
Output (And Code)
def length():
global gameLength
try:
gameLength = int(input("How many words do you want to play? You can choose any number from 1-40: "))
if gameLength <= 40 and gameLength >= 1:
quit()
else:
return ValueError
except ValueError:
print("Please type a number from 1-40.")
length()
return gameLength
length()
IDLE: How many words do you want to play? You can choose any number from 1-40:
ME: "I'm a string."
IDLE: Please type a number from 1-40.
IDLE: How many words do you want to play? You choose any number from 1-40:
ME: 54919
IDLE: Please type a number from 1-40.
IDLE: How many words do you want to play? You choose any number from 1-40:
ME: 37.1
*Making number an integer: 37.1 => 37.
CON: 37
Quitting Python.