Using exception handling - exception

I am trying to create an exception block that reads an error message and shuts down the program gracefully if my user inputs anything other than a number. How can I achieve this?
x=int(input("Choose a number:"))
try:
x==int()
except:
print("Invalid input.")
sys.exit()
y=int(input("Choose a number:"))
try:
y>=0 or y<=0
except:
print("Invalid input. Please try again.")
sys.exit()

In python the try block lets you test a block of code for errors.
The except block lets you handle the error.
In except block you can use ValueError as you are trying to convert the input to an integer, so if the input value is an integer, the code in the try block will be executed. otherwise the code in the excpet block will be executed.
You can use the while loop to exit the program only when you want by changing the value of the start variable to False.
start = True
while start:
try:
x=int(input("Choose a number for x :"))
y=int(input("Choose a number for y :"))
# if x > y:
# print("x is greater than y")
# elif x == y:
# print("x equal to y")
# else:
# print("x is less than y")
except ValueError:
print("Invalid input. Please enter a number")
start = False
Learn more about exceptions:
https://www.w3schools.com/python/python_try_except.asp
https://docs.python.org/3/tutorial/errors.html#handling-exceptions
Learn more about while loop:
https://www.w3schools.com/python/python_while_loops.asp

Related

Calling Private Methods Recursively

I am writing a code that has a class Fraction with attributes Numerator and Denominator. The Output should display the fraction in a simplified form. For e.g. 20/100 should be display as 1/5.
I have tried the below code but getting a Type Error as below:
TypeError: unsupported operand type(s) for /: 'int' and 'NoneType'
class fraction:
def get_data(self):
self.__num=int(input("Enter the Nr:"))
self.__deno=int(input("Enter the Dr:"))
if (self.__deno==0):
print("Fraction not possible")
exit()
def display_data(self):
self.__simplify()
print(self.__num,"/",self.__deno)
def __simplify(self):
print("The simplified fraction is")
common_divisor=self.__GCD(self.__num,self.__deno)
self.__num=(self.__num)/(common_divisor)
self.__deno=(self.__deno)/(common_divisor)
def __GCD(self,a,b):
if (b==0):
return a
else:
self.__GCD(b,a%b)
f=fraction()
f.get_data()
f.display_data()
I have no clue how to solve this Error. Please help me as i am new to Python and want to build strong basics.
The problem is in this function definition:
def __GCD(self,a,b):
if (b==0):
return a
else:
self.__GCD(b,a%b)
There's no return statement on the else clause. (Also, the else clause can be implicit instead of explicit.) Instead try:
def __GCD(self, a, b):
if b == 0:
return a
return self.__GCD(b, a % b)

why Python keeps saying prompt is not defined

this is the code in Python, I really don't know how to do this, I am just a beginner and someone can understand my question and help me
def get_float(prompt, low, high):
while True:
prompt = input("Enter monthly investment:")
number= float(input(prompt))
if number > low or number <= high:
is_valid = True
return number
else:
print("Entry must be greater than {low}and less than or equal to {high}")
def main():
get_float(prompt,low,high)
if __name__ == "__main__":
main()
In main, you are passing in the prompt variable into get_float. However, prompt is not defined in main, therefore you are attempting to pass an undefined variable which is not allowed.
In fact, given that get_float reads the prompt from input (and not the value passed in), you do not need to pass prompt into get_float, and prompt can be removed from the function signature.
You cannot pass prompt as a Function argument cause you are reading the value inside the function
def get_float(low, high):
while True:
prompt = input("Enter monthly investment:")
number= float(input(prompt))
if number > low or number <= high:
is_valid = True
return number
else:
print("Entry must be greater than {low}and less than or equal to {high}")
def main():
get_float(200,1000)
if __name__== "__main__":
main()

How to make python script continue after raise statement

I need to execute my second function cleanup after raise statement incase my else statement is executed in first function
but as this is an exception it doesn't work hence my second function which is cleanup() doesn't work .
Please note : I need to raise exception in my first function in case the string is not found
Please let me know what can I do to overcome this . Any help is very much appreciated
I have tried if else to achieve this with raise statement called in else but it doesn't works at all and I am stuck due to this . Please help
import os
import re
def validated():
if 'line is up , protocol is up' in open('C:/Users/diwak/Desktop/1.txt').read():
print("true")
else:
raise ("Not found")
def cleanup():
print ("cleanup still performed")
print (validated())
(cleanup())
My Expectation was both functions get executed :
1) Exception error raised for first function
2) Cleanup function executed
Actual output :
Program exits out of first function itself in case condition doesn't matches
I suppose this is desired (whereas it looks weird):
def validated():
try:
if 'helo' in 'hello world':
print("true")
else:
raise Exception("Not found")
except:
cleanup()
def cleanup():
print ("cleanup still performed")
validated()
def validated():
try:
if 'line is up , protocol is up' in open('C:/Users/diwak/Desktop/1.txt').read():
print("true")
else:
print("string not found")
raise Exception("Not found")
except:
pass
def cleanup():
print ("but cleanup still performed")
validated()
cleanup()
I think pass should also work if you agree

how can i make the input work with my parameters?

I have started a python class and my book does not seem to help me.
My professor has a program that bombards my code with different inputs and if any of the inputs do not work then my code is "wrong". I have done many days worth of editing and am at a complete loss. I have the code working if someone puts and input of an actual number. But where my code fails the test is if input is "miles_to_laps(26)" it errors out.
I have tried changing the input to int(input()) but that does not fix the issue. I've gone through changing variables and even changing the input method but still am at a loss. I have already tried contacting my teacher but 6 days of no response and 3 days of being late i feel like I'm just going no where.
user_miles = int(input())
def miles_to_laps(user_miles):
x = user_miles
y = 4
x2 = x * y
result = print('%0.2f' % float(x2))
return result
miles_to_laps(user_miles)
my code works for real number inputs but my professor is wanting inputs like
miles_to_laps(26) and miles_to_laps(13) to create the same outputs.
For the wierd input functionality you can try:
import re
def parse_function_text(s):
try:
return re.search("miles_to_laps\((.+)\)", s)[1]
except TypeError:
return None
def accept_input(user_input):
desugar = parse_function_text(user_input)
if desugar is not None:
user_input = desugar
try:
return float(user_input)
except ValueError:
raise ValueError("Cannot process input %s" % user_input)
assert accept_input("miles_to_laps(3.5)") == 3.5
I'm trying to keep all the pedantism aside, but what kind of CS/programming teaching is that?
Areas of concern:
separate user input from rest of code
separate output formatting from function output
the code inside miles_to_laps is excessive
Now here is the code to try:
LAPS_PER_MILE = 4
# the only calculation, "pure" function
def miles_to_laps(miles):
return LAPS_PER_MILE * miles
# sorting out valid vs invalid input, "interface"
def accept_input(user_input):
try:
return float(user_input)
except ValueError:
raise ValueError("Cannot process input %s" % user_input)
if __name__ == "__main__":
# running the program
laps = miles_to_laps(accept_input(input()))
print ('%0.2f' % laps)
Hope this is not too overwhelming.
Update: second attempt
MILE = 1609.34 # meters per mile
LAP = 400 # track lap
LAPS_PER_MILE = MILE/LAP
def miles_to_laps(miles):
return LAPS_PER_MILE * miles
def laps_coerced(laps):
return '%0.2f' % laps
def accept_input(user_input):
try:
return float(user_input)
except ValueError:
raise ValueError("Cannot process input %s" % user_input)
def main(user_input_str):
miles = accept_input(user_input_str)
laps = miles_to_laps(miles)
print (laps_coerced(laps))
if __name__ == "__main__":
main(input())

Using integers with dictionary to create text menu (Switch/Case alternative)

I am working my way through the book Core Python Programming. Exercise 2_11 instructed to build a menu system that had allowed users to select and option which would run an earlier simple program. the menu system would stay open until the user selected the option to quit. Here is my first working program.
programList = {1:"menu system",
2:"for loop count 0 to 10",
3:"positive or negative",
4:"print a string, one character at a time",
5:"sum of a fixed tuple",
"x":"quit()",
"menu":"refresh the menu"}
import os
for x in programList:
print(x,":",programList[x])
while True:
selection = input("select a program: ")
if selection == "1":
os.startfile("cpp2_11.py")
elif selection == "2":
os.startfile("cpp2_5b.py")
elif selection == "3":
os.startfile("cpp2_6.py")
elif selection == "4":
os.startfile("cpp2_7.py")
elif selection == "5":
os.startfile("cpp2_8.py")
elif selection == "menu":
for x in range(8): print(" ")
for x in programList:print(x,":",programList[x])
elif selection == "X":
break
elif selection == "x":
break
else:
print("not sure what you want")
input()
quit()
This version worked fine, but I wanted to use the a dictionary as a case/switch statement to clean up the ugly if/elif/else lines.
Now I'm stuck. I'm using Eclipse with PyDev and my new code is throwing an error:
Duplicated signature:!!
Here's a copy of my current code:
import os
def '1'():
os.startfile("cpp2_11.py")
def '2'():
os.startfile("cpp2_5b.py")
def '3'():
os.startfile("cpp2_6.py")
def '4'():
os.startfile("cpp2_7.py")
def '5'():
os.startfile("cpp2_8.py")
def 'm'():
for x in range(8): print(" ")
for x in actions:print(x,":",actions[x])
def 'x'():
quit()
def errhandler():
else:
print("not sure what you want")
actions = {1:"menu system",
2:"for loop count 0 to 10",
3:"positive or negative",
4:"print a string, one character at a time",
5:"sum of a fixed tuple",
"X":"quit()",
"menu":"refresh the menu"}
for x in actions:
print(x,":",actions[x])
selectedaction = input("please select an option from the list")
while True:
actions.get(selectedaction,errhandler)()
input()
quit()
I'm pretty sure that my current problem (the error codes) are related to the way I'm trying to use the os.startfile() in the functions. Maybe I'm way off. Any help is appreciated.
EDIT: I am changing the title to make it more useful for future reference. After a helpful comment from Ryan pointing out the simple error in function naming, I was able to piece together a script that works. sort of...Here it is:
import os
def menu_system():
os.startfile("cpp2_11alt.py")
def loopCount_zero_to_ten():
os.startfile("cpp2_5b.py")
def positive_or_negative():
os.startfile("cpp2_6.py")
def print_a_string_one_character_at_a_time():
os.startfile("cpp2_7.py")
def sum_of_a_tuples_values():
os.startfile("cpp2_8.py")
def refresh_the_menu():
for x in range(4): print(" ")
for y in actions:print(y,":",actions[y])
for z in range(2): print(" ")
def exit_the_program():
quit()
def errhandler():
print("not sure what you want")
actions = {'1':menu_system,
'2':loopCount_zero_to_ten,
'3':positive_or_negative,
'4':print_a_string_one_character_at_a_time,
'5':sum_of_a_tuples_values,
'x':exit_the_program,
'm':refresh_the_menu}
for item in actions:
print(item,":",actions[item])
for z in range(2): print(" ")
selectedaction = input("please select an option from the list: ")
while True:
actions.get(selectedaction,errhandler)()
selectedaction = input("please select an option from the list: ")
quit()
There were many problems with the second attempt. I was referencing the dictionary key instead of the value when calling functions. I also had some bugs in the way the menu printed and handled input values. Now all I need to do is figure out how to get the dictionary values to print without all of the extra information:
This is the output when I print the menu:
2 : <function loopCount_zero_to_ten at 0x027FDA08>
3 : <function positive_or_negative at 0x027FD810>
1 : <function menu_system at 0x027FD978>
4 : <function print_a_string_one_character_at_a_time at 0x027FD930>
5 : <function sum_of_a_tuples_values at 0x027FD780>
x : <function exit_the_program at 0x027FD858>
m : <function refresh_the_menu at 0x027FD7C8>
AND how to get the menu to print in numeric order.
Once again, any help is appreciated.
I finally found a solution to the problem of sorting a dictionary and printing the function names as a string. In the last part of the edited question (3rd code section), I had the fixed code for the question that started this post: how to use integers in a dictionary to create a menu - with the intention of creating a switch/case style alternative and avoiding the ugly if/elif/else problems in the first code section.
Here's the final version of the working code:
import os
def menu_system():
os.startfile("cpp2_11alt.py")
def loopCount_zero_to_ten():
os.startfile("cpp2_5b.py")
def positive_or_negative():
os.startfile("cpp2_6.py")
def print_a_string_one_character_at_a_time():
os.startfile("cpp2_7.py")
def sum_of_a_tuples_values():
os.startfile("cpp2_8.py")
def refresh_the_menu():
for x in range(4): print(" ")
for key in sorted(actions):
print (key, '=>', actions[key].__name__)
for z in range(2): print(" ")
def exit_the_program():
quit()
def errhandler():
print("not sure what you want")
actions = {'1':menu_system,
'2':loopCount_zero_to_ten,
'3':positive_or_negative,
'4':print_a_string_one_character_at_a_time,
'5':sum_of_a_tuples_values,
'x':exit_the_program,
'm':refresh_the_menu}
for key in sorted(actions):
print (key, '=>', actions[key].__name__)
selectedaction = input("please select an option from the list: ")
while True:
actions.get(selectedaction,errhandler)()
selectedaction = input("please select an option from the list: ")
quit()
adding the .__name__ method allowed me to print the function names as a string.
Using the for loop:
for key in sorted(actions):
print (key, '=>', actions[key].__name__)
created the ability to sort the dictionary.