Except being an invalid syntax - python

I asked a related question here about this. However, I still have one problem.
import sys
import calendar
trueVal = 'yes'
while trueVal == 'yes' :
yy = int(input("Enter year: "))
mm = int(input("Enter month: "))
break
except ValueError:
print "Oops! That was not an integer. Try again..."
print(calendar.month(yy, mm))#returns the result
cmd=input("Would you like to view another calendar? Type yes if you do, no to exit program")
if cmd != trueVal :
sys.exit()
Apparently, my prof wants me to put an error message for users who input strings. So I put that except function but it doesn't recognize it.

You need to use a try/except block, always together:
while trueVal == 'yes' :
try:
yy = int(input("Enter year: "))
mm = int(input("Enter month: "))
break
except ValueError:
print("Oops! That was not an integer. Try again...")

There are some errors in your code:
you didn't add "try" at the beginning of the block
even if you answered yes or no your program will have an error!
Here is the code you need, so you can get your deadline ;)
Updated! Because you are using Python 3 so print statement must have parentheses and you have to just use input() instead of raw_input().
import sys
import calendar
trueVal = "yes"
while trueVal == "yes":
try:
yy = int(input("Enter year: "))
mm = int(input("Enter month: "))
print(calendar.month(yy, mm))#returns the result
trueVal = input("Would you like to view another calendar? Type yes if you do, no to exit program: ")
except ValueError:
print("Oops! That was not an integer. Try again...")

Related

How can I get print except statement printed instead of an error below in try/except syntax in Python

I am new to Python programming. Following is the code written and it works fine when I print any numeric digit and give me the desired result as expected but the problem comes when I enter string (anything other than integer/float) instead of giving me just the except statement, it also gives me an error which I don't want. So, what I want is when a user enter anything other than numeric digits, he should be prompted with a message i.e., "Invalid input. Enter a number please" instead of an error which I am getting after the except print statement in the end. Please help.
hours_string = input("Enter Hours: ")
rate_string = input("Enter Rate: ")
try:
hours_float = float(hours_string)
rate_float = float(rate_string)
except:
print("Invalid input. Enter a number please.")
result = hours_float * rate_float
print("Pay",result)
This is the error I am getting. If I enter string, I should simply get an except statement. That's it. Not any other error. How can I accomplish to get there?
Enter Hours: 9
Enter Rate: entered string by mistake
Invalid input. Enter a number please.
Traceback (most recent call last):
File "<string>", line 9, in <module>
NameError: name 'rate_float' is not defined
For a particular Error you can do a particular Exeption like in the Code below. Also note that each question is in a whileloop that you need to acomplish the task before you get to the next one.
while True:
try:
hours_string = input("Enter Hours: ")
hours_float = float(hours_string)
except ValueError:
print("Invalid input. Enter a number please.")
else:
break
while True:
try:
rate_string = input("Enter Rate: ")
rate_float = float(rate_string)
except ValueError:
print("Invalid input. Enter a number please.")
else:
break
result = hours_float * rate_float
print("Pay",result)
hours_float = None
rate_float = None
while hours_float is None:
hours_string = input("Enter Hours: ")
try:
hours_float = float(hours_string)
except ValueError:
print("Invalid input. Enter a number please.")
while rate_float is None:
rate_string = input("Enter Rate: ")
try:
rate_float = float(rate_string)
except ValueError:
print("Invalid input. Enter a number please.")
result = hours_float * rate_float
print("Pay", result)
In the while loop we repeatedly ask user for input, while they don't enter a valid number, separately for hours and rate.
Valid input changes the initially set None value to something else, which finishes the corresponding loop.
Since this is a expected situation and it can be treated as a test I would recommend instead of trying to execute the operation with wathever input the user provided you could ask the user for the input and while it is not an integer you ask for the input again.
def get_input(name, var_type):
userin = None
while userin is None:
userin = input(f'Input {name}: ')
try:
userin = var_type(userin)
except ValueError:
print(f'{name} must be {str(var_type)}, not {str(type(userin))}')
userin = None
return userin
hours = get_input('hours', int)
rate = get_input('rate', float)
result = hours * rate
print('Pay', result)
The function get_input tries to cast the input input value to the type you want and if it is not as desired it will keep asking until the type matches.

How to detect a invalid input and put the user into a loop until an acceptable answer is typed?

I'm trying to figure out how to get the user to type on letters and return numbers as invalid inputs only.
This is my code, I'm still unclear about the ValueError as if I run the code and type in letters it'll come out as an invalid input but if I put in numbers it comes in as valid.
while True:
try:
name = int(input("What is your name? "))
except ValueError:
print("Invalid response. Letters only please.")
continue
else:
break
correctName = input("Your name is...'" + (name) + "', is this correct? \n Please use 'Y' as yes and 'N' as no.\n")
if correctName == "Y":
print("Thank you..!")
int(input()) will expect an integer as an input, so when you type your name (unless you're name wholly consists of numbers), you will get a ValueError like you're experiencing now. Instead, you can use str(input()) to get the user input, then use the str.isdigit() method to check if it's a number.
name = str(input("What is your name? "))
if name.isdigit():
print("Invalid response. Letters only please.")
continue
else:
break
you can also try regex to check if a string contains a number:
bool(re.search(r'\d', name))
\d will matches for digits [0-9].
it will return True if the string contains a number.
full code:
import re
while True:
name = input("What is your name? ")
if bool(re.search(r'\d', name)):
print("Invalid response. Letters only please.")
else:
correctName = input("Your name is...'" + (name) + "', is this correct? \n Please use 'Y' as yes and 'N' as no.\n")
if correctName == "Y":
print("Thank you..!")
break
For Python3
while True:
name = input()
if name.isalpha():
break
For Python2
while True:
name = str(input())
if name.isalpha():
break

python input int only from input statement

I'm new to python and am trying to check if startmiles and endmiles are input as integer only and gallons are input as float. When I enter alpha the program crashes. Thank You
#!/usr/bin/env python
import os
import sys
import subprocess
import datetime
clear = lambda: os.system('clear')
clear()
t = datetime.datetime.now()
from time import gmtime, strftime
strftime("%a, %d %b %Y %X +0000", gmtime())
today = strftime("%a, %d %b %Y ")
print(today,'\n')
def main():
startmiles = input("Enter Your Start Miles = ")
endmiles = input("Enter Your Ending Miles = ")
gallons = input("Enter Your Gallons = ")
mpg = (int(endmiles) - int(startmiles)) / float(gallons)
print("Miles Per Gallon =", round(mpg, 2))
answer = input("\n Go Again Y or n ").lower()
if answer == 'y': print('\n'), main()
if answer != 'y': print('\n Thank You Goodbye')
if __name__=="__main__":
main() # must be called from last line in program to load all the code
Convert your inputs to int/float as soon as they are entered, wrapped in a try/except block in a loop to catch exceptions and immediately prompt again for more input:
while True:
try:
startmiles = int(input("Enter Your Start Miles = "))
break
except ValueError:
print('that is not an integer, please try again')
Or just wrap your final calculation in a try/except:
try:
mpg = (int(endmiles) - int(startmiles)) / float(gallons)
except ValueError:
print('some error message')
But this way you can't easily ask for more input, and you don't know exactly which value caused the error.
In Python 2.x the input should result in an integer anyways, unless you use raw_input. It looks like your mpg variable is taking the integer of the endmiles anyways.
In Python 3.x
startmiles = int(input("Enter Your Start Miles = "))
It sounds like you're saying certain characters crash the program, which means you need to do some exception handling. See this question response for more detail, but you need to find a way to handle your exceptions instead of crashing. Here's an example below forcing proper entry of the variable.
while True:
try:
# Note: Python 2.x users should use raw_input, the equivalent of 3.x's input
age = int(input("Please enter your age: "))
except ValueError:
print("Sorry, I didn't understand that.")
#better try again... Return to the start of the loop
continue
else:
#age was successfully parsed!
#we're ready to exit the loop.
break
if age >= 18:
print("You are able to vote in the United States!")
else:
print("You are not able to vote in the United States.")

i keep getting an undefined error when running this code

import sys
looptwo = True
while looptwo == True:
print("Welcome to the junior maths program, this program helps you do maths problems and acts as a calulator.")
try:
name = input("What is your name? ")
number = int(input("Enter your first number: "))
number2 = int(input("Enter your second number: "))
except ValueError:
print("that is not an option")
looptwo == False
when i run this code, it says that number isn't defined.
Your logic is backwards, you should only break if there is no error, you set looptwo equal to False in the except presuming that == is a typo which breaks the loop. So whenever you try to access name etc.. outside when the loop after an exception you will get an undefined error.
The only way your code breaks is when an exception is raised:
Use while True and only break if there were no exceptions.
while True:
print("Welcome to the junior maths program, this program helps you do maths problems and acts as a calulator.")
try:
name = input("What is your name? ")
number = int(input("Enter your first number: "))
number2 = int(input("Enter your second number: "))
break
except ValueError:
print("that is not an option")

try: statement fails

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

Categories

Resources