Python3: creating error for input of negative - python

Taking an intro course and need to create an over/under guessing game. I want to fine-tune my user inputs by creating an error if someone inputs a negative or non-integer. I have the non-integer error reporting correctly, and the negative loops back correctly, but the negative will not print my error message.
#Number of plays
def get_plays(msg):
while True:
try:
x = (int(input(msg)))
except ValueError:
print ("Integer numbers only please.")
except:
if x <=0:
print ("Positive numbers only please.")
i = get_plays("\nHow many times would you like to play?")
print ("The game will play " +str(i)+" times.")
Separately, if I wanted to use a similar setup to produce an error for any negative non-integer number between 1 and 20, how would this look?

Try:
def get_plays(msg):
while True:
try:
x = (int(input(msg)))
if x <=0:
print("Positive numbers only please.")
continue
if x not in range(20):
print("Enter a number between 1 - 20.")
continue
return x
except ValueError:
print("Integer numbers only please.")
It will accept only positive numbers between 1 to 20

The problem is this section
except:
if x <=0:
Empty except clauses trigger on any error that hasn't been caught yet, but negative numbers don't trigger an exception. You want something like this instead. Notice that in the try clause we can just proceed as if x is an int already, because we can assume that no ValueError was thrown.
def get_plays(msg):
while True:
try:
x = (int(input(msg)))
if x <=0:
print ("Positive numbers only please.")
else:
return x
except ValueError:
print ("Integer numbers only please.")

Related

Counting down the user inputs

Basic python learning:
I am asked to write a program that makes a list of 15 integer entries (size) the user inputs. For each input, the program should give the number of integers remaining to input. In the end, the program should list the 15 entries, and tell the user he is done.
With the code below, I get the list and the final report, but can't really figure out how to count down, print the remaining entries, and tell the user he is done.
my_list = []
for _ in range(15):
try:
my_list.append(int(input('Enter size: ')))
except ValueError:
print('The provided value must be an integer')
print(my_list)
One thing to figure out is "what to do if the user inputs something that is not a valid integer?" You can solve that by keeping asking the user for an input until it's a valid number.
You can do that using a while loop with a boolean variable:
good_int = False
while not good_int:
try:
num = int(input(f'Enter an integer: '))
good_int = True
except ValueError:
print('I said int, gorramit!!')
Now that we have that, there is a lot of approaches you can take here.
One of the interesting things a for loop can do is count backwards.
You can try:
my_list = []
for i in range(15, 0, -1):
good_int = False
while not good_int:
try:
my_list.append(int(input(f'Enter size for iteration {i}: ')))
good_int = True
except ValueError:
print('The provided value must be an integer')
print("Aight, you're done. This is the list:")
print(my_list)
Or... probably what is better, use a variable to store the number of tries (15) and don't consider a "valid try" until the user inputted a valid integer.
my_list = []
tries = 15
while tries > 0:
try:
my_list.append(int(input(f'Enter size for iteration {tries}: ')))
tries = tries - 1 # Or just tries -= 1
except ValueError:
print('The provided value must be an integer')
print("Aight, you're done. This is the list:")
print(my_list)
Since you don't want the loop to repeat a fixed number of times, but instead need it to repeat until you have 15 values, you should consider using a while instead of a for.
my_list = []
while len(my_list) < 15:
try:
my_list.append(int(input('Enter size: ')))
except ValueError:
print('The provided value must be an integer')
print(f'You are done: {my_list}')
It may be a good idea to inform the user how many values they still have to enter:
my_list = []
while len(my_list) < 15:
try:
my_list.append(int(input(f'Enter size ({15 - len(my_list)} left): ')))
except ValueError:
print('The provided value must be an integer')
print(f'You are done: {my_list}')
You're going to need to use a counter variable, which simply keeps track of the amount of numbers left for the program to receive. You will print it out after every input, and then subtract 1 from the variable. I added a check to make sure that we don't print out "You have to input 0 more numbers" since that isn't what we really want to do.
my_list = []
numbers_left = 15
for _ in range(15):
try:
my_list.append(int(input('Enter size: ')))
numbers_left = numbers_left - 1
if numbers_left != 0:
print("You have to input " + str(numbers_left) + " numbers to complete the program.")
except ValueError:
print('The provided value must be an integer')
print(my_list)
You can print with f strings and the deincrement the number for each for loop. I am not sure about the try and for loop isn't this better?
EDIT: Changed the for loop and gives errors on string vals.
my_list=[]
len_val=15
val=0
while val<len_val:
try:
my_list.append(int(input("Enter size:")))
val+=1
print(f"{(len_val-val)}to go!")
except ValueError:
print("Enter an integer")
print(len(my_list))
range(14, 0, -1) will do the job for you.
my_list = []
for i in range(14, 0, -1):
try:
my_list.append(int(input('Enter size: ')))
print(f'{i} to go')
except ValueError:
print('The provided value must be an integer')
print(my_list)
If you have ValueError during the execution. I would suggest using a while loop. Like this
my_list = []
size = 15
while len(my_list) < size:
try:
my_list.append(int(input(f'Enter size : ')))
print(f'{size-len(my_list)} to go')
except ValueError:
print('The provided value must be an integer')
print(f'You are done: {my_list}')

Try/Except handling

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

How to print a message to the user when a negative number is inputed?

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.

Python: input validation not working

I have this code:
#counting the number down to zero.
x = int(x)
while x>=0:
print x
x -= 1
#if the user asks for a number below zero print this:
if x<0:
print "You cant countdown number below zero."
#if the user asks for something else than a number print this:
else:
print "only insert numbers."
The code itself is really basic, just counting a random number down till zero.
The only problem is that my else block is not working, I made the else block for when someone writes a word/letter instead of a number. Can anyone please solve this problem? :)
EDIT:
The error that I am getting is:
ValueError: invalid literal for int() with base 10: 'ha'
You should use a different approach. First validate the input:
try:
x = int(x)
except ValueError:
print "only insert numbers"
#return from function, or exit the program, or whatever you want
while x >= 0:
print x
x -= 1
if x < 0:
print "You cant countdown number below zero."

Python user must only enter float numbers

I am trying to find out how to make it so the user [only enters numbers <0] and [no letters] allowed. Can someone show me how I would set this up. I have tried to set up try/catch blocks but I keep getting errors.
edgeone = input("Enter the first edge of the triangle: ")
I think you want numbers only > 0, or do you want less than zero? Anyway to do this you can using try/except, inside a while loop.
For Python 3, which I think you are using?
goodnumber = False
while not goodnumber:
try:
edgeone = int(input('Enter the first edge of the triangle:'))
if edgeone > 0:
print('thats a good number, thanks')
goodnumber = True
else:
print('thats not a number greater than 0, try again please')
except ValueError:
print('Thats not a number, try again please')
hope this helps.
you must use except handler for this case :
try:
value = int(raw_input("Enter your number:"))
if not ( value < 0 ):
raise ValueError()
except ValueError:
print "you must enter a number <0 "
else:
print value #or something else
Also This question already has an answer here: Accepting only numbers as input in Python
You can do like this.
i = 1
while(type(i)!=float):
i=input("enter no.")
try:
int(i):
except:
try:
i = float(i)
except:
pass
print(i)

Categories

Resources