Python code skips try/except clause - python-3.x

I am working on a class assignment in which I need to raise two exceptions.
First Exception: I am supposed to raise and handle an exception if a user's entry is less than 0 or greater than 100. The code should then ask the user for the digit again.
Second Exception: If a particular file is not found, the exception requests the file name and then search happens again.
In both cases, I cannot make the exception happen. In other words, if in the first exception, I enter a digit greater than 100 or less 0, the program continues and simply doesn't record anything for this entry. If I print the user's entry, I get "none" rather than the error message that the except clause should display. Likewise in the second exception, if the file is not found, the code simply stops executing rather than firing the exception.
I have tried manually raising an exception (as in this question/answer), but that creates a traceback which I do not want-- I just want the first exception to print the error message and call a function and the second to request input and call a function.
First exception:
def grade():
#input student's average grade
avgGrade = int(input("Enter average grade: "))
try:
if avgGrade > 0 and avgGrade < 100:
return avgGrade
except ValueError:
print("Grade must be numeric digit between 0 and 100")
grade()
Second exception:
def displayGrades(allStudents):
try:
#open file for input
grade_file = open(allStudents, "r")
#read file contents
fileContents = grade_file.read()
#display file contents
print(fileContents)
grade_file.close()
except IOError:
print("File not found.")
allStudents = input("Please enter correct file name: ")
displayGrades(allStudents)

Sounds like the exercise is to raise the exception and handle it. You really need a loop for continuation rather than recursion, e.g.:
def grade():
while True:
try:
avgGrade = int(input("Enter average grade: "))
if avgGrade < 0 or avgGrade > 100:
raise ValueError()
except ValueError:
print("Grade must be numeric digit between 0 and 100")
continue # Loop again
break # Exit loop
return avgGrade
But this is contrived for the purpose of the exception, as exceptions are not really needed in this case.
For your other example this is less contrived because the downstream function raises the exception, e.g.:
def displayGrades(allStudents):
while True:
try:
with open(allStudents, "r") as grade_file:
...
except IOError:
allStudents = input("Please enter correct file name: ")
continue
break
Though I would caution mixing arg passing and user input in the same function - usually the exception would be caught and handled where the user is originally providing the file name. So in this example, it would probably be the calling function.

For your first one, you have to raise it manually as python won't guess your logic and raise it for you.
def grade():
#input student's average grade
avgGrade = int(input("Enter average grade: "))
try:
if avgGrade > 0 and avgGrade < 100:
return avgGrade
else:
raise ValueError()
except ValueError:
print("Grade must be numeric digit between 0 and 100")
return grade()
For the second one, You have to return the value in the second call.
use return displayGrades(allStudents) instead of displayGrades(allStudents)

Try this:
def get_value(data_list, index):
return data_list[index]
# Sample list data
my_list = ['a', 'b', 'c']

Related

Is there a possibility to add "less than" exception to this piece of code in Python?

I'm quite new to coding and I'm doing this task that requires the user to input an integer to the code. The function should keep on asking the user to input an integer and stop asking when the user inputs an integer bigger than 1. Now the code works, but it accepts all the integers.
while True:
try:
number = int(input(number_rnd))
except ValueError:
print(not_a_number)
else:
return number
You can do something like this:
def getPositiveInteger():
while True:
try:
number = int(input("enter an integer bigger than 1: "))
assert number > 1
return number
except ValueError:
print("not an integer")
except AssertionError:
print("not an integer bigger than 1")
number = getPositiveInteger()
print("you have entered", number)
while True:
# the input return value is a string
number = input("Enter a number")
# check that the string is a valid number
if not number.isnumeric():
print(ERROR_STATEMENT)
else:
if int(number) > 1:
print(SUCCESS_STATEMENT)
break
else:
print(NOT_BIGGER_THAN_ONE_STATEMENT)
Pretty simple way to do it, of course you must define ERROR_STATEMENT, SUCCESS_STATEMENT and NOT_BIGGER_THAN_ONE_STATEMENT to run this code as it is, I am using them as place-holder.

Additional ValueError Exception

I am new with exceptions. Especially multiple exceptions.
I am able to excuse this code with positive numbers and raise the ValueError with negative numbers.
My issue is how to "add" an additional exception for ValueError if I were to use a non-integer.
I maybe making it hard than it is.
def findFirstEvenInteger(number_list):
"""Def even integer. The following rest of the function utilizes a modulo operator
that checks if the number is even."""
for element in number_list:
if element % 2 == 0:
return element
raise ValueError
nn = int(input("Please enter any length of elements: "))
meep = []
for x in range(nn):
x = int(input())
meep.append(x)
try:
print("The first even integer in the list: " + str(findFirstEvenInteger(meep)))
except ValueError:
print("All the number are odd")

TypeError: method() takes 0 positional arguments but 1 was given

I wrote an input function python program,
But when run that code , IDE show that, "this function need to pass argument"
Even though ,I didn't declare any argument enter image description here
please help me how to solve this problem , Thank you in advance
list_number = list()
def input():
while True:
try:
number = input("Enter your number in to list = ")
if number == "Quit":
break
number = int(number)
list_number.append(number)
print(list_number)
except ValueError as e:
print(e)
def diagram():
display = ""
for i in list_number:
for j in range(i):
display = display +"#"
print(display)
display = ""
input()
diagram()
Several errors are noticed at glance:
mixture of namespace
You declared list_number as a global variable, but you cannot set value to it
directly insides a function. Instead, you can let the function return a value,
or use global statement to temporary allow a function to set a value to
a global variable temperary.
Read more on offical document, or search keyword python namespace for
relative articles.
name collision on builtin keyword
Some special word are reserved by python and could not be used as variable or
function name, input is amoung them.
BTW: The title of your question and example code layout is confusion! Follow the
tour to learn how to ask a better question and improve layout, so that people
can help you out.
Example code: though the test part has some bug I don't solved...
# remove: move it to a main progress for future design
# list_number = list()
# rename: input is a reserved name of builtins, pick another word
def myinput(*pargs):
if pargs:
for arg in pargs:
try:
yield int(arg)
except ValueError:
pass
else:
count = 0
while True:
# move out of `try` statement as it won't raise any exceptions
# imply lowercase for easier string comparison
userinput = input("Enter your number in to list: ").lower()
if userinput in ['quit', 'q']:
# for interactive, give user a response
print("Quit input procedure. Preparing Diagram...")
break
try:
number = int(userinput)
except ValueError:
# raise a error and the output will print to output by default
# there is no need to `print` an error
# and, for improve, you can raise a more specific message
# and continue your program
msg = "The program wants a number as input, please try again.\n"
msg += "Type `Quit` to exit input procedure."
print(msg)
continue
except KeyboardInterrupt:
msg = "You pressed Interrupt Keystroke, program exit."
print(msg)
return 0
# print a message and pass the value intercepted
count += 1
print("%d: number %d is added to queue." % (count, number))
yield number
def diagram(numbers):
# there is no need to iter a list by index
# and I am **not** sure what you want from your origin code
# if what you wnat is:
# join number with "#" sign
# then just use the builtins str.join method
# valid: is_list_like
if is_list_like(numbers):
numstr = map(str, numbers)
ret = "#".join(numstr)
else:
ret = "Nothing to export."
return ret
def is_list_like(obj):
"""fork from pandas.api.types.is_list_like,
search c_is_list_like as keyword"""
return (
# equiv: `isinstance(obj, abc.Iterable)`
hasattr(obj, "__iter__") and not isinstance(obj, type)
# we do not count strings/unicode/bytes as list-like
and not isinstance(obj, (str, bytes))
)
def main(*pargs):
# get a generator of user input
# if passed in values, accept parameter as user input for test
msgout = ""
if pargs:
# bug: test input not filtered by int() function
list_number = list(myinput(pargs))
print("Run builtin test module.")
else:
list_number = list(myinput())
count = len(list_number)
# process your input by whatever means you need
if count == 1:
msgout += "Received %d number from user input.\n" % count
else:
msgout += "Received %d numbers from user input.\n" % count
msgout += "The diagram is:\n%s" % diagram(list_number)
print(msgout)
def test():
"""simulate user input"""
userinputs = [
['a', 1, 5, 4, 9, 'q'],
[999, 'Quit'],
['q'],
]
for userinput in userinputs:
main(*userinput)
# test bug:
# 1. charactor is printed as output, too
if __name__ == "__main__":
# remove test() if you don't need it
test()
main()
Well I would change your function name from input to something else because you cannot have any function named anything from base python named in your function, This is probably the reason for your error.
Like the others said, input() is a builtin function in Python. Try this following code:
list_number = list()
def input_func():
while True:
try:
number = input("Enter your number in to list = ")
if number == "Quit":
break
number = int(number)
list_number.append(number)
print(list_number)
except ValueError as e:
print(e)
def diagram():
display = ""
for i in list_number:
for j in range(i):
display = display + "#"
print(display)
display = ""
input_func()
diagram()
Also, nice to note that try should be used more precisely only where the exception is expected to be thrown. You could rewrite input_func with that in mind, such as:
def input_func():
while True:
number = input("Enter your number in to list = ")
if number == "Quit":
break
try:
number = int(number)
except ValueError as e:
print(e)
else:
list_number.append(number)
print(list_number)

How do you code an error message for the wrong user input?

I need to Write a program, that takes input (from STDIN) of a number N, then prints N lines containing "Hello".
0< Max number in Input <=100
I am using Python 3.
User Input = abc
I've tried using if/elif/else to produce an "Error" message if the user inputs anything other than an integer. However, I think my last elif statement opposes the fact that I'm calling the "line" input an integer.
When I use a string as my test case I get a coding error:
Traceback (most recent call last):
File "/temp/file.py", line 3, in <module>
line = int(sys.stdin.readline())
ValueError: invalid literal for int() with base 10: 'abc'
Code:
import sys
line = int(sys.stdin.readline())
if line<1:
print("Error")
elif line>100:
print("Error")
elif line != int:
print("Error")
else:
print("Hello\n" * line)
You want to use a try/except statement:
>>> try:
l = int(input())
except ValueError:
print("Invalid Input")
abc
Invalid Input
If you want it to keep prompting the user until they enter valid input, use a while loop:
while True:
try:
l = int(input())
break
except ValueError:
print("Invalid Input")

What is the difference between try/except and assert?

try:
def function_addition(x,y):
assert (y!=0)
total= x/y
return total
num1=float(input("Write a number :"))
num2=float (input("Write a second number:"))
result=function_addition(num1,num2)
assert (num2 !=0)
print (result)
except AssertionError:
print ("Error!Check your inputs")
I wrote the code above ,but I don't know why I got the same result when I do: except ZeroDivisionError:
So can I delete assert and replace it by except ZeroDivisionError ?
`
assert only check if a condition is true or not and throw an exception. A try/except block can run a few statements and check if any of them throw an exception so you can process it in the except part. Examples:
assert(1 == 2)
will give you an AsertionError.
try:
# some statements
# ...
except OSError as err:
#If an OSerror exception is thrown, you can process it here. For example:
print("OS error: {0}".format(err))
Your code will look like this:
def function_addition(x,y):
try:
assert (y!=0)
except:
raise ValueError('y is 0.')
total= x/y
return total
num1=float(input("Write a number :"))
num2=float (input("Write a second number:"))
try:
result=function_addition(num1,num2)
except ValueError as ve:
print(ve)
else:
print(result)
If you save it in a fun.py file and run it, you will have this output:
Write a number :1
Write a second number:2
0.5
# Run it again.
Write a number :0
Write a second number:0
y is 0.

Resources