try: statement fails - python

I have some python code that fails:
import sys
print ("MathCheats Times-Ed by jtl999")
numbermodechoice = raw_input ("Are you using a number with a decimal? yes/no ")
if numbermodechoice == "yes":
try:
numberx1 = float(raw_input('Enter first number: '))
except ValueError:
print ("Oops you typed it wrong")
try:
numberx1 = float(raw_input('Enter first number: '))
except ValueError:
print ("Oops you typed it wrong")
numberx2 = (float)(raw_input('Enter second number: '))
elif numbermodechoice == "no":
print ("Rember only numbers are allowed")
numberx1 = (int)(raw_input('Enter first number: '))
numberx2 = (int)(raw_input('Enter second number: '))
else:
print ("Oops you typed it wrong")
exit()
print ("The answer was")
print numberx1*numberx2
ostype = sys.platform
if ostype == 'win32':
raw_input ("Press enter to exit")
elif ostype == 'win64':
raw_input ("Press enter to exit")
(Full code here)
I want to wrap the float operations with try statements so if a ValueError happens, it gets caught. Here is the output:
File "./Timesed.py", line 23
try:
^
IndentationError: expected an indented block
What is wrong with it and how can I fix this?

Python is whitespace sensitive, with regards to the leading whitespace.
your code probably should be indented like
import sys
from sys import exit
print ("MathCheats Times-Ed by jtl999")
numbermodechoice = raw_input ("Are you using a number with a decimal? yes/no ")
if numbermodechoice == "yes":
try:
numberx1 = float(raw_input('Enter first number: '))
numberx2 = float(raw_input('Enter second number: '))
except ValueError:
print ("Oops you typed it wrong")
exit()
elif numbermodechoice == "no":
print ("Remember only numbers are allowed")
try:
numberx1 = (int)(raw_input('Enter first number: '))
numberx2 = (int)(raw_input('Enter second number: '))
except ValueError:
print ("Oops you typed it wrong")
exit()
else:
print ("Oops you typed it wrong")
exit()
print ("The answer was")
print numberx1*numberx2
ostype = sys.platform
if ostype == 'win32':
raw_input ("Press enter to exit")
elif ostype == 'win64':
raw_input ("Press enter to exit")

In python, the indentation of your code is very important. The error you've shown us points here:
if numbermodechoice == "yes":
try:
numberx1 = float(raw_input('Enter first number: '))
except ValueError:
print ("Oops you typed it wrong")
All code that is part of a block must be indented. By starting a try block, the following line is part of that block and must be indented. To fix it, indent it!
if numbermodechoice == "yes":
try:
numberx1 = float(raw_input('Enter first number: '))
except ValueError:
print ("Oops you typed it wrong")

You had a wrong syntax. It should be except ValueError: and not except: ValueError. Correct it for you in the question too.

You need to indent the second print statement.
Indentation is important in Python. It's how you delimit blocks in that language.

The conversion to float is using an incorrect syntax. That syntax is valid for C/C++/Java, but not in Python. It should be:
numberx1 = float(raw_input('Enter first number: '))
Which will be interpreted like float("2.3"), which is a constructor for the float type being called with a string parameter. And, yes, the syntax is exactly the same for the function call, so you might even think the constructor is a function that returns an object.

import sys
class YesOrNo(object):
NO_VALUES = set(['n', 'no', 'f', 'fa', 'fal', 'fals', 'false', '0'])
YES_VALUES = set(['y', 'ye', 'yes', 't', 'tr', 'tru', 'true', '1'])
def __init__(self, val):
super(YesOrNo,self).__init__()
self.val = str(val).strip().lower()
if self.val in self.__class__.YES_VALUES:
self.val = True
elif val in self.__class__.NO_VALUES:
self.val = False
else:
raise ValueError('unrecognized YesOrNo value "{0}"'.format(self.val))
def __int__(self):
return int(self.val)
def typeGetter(dataType):
try:
inp = raw_input
except NameError:
inp = input
def getType(msg):
while True:
try:
return dataType(inp(msg))
except ValueError:
pass
return getType
getStr = typeGetter(str)
getInt = typeGetter(int)
getFloat = typeGetter(float)
getYesOrNo = typeGetter(YesOrNo)
def main():
print("MathCheats Times-Ed by jtl999")
isFloat = getYesOrNo("Are you using a number with a decimal? (yes/no) ")
get = (getInt, getFloat)[int(isFloat)]
firstNum = get('Enter first number: ')
secondNum = get('Enter second number: ')
print("The answer is {0}".format(firstNum*secondNum))
if __name__=="__main__":
main()
if sys.platform in ('win32','win64'):
getStr('Press enter to exit')

Related

Trying to control the user's input to strictly a positive number only

I am trying to control the user's input using exception handling. I need them to only input a positive number, and then I have to return and print out that number.
I have to send a message if the user puts in non-number and I have to send a message if the user puts in a number less than 1. Here is what I have:
def input_validation(prompt):
boolChoice = True
while boolChoice == True:
try:
l = input(prompt)
x = int(l)
boolChoice = False
except ValueError:
print("Not a valid input")
if l.isalpha() == True:
print("Your input is not a number")
elif l.isalnum() == True:
print ("Your input is not completely a positive number")
elif l < 0:
print("Your number is not positive")
print("Try again")
return x
def main():
x = input_validation("Enter a positive number: ")
print (x)
main()
My program works fine until a negative integer gets inputted. It doesn't print the message and then goes through the loop again, it just returns and prints back the negative number, which I don't want. How can I fix this? Thank you.
You can use try...except to check if its an integer or letters
def input_validation(prompt):
while True:
try:
l = int(input(prompt))
if l<0: #=== If value of l is < 0 like -1,-2
print("Not a positive number.")
else:
break
except ValueError:
print("Your input is invalid.")
print("Try again")
return l
def main():
x = input_validation("Enter a positive number: ")
print (x)
main()
try
def input_validation(prompt):
boolChoice = True
while boolChoice == True:
try:
l = input(prompt)
x = int(l)
if x < 0:
print ("Your input is a negative number\n Please enter a postive number")
elif x == 0:
print("Your input is zero\n Please enter a postive number ")
else:
boolChoice = False
except Exception as e:
print("Not a valid input")
if l.isalpha() == True:
print("Your input is not a number")
elif l.isalnum() == True:
print ("Your input is not completely a positive number")
else:
print(f"Failed to accept input due to {e}")
print("Try again")
continue
return x
def main():
x = input_validation("Enter a positive number: ")
print (x)
main()

Python catch int or str

I've written a program that generates a random number for the user to guess. I'm working on trying to catch all the possible errors. The only one I can't seem to figure out is this. At the beginning I ask the user to hit enter to continue to the game. The program catches if they type a string or even special characters and punctuation. The only thing I can't seem to prevent is if they they type a number, the program terminates. This is what I have. The issue is in the first while loop in the try block. Any suggestions or help would be appreciated.
Thanks in advance.
from random import randint #imports randint from random class
cont = input('Press enter to continue')
while True:
if cont != '':
try:
int(cont)
str(cont)
break
except ValueError:
print('Just hit enter')
cont = input()
continue
elif cont == '':
while True:
randNum = randint(1, 100)
print('Try guesssing a number between 1 and 100')
num = input()
while True:
try:
int(num)
break
except ValueError:
print('Please enter a number')
num = input()
int(num)
if num == randNum:
print('Good job, ' + str(num) + ' is correct.')
else:
print('Sorry, the number was ' + str(randNum) + '.')
print('Would you like to try again?')
answer = input().lower()
if answer == 'yes':
continue
elif answer == 'no':
print('Thanks for playing')
exit()
else:
while True:
print('Please type yes or no')
answer = input()
if answer == 'yes':
break
elif answer == 'no':
print('Thanks for playing.')
exit()
What happens when you enter a number is that the program tries to convert the number to an int (which works), and then to a str (which also works), after which it breaks. Instead, try the following:
from random import randint #imports randint from random class
cont = input('Press enter to continue')
while cont != '':
cont = input('Press enter to continue')
while True:
randNum = randint(1, 100)
print('Try guesssing a number between 1 and 100')
num = input()
while True:
try:
int(num)
break
except ValueError:
print('Please enter a number')
num = input()
num = int(num)
if num == randNum:
print('Good job, ' + str(num) + ' is correct.')
else:
print('Sorry, the number was ' + str(randNum) + '.')
print('Would you like to try again?')
answer = input().lower()
if answer == 'yes':
continue
elif answer == 'no':
print('Thanks for playing')
exit()
else:
while True:
print('Please type yes or no')
answer = input()
if answer == 'yes':
break
elif answer == 'no':
print('Thanks for playing.')
exit()
while True:
if cont != '':
try:
int(cont)
str(cont)
break
What it does here is try and convert cont to an int, if it succeeds it tries to convert it to a string (which is virtually always possible). If that succeeds it breaks the while loop and ends the program.
In any other scenario other than an int when it tries to parse it int(cont) it raises an error and you continue to your program.
Once he pressed enter cont starts. there is no reason for you to verify he didn't write something before entering the text.

my program dose not run because of confuse between integer value and string

my program confuse between integer value and string
import random
def test():
num=random.randrange(100,1000,45)
while True:
ans=run(num)
print ans
ss=raw_input("if you want to exit press t: ")
if ss=='t':
break
def run(userinput2):
first = int(userinput2/20)
print "i will send it in %s big pack"%str(first)
userinput2=userinput2%20
second =int(userinput2/10)
print "i will send it in %s med pack"%str(second)
third =userinput2%10
print "i will send it in %s med pack"%str(third)
def main():
print "the began of pro"
print "#"*20
userinput=raw_input("test or run: ")
if userinput.lower()=='test':
test()
else:
while True:
userinput2=int(raw_input("press t to exit or chose a number:"))
if userinput2 =='t':
break
else:
answer=run(userinput2)
if __name__ == "__main__":
main()
this piece of code i has error in it
userinput2=int(raw_input("press t to exit or chose a number:"))
if userinput2 =='t':
if i change it to string i had it not accept string and if make it string it not accept integers
I think that this covers the cases you need:
while True:
userinput2=raw_input("press t to exit or chose a number:")
if userinput2 =='t':
break
try:
userinput2 = int(userinput2)
except ValueError:
print('That was neither a number nor a "t". Try again.')
continue
answer=run(userinput2)

Specific Try and Except

continue = True
while continue:
try:
userInput = int(input("Please enter an integer: "))
except ValueError:
print("Sorry, wrong value.")
else:
continue = False
For the code above, how would I be able to catch a specific ValueError? What I mean by that is if the user inputs a non-integer, I would print out "Sorry, that is not an integer.". But if the user input is an empty input, I would print out "Empty Input.".
Move the call to input outside of the try: block and place only the call to int inside it. This will ensure that userInput is defined, allowing you to then check its value with an if-statement:
keepgoing = True
while keepgoing:
userInput = input("Please enter an integer: ") # Get the input.
try:
userInput = int(userInput) # Try to convert it into an integer.
except ValueError:
if userInput: # See if input is non-empty.
print("Sorry, that is not an integer.")
else: # If we get here, there was no input.
print("Empty input")
else:
keepgoing = False
Perhaps something like this:
keepgoing = True
while keepgoing:
try:
userInput = input("Please enter an integer: ")
if userInput == "":
print("Empty value")
raise ValueError
else:
userInput = int(userInput)
except ValueError:
print("Sorry, wrong value.")
else:
keepgoing = False

Continuously re-running a while loop until a certain input [duplicate]

This question already has answers here:
If an exception is raised ask again for input
(5 answers)
Closed 9 years ago.
What I'm trying to do with this is ask the user for two inputs and then call a function on the inputs. If it doesn't raise an exception then do the while loop again. If it does raise an exception than print something and do the while loop again. The problem I have is that I can't find a way to do the while loop again if it doesn't raise an exception. It works if it does raise an exception. The only way I can think of it is where I put #Rerun loop paste the entire while True loop again but that would be really horrible in this case.
class Illegal(Exception):
pass
def add_input(first_input, second_input):
if first_input + second_input >= 10:
print('legal')
else:
raise Illegal
def play():
inp = input("Ready? <yes/no>: ")
if inp == 'yes':
while True:
first_input = input("First number: ")
second_input = input("Second number: ")
try:
if first_input or second_input == 'quit':
break
else:
add_input(int(first_input), int(second_input))
#Rerun loop
except Illegal:
print("Illegal")
else:
break
else:
return
>>> play()
Ready? <yes/no>: yes
First number: 1
Second number: 2
Illegal
First number: 9
Second number: 6
legal
First number: 1
Second number: 2
Illegal
First number: quit
What I thought of doing:
def play():
inp = input("Ready? <yes/no>: ")
if inp == 'yes':
while True:
first_input = input("First number: ")
second_input = input("Second number: ")
try:
if first_input or second_input == 'quit':
break
else:
add_input(int(first_input), int(second_input))
while True:
first_input = input("First number: ")
except Illegal:
print("Illegal move")
else:
break
except Illegal:
print("Illegal move")
else:
break
else:
return second_input = input("Second number: ")
try:
if first_input or second_input == 'quit':
break
else:
add_input(int(first_input), int(second_input))
#Rerun loop
But this is a horrible idea because then I'd have to paste the same thing continuously.
The break in your else: causes the loop to exit. You can remove this entirely:
else:
break
You want to run the loop while the user doesn't quit it via typing quit. So you just have to remove this else: break:
def play():
inp = input("Ready? <yes/no>: ")
if inp.lower() == 'yes':
while True:
first_input = input("First number: ")
second_input = input("Second number: ")
# quit if the user wants
if first_input or second_input == 'quit':
break
try:
add_input(int(first_input), int(second_input))
except Illegal:
print("Illegal")
Also, take the habit to put the minimum of code in your try/except blocks. It makes the debugging easier after. Your last else: return is also useless, you can remove it.

Categories

Resources