What is the difference between try/except and assert? - python-3.x

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.

Related

Why does having a return statement in my try block make the 'else' statement unreachable?

I'm learning exception handling in Python3 and can't seem to understand why the else statement in my if-else block is unreachable when using return in the try block.
def simple_division() -> float:
"""
:return: the quotient of a / b
"""
a, b = _git_int()
if a == 0:
return 0
else:
try:
return a / b
except ZeroDivisionError:
print("Uh, you can't divide by zero, bud.")
else:
print("This should execute if no exceptions are raised, right? but it doesn't")
finally:
print("This should execute either way.")
I spent some time debugging in order to figure out that the return statement in the try block was at fault... and I now understand that doing something like this circumvents the problem:
def simple_division() -> float:
"""
:return: the quotient of a / b
"""
a, b = _git_int()
if a == 0:
return 0
else:
try:
answer = a / b
except ZeroDivisionError:
print("Uh, you can't divide by zero, bud.")
else:
print("This DOES work")
return answer
finally:
print("This should execute either way.")
But I haven't yet found any documentation explaining why you can't have a return statement in a try block. Could someone explain this to me? What would be the best practice here?

How to print the value only which is creating exception in python?

try:
a,b = map(int,input().split())
print(a//b)
except ZeroDivisionError:
print("invalid")
except ValueError:
print("this value _ is not allowed for division")
I need to print the value here _ which is caused for exceptions as "#" or "%"
It looks like you're trying to get something similar to the code showed below. This is possible by using regular expressions (through the search() function of the re module) to find the invalid argument that comes in the exception's (e) arguments (args).
e.args is a tuple that looks like the following when the ValueError is raised because of an invalid input entered:
("invalid literal for int() with base 10: '%'",)
Therefore, we could do something as follows:
import re
try:
a, b = map(int, input().split())
print(a // b)
except ZeroDivisionError:
print("Can't divide by zero")
except ValueError as e:
regex_groups = re.search('\'(.+)\'|\"(.+)\"', e.args[0]).groups()
invalid_arg = regex_groups[0] if regex_groups[0] else regex_groups[1]
print(f"This value: {invalid_arg} is not allowed for division")
Testing:
1 $
This value: $ is not allowed for division
Q 2
This value: Q is not allowed for division
% '
This value: % is not allowed for division
20 ?
This value: ? is not allowed for division
50 2
25

How to make the try function only print my message once

I've tried using the try() function, but when i try: and then type print() it just prints the message non-stop. how do i make it only print once?
def inputInt(minv, maxv, message):
res = int(input(message))
while (res > minv) and (res < maxv):
try:
print("Good job.")
except:
print("Invalid input")
Have you tried with break?
Take a look at this and this to get more clarification, but if you want that at the one time the try jumps to the except, it should print it once only, breakis the thing.
I must say this loop will go on forever as you are not changing res. Even if it goes in the try or in the except.
The code that could raise an exception should be in the try. The input should be inside the while. Catch expected exceptions in case an unexpected exception occurs. A naked except is bad practice and can hide errors.
Here's a suggested implementation:
def inputInt(minv, maxv, message):
while True: # Loop until break
try:
res = int(input(message)) # Could raise ValueError if input is not an integer.
if minv <= res <= maxv: # if res is valid,
break # exit while loop
except ValueError: # Ignore ValueError exceptions
pass
print("Invalid input") # if didn't break, input or res was invalid.
return res # Once while exits, res is good
x = inputInt(5,10,"enter number between 5 and 10: ")

collatz sequence infinte loop error

I am getting an infinite loop. I am not sure on how to covert the result as the new number variable and put it back in the while loop.
#Collatz squence
import sys
def collatz():
try:
print('Enter a number')
number = int(input())
except:
ValueError
print('Please type an integer')
while number != 1:
if number %2 == 0:
result = number//2
print(result)
elif number %2 == 1:
result = 3*number + 1
print(result)
**result = number**
while number == 1:
print ('You have arrived at the number itself')
sys.exit()
collatz()
The following works:
#Collatz squence
import sys
def collatz():
try:
print('Enter a number')
number = int(input())
except ValueError:
print('Please type an integer')
sys.exit(1)
while number != 1:
if number %2 == 0:
result = number//2
print(result)
elif number %2 == 1:
result = 3*number + 1
print(result)
number = result # set the number to the result
while number == 1:
print ('You have arrived at the number itself')
sys.exit()
collatz()
Notice that I set the number to the result, in your code the number never changed, and so kept hitting the same block of code over and over. I also added a sys.exit call in the exception, we don't want to continue if someone entered in a bad value.

Python code skips try/except clause

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

Resources