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."
Related
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 2 years ago.
I am trying to get this input below to work, I want to if the user puts in a number less then 10 to say you need to put a higher number, then get them to input another number. until they pick a number that is accepted.
However, my code does not pick up the result of the user and does pick the correct response or move on when someone say picks 50.
It just loops forever. Is there any way to fix this?
def weapons_(aaa,numguns,numknifes,numbombs,numswords):
print("Good job!")
while True:
try:
aaa = input("""Enter you're number accordinly to the list above:""")
number = int(aaa)
print("this is a num, thank you")
while number <=10:
print ("You need to pick a number between 50 and 200")
if number <= 50:
print(x)
break
elif number <= 100:
print (y )
break
elif number<= 150:
print (m + p)
break
elif number <= 200:
print (z)
break
except ValueError:
print("this is not a number, please try again")
One thing - please format the code with backticks just before 'def'. The backtick is `, just above escape key on my laptop. Also, its good style to try to only use the three speech marks for multiline comments, you don't need it to designate a string (is what I've been told anyway) :) Finally, most of your number checks in the second code block aren't needed, because no numbers that meet the required conditions will enter the code block - if you want these to be done still then move them away from a conditional that excludes all values of number that can satisfy them (i.e. if you have a number variable with 99, this wont cause y to be printed, because it is above 10, so wont satisfy while number <=10:. This means it wont execute any of the code below while number <=10:).
Anyway, I think the problem is when someone inputs 50 or a good answer, it will print your variable (x if its under 50, y under 100 etc), and then it will ask for user input with """Enter you're number accordinly to the list above:""". Right?
This is happening because your break is only escaping the inner while loop - it will just go back to the outer while loop (i.e. While True) when this happens, and ask everything again. To fix this, try putting:
while True:
try:
aaa = input("""Enter you're number accordinly to the list above:""")
number = int(aaa)
print("this is a num, thank you")
#####this######
if number >10:
#do whatever you want when the user enters a number between 10 and 200. Break will exit all the while loops
print ('ok')
break
###############
while number <=10:
print ("You need to pick a number between 50 and 200")
#this code will only be entered if number is less than or equal to 10. So any value of number above 10 wont cause this code to execute. so all the conditions checking 100-200 are not going to be entered
if number <= 50:
print(x)
break
elif number <= 100:
print (y )
break
elif number<= 150:
print (m + p)
break
elif number <= 200:
print (z)
break
except ValueError:
print("this is not a number, please try again")
I'm trying to create a small code that asks a user to enter a number between 1 and 100. However my Else statement will not output when entering a string. I want my Else statement to print a message if the user enters an input other than an integer or float. Here is my code.
def between():
print ("Please enter a number between 1 and 100.")
number = eval(input())
if number >= 1 and number <= 100:
print ("Thank you! You entered",number,"which is within the 1 and 100 range.")
between()
elif number > 100 or number < 1:
print ("OOPS! You entered",number,"Please enter a number between 1 and 100.")
between()
else:
print ("ERROR! You have entered an invalid value. Please try again using numerical values only.")
between()
between()
The easiest method would be to use try and except
num = input()
try:
number = float(num)
# code to do if num is a number
except ValueError:
print("Not a number!")
# code to do if num isn't a number
If num isn't a number, then converting it to a float would raise ValueError going on to the except.
If num is a number, the coversion of it to a float would run fine, and continue on in the try.
Side note: I highly suggest not using eval(input()) but rather just input(), see this for why you shouldn't use eval. Also eval(input()) won't work with my example above.
Try this:
print "Please enter a number between 1 and 100"
in = input()
try:
num = int(in)
if 1 <= num <= 100:
print("Valid")
else:
print("Out of bounds")
except:
print("Invalid")
Try:
def between():
print ("Please enter a number between 1 and 100.")
number=0
try:
number = int(input())
except:
print ("ERROR! You have entered an invalid value. Please try again using numerical values only.")
exit(1)
if number >= 1 and number <= 100:
print ("Thank you! You entered",number,"which is within the 1 and 100 range.")
between()
else:
print ("OOPS! You entered",number,"Please enter a number between 1 and 100.")
between()
between()
Note: why you use eval and input together? I don't think that's right, correct me if I'm wrong
There are a few logical issues with your code. First before using eval() you must be aware of the security risk associated with it. Consider going through this post for some insight. If you entered some arbitrary input in eval, it will most likely be a run time error.
Now, assuming that the variable actually has a value. To check if it is an integer or a float and is in the desired range or something else (possibly a string), you can not directly apply comparison operators with it because if the variable is not a number it will most likely give a TypeError during comparison with other integers.
Hence a correct approach would be to first check if the variable is of desired type by checking if type(r) is int or type(r) is float only then you should apply test for range. If the above type checking is false then you should print your "else" error message.
Try is too slow and should be avoided when not necessary
num = input("Please enter a number between 1 and 100: ")
if num.replace('.','').isdigit():
num = float(num)
if number >= 1 and number <= 100:
print ("Thank you! You entered",number,"which is within the 1 and 100 range.")
between()
else:
print ("OOPS! You entered",number,"Please enter a number between 1 and 100.")
between()
else:
print('thats not a number!')
I am a new learner for Python. I have a question about while loop.
I wrote a program below to look for square roots.
When I input anything but integers, the message "is not an integer" shows up and it repeats itself until I input correct data(integers).
My question is, why does it end loop when it return value on line 5, return(int(val))?
Thank you for your attention.
def readInt():
while True:
val = input('Enter an integer: ')
try:
return(int(val))
except ValueError:
print(val, "is not an integer")
g = readInt()
print("The square of the number you entered is", g**2)
To answer your original question, 'return' effectively exits the loop and provide the result that follows the 'return' statement, but you have to explicity print it like so:
def read_int(num1, num2):
while True:
return num1 + num2
print(read_int(12, 15))
If you simply put 'read_int(12, 14)' instead of 'print(read_int(12, 15))' in this scenario, you won't print anything but you will exit the loop.
If you allow me, here are some modifications to your original code:
def read_int(): # functions must be lowercase (Python convention)
while True:
val = input('Enter an integer: ')
try:
val = int(val) # converts the value entered to an integer
minimum_value = 0 # There is no need to evaluate a negative number as it will be positive anyway
maximum_value = 1000000 # Also, a number above 1 million would be pretty big
if minimum_value <= val <= maximum_value:
result = val ** 2
print(f'The square of the number you entered is {result}.')
# This print statement is equivalent to the following:
# print('The square of the number you entered is {}.'.format(result))
break # exits the loop: else you input an integer forever.
else:
print(f'Value must be between {minimum_value} and {maximum_value}.')
except ValueError: # If input is not an integer, print this message and go back to the beginning of the loop.
print(val, 'is not an integer.')
# There must be 2 blank lines before and after a function block
read_int()
With the final 'print' that you actually have at the end of your code, entering a string of text in the program generates an error. Now it doesn't ;). Hope this is useful in some way. Have a great day!
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.")
I been trying to solve this one for a while and can't seem to make it work right.. here is my current work
while True:
guess = int(raw_input('What is your number?'))
if 100 < guess or guess < 1:
print '\ninvalid'
else:
.....continue on
Right now I have made it so when a user input a number higher than 100 or lower than 1, it prints out "invalid". BUT what if i want to make it so when a user input a string that is not a number(alphabetic, punctuation, etc.) it also returns this "invalid" message?
I have thought about using if not ...isdigit(), but it won't work since I get the guess as an integer in order for the above range to work. Try/except is another option I thought about, but still haven't figured out how to implement it in correctly.
You can use exception handling:
try:
guess = int(raw_input('What is your number?'))
if not (1 <= guess <= 100):
raise ValueError
# .....continue on
except ValueError:
print '\ninvalid'
That way, \ninvalid will be printed if the user either inputs a non-numeric string or inputs a numeric string greater than 100 or smaller than 1.
EDIT: Okay, I submit to the x < y < z syntax. Still think it loses some of its charm when it's used with not, though.
while True:
try:
guess = int(raw_input("..."))
except EOFError:
print "whoa nelly! EOF? we should probably exit"
break # or sys.exit, or raise a different exception,
# or don't catch this at all, and let it percolate up,
# depending on what you want
except ValueError:
print "illegal input: expected an integer"
else:
if not (1 <= guess <= 100):
print "out of range"
else:
print "processing guess... (but if it wasn't 42, then it's wrong)"
break # out of while loop after processing