Exception Handling with Boolean Expressions - python-2.7

Is it possible to include a boolean expression like I've done below while exception handling using try/except?
For example:
while True:
try:
grade = float(input('Please enter your your score:'))
break
except ValueError:
print('Please enter a numeric value, you dingus!')
except (grade > 1):
print('Not a valid number, please re-enter:')
except NameError:
print('Please enter a numeric value, you dingus!')
I'd like for string inputs to be handled by 'except NameError.' I'd like for numerics greater than 1 to be handled by printing 'Not a valid number, please re-enter:'
As is, the program handles strings and valid numeric inputs as intended. However, when I input numbers greater than 1, the program accepts my input and does nothing else. No except commands are executed and nothing is passed on to the function found below this exception handling piece of code. The program just stops and no error is given to help with debugging.

Give this a shot:
while True:
try:
grade = float(input('Please enter your your score:'))
if grade > 1:
raise ValueError
except ValueError:
print('Not a valid number, please re-enter.')
except NameError:
print('Please enter a numeric value, you dingus!')
except SyntaxError:
print('Please enter something, anything!?')

Related

NameError: name 'Right' is not defined

I'm trying to execute the following code in Spyder 3.3.1 using Python 2.7.15. I'm a beginner.
text = str(input("You are lost in forest..."))
while text == "Right":
text = str(input("You are lost in forest..."))
print "You got out of the forest!!!"
When I run the code with integer value it works. For example the following piece of code:
text = input("You are lost in forest...")
while text == 1:
text = input("You are lost in forest...")
print "You got out of the forest!!!"
How can I make the input() work with a string value? Thank you for your help.
Use raw_input() instead of input():
value = raw_input("You are lost in forest...") # String input
value = int(raw_input("You are lost in forest...")) # Integer input
...
In python 2, raw_input() takes exactly what the user typed and passes it back as a string. input() tries to understand the data entered by the user.Hence expects a syntactically correct python statement.That's why you got an error when you enter Right. So you can enter "Right" as input to fix this error.
But it is better to use raw_input() instead of input().

Why following code doesn't run an exception for negative inputs?

I want to write a simple code when user enters his age, it will give in how many years user will be 100 years. But I have assigned an exception if the user enters a negative number to give a value error. But the code runs regardless even if I enter a negative number without raising an exception. Why is that? Thanks! I'm using python 2.7
try:
age = raw_input("Please enter your age: ")
if age < 0:
raise ValueError ('%d is not a positive number' )
except ValueError as err:
print ("You've entered an incorrect age input %s" %err)
else:
print("You will be 100 in %d" % (100 - int(age)))
raw_input returns a string, so age is a string containing whatever you put - "-3" for example. Not an integer.
When comparing an integer to a string, "-3" < 0, the integer always "comes first" (is smaller than the string), just as an implementation detail, so your if will always be False. Cast to an int, the ValueError will already catch an invalid cast:
age = int(raw_input("Please enter your age: "))

Python readability

Greetings stackoverflow,
I am pretty new to both this website and python.
I wrote a simple program to create a list of devisors based on a user inputted number, the program works (as far as I know)
But I am pretty sure my syntax is extremely amateurish, so I ask the fluent among you, what can I do to make this:
divisors = []
def devisors(x):
while True:
try:
for i in range(1,x+1):
if x%i==0:
divisors.append(i)
if x==i:
break
except ValueError, TypeError:
return "Invalid input."
continue
print "The list of divisors of",x,"Are: ", divisors
choice1= raw_input("Would you like to use devisors program?(Y/N): ")
while True:
try:
if choice1 in yes:
x = int(raw_input("Please enter a number: "))
devisors(x)
elif choice1 in no:
print "Alright, bye bye."
break
else:
print "invalid input"
choice1= raw_input("Would you like to use devisors program(Y/N): ")
continue
except ValueError, TypeError:
print "Invalid input, try again."
try:
choice2= raw_input("Would you like to try again?(Y/N): ")
if choice2 in yes:
divisors = []
continue
devisors(x)
elif choice2 in no:
print "Alright, bye bye. "
break
else:
print "invalid input"
choice2= raw_input("Would you like to try again?(Y/N): ")
continue
except ValueError, TypeError:
print "Invalid input, try again."
Better written?
I want you to go berserk on this code, tell me (If you feel like it) what could be done to improve it, to write less lines, and mistakes I made.
Also I am not sure if this is something allowed on stackoverflow, if not, please let me know and I'll delete this.
Thank you.
Looking forward to the feedback.
First of all, we do have a dedicated Stack Exchange Code Review site, but you're not the only one asking for a code review here.
The first thing I noticed is that you are trying to hard to put everything in a single method.
Whenever you are faced with a problem or task you should try to divide it into the smallest possible problems. Afterwards we can implement the solution to these small problems as functions.
In your example your tasks are the following:
Get user input of a number
Get the divisors of that number
Print the divisors
Ask if the user wants to give it another try
Let's start with the 2nd point of our list:
def divisors_of(x):
if x < 0:
raise ValueError("Value cannot be smaller than 0")
divisors = []
for i in range(1, x + 1):
if x % i == 0:
divisors.append(i)
return divisors
That doesn't look too bad, does it?
After implementing the user input for a number and printing the result, we already get something like this:
try:
num = int(raw_input("Please enter a number: "))
divisors = divisors_of(num)
print "The divisors of ", num, " are: ", divisors
except (ValueError, TypeError) as ex:
print ex.message
Looking at our task list we still don't ask the user for another try. Again, IMHO it's more readable if we put the logic for that in a function. This has two additional benefits, we can convert the yes/no choice to a boolean and the written code is reuseable:
def yes_no_choice(text):
while True:
choice = raw_input(text)
if choice in "yes":
return True
# Returning like this is called early return
# As we jump out of the function, the code after
# the if is automatically the else statement
# The code is shorter and more readable
if choice in "no":
return False
print "Invalid answer"
Our final result looks like this:
while True:
try:
num = int(raw_input("Please enter a number: "))
divisors = divisors_of(num)
print "The divisors of ", num, " are: ", divisors
except (ValueError, TypeError) as ex:
print ex.message
if not yes_no_choice("Would you like to try again?(Y/N): "):
print "Bye!"
break
# else we will loop
Oh, and try not to use global variables if you don't have to. I'm looking at your divisors = []

check whether the given date value is valid or not in python with django

I need to check whether the given input value of date is valid or not in python. I normally used datetime.strptime is to check for date. Am getting Value Error doesn't match format when i given the input value date '06-06-'. It's wrong only but i want to display the output like invalid.
if (datetime.strptime(s,'%m-%d-%y')):
print "valid"
else:
print "Invalid"
1 . s = '06-06-15'
when i given the input value like above, it display the correct output value "Valid"
s = '06-06-'
when i given the input value like above, am getting error like time data '06-13' does not match format '%m-%d-%y'. But i want to display the output "Invalid"
Please anyone suggest me to do that. Thanks in advance.
This is just how it works.
ValueError is raised if the date_string and format can’t be parsed by
time.strptime()
Just turn it to
datetime.strptime(s,'%m-%d-%y'):
print "valid"
except ValueError:
print "Invalid"

What's wrong with this code? TypeError: 'float' object has no attribute '__getitem__'

In this program, i want marks of 3 subjects per each student, for 4 students.
But when i run this one, i get an error like this:
Traceback (most recent call last):
File "E:\Python\Lab\Lab6_3.py", line 12, in <module>
for marks in marks[student]:
TypeError: 'float' object has no attribute '__getitem__'
I can't identify what's wrong with, using the len() function to find the number of elements in a list.
Here's the code:
while True:
try:
marks=[]
print "Enter marks of the 3 subjects of each student : "
for student in range(4):
marks.append(raw_input())
marks[student]=map(float,marks[student].split(" "))
if len(marks[student])!=3:
print "Please enter marks of 3 subjects per each student"
for student in range(4):
total=0
for marks in marks[student]:
if marks<0:
print "You have entered a minus value"
total+=marks
print "Total of student %d = %f" %((student+1),total)
break
#except TypeError:
# print "You have entered an invalid input1"
except ValueError:
print "You have entered an invalid input2"
except NameError:
print "You have entered an invalid input3"
except SyntaxError:
print "You have entered an invalid input4"
else:
print "DONE !\n"
Here, I have skipped the exception "TypeError" to identify the fault. Can anybody tell what's wrong with this code?
marks is only an iterable the first time through the outer loop. Since marks is also the name you use in the inner loop, the iterable no longer exists in the outer loop.
TL;DR: for loops don't create a new scope in Python.