Why my try-exception-finally cant work properly - python

it's homework from udemy,my solution cant work,here is the question:
Write a function that asks for an integer and prints the square of it. Use a while loop with a try, except, else block to account for incorrect inputs.
here is my solution:
def ask():
while True:
try:
user_input = int(input('give me int energe:'))
squ = user_input**2
print('boom! show you my power:'+squ)
except:
print('lack of int energe')
continue
else:
print('Gotcha')
break
finally:
print('boooooom')
pass
if I input str, the exception works well but even I input an int also show the same result as str,why this happens??
here is the correctly solution:
def ask():
while True:
try:
n = int(input('Input an integer: '))
except:
print('An error occurred! Please try again!')
continue
else:
break
print('Thank you, your number squared is: ',n**2)
I am not sure why my attempt cant going well

Your print statement is throwing an exception. You cannot append a string and an int using +. Either use
print('boom! show you my power:' + str(squ))
or
print('boom! show you my power:', squ)
In general untyped except statements are a really bad idea. If you had instead written except ValueError:, catching only the error thrown by trying to convert a string to an int using the int() function, you would have immediately seen the problem.

In your code, the error lies in:
print('boom! show you my power:'+squ)
squ is type int, and you're using the + operator where the left side has a string and the right side has an int. Either change the int to a string, or use the , character. Either of these would work:
print('boom! show you my power:', squ)
print('boom! show you my power:' + str(squ))

Related

How to ask user for input when an exception has occurred?

I am making a code to solve quadratic formula and need exception handling such that missing command
line arguments are detected. In the except IndexError: block, instead of exiting
the program you should use input() to ask the user for the missing input data. It doesn't work with the following code. Anyone have any ideas?
from math import sqrt
import sys
print('This program will solve the quadratic formula with given values, please enter below.')
try:
a=float(sys.argv[1]) #first system argument
b=float(sys.argv[2]) #second system argument
c=float(sys.argv[3]) #third system argument
d=b**2-4*a*c #discriminant
x1=((-b+sqrt(d))/2*a) #first solution
x2=((-b-sqrt(d))/2*a) #second solution
except IndexError:
raise IndexError(
'Oops! Looks like you have not entered all values. Try again.') #request user input
a=input(sys.argv[1]) #first system argument
b=input(sys.argv[2]) #second system argument
c=input(sys.argv[3]) #third system argument
d=b**2-4*a*c #discriminant
x1=((-b+sqrt(d))/2*a) #first solution
x2=((-b-sqrt(d))/2*a) #second solution
print(f'The quadratic formula with used a,b,c values gives two roots {x1:.2f} and {x2:.2f}')
I see several ways to improve with the original code:
Statements following raise are never executed
Conversion of string via float() may throw a ValueError
If less than 3 arguments are supplied, then sys.argv[n] will throw an error
You should revalidate re-entered input until it's correct.
You shouldn't trigger reentry of correct values if later ones have issues.
If your discriminant d is negative, sqrt() will throw a ValueError
Make your code DRY (Don't Repeat Yourself) by factoring out validation logic.
You need some way to do output.
The following code fixes these by:
Adding a validate method to be more DRY and validate input and handle ValueError.
Process the 3 arguments in order via an iterator that returns '' if not supplied, which the validate method will handle.
Test for negative discriminant.
from math import sqrt
import sys
print('This program will solve the quadratic formula with given values, please enter below.')
def validate(name, value):
try:
return float(value)
except ValueError:
new_value = input(f"Entered a value for {name}: ")
return validate(name, new_value)
args = iter(sys.argv)
a = validate('a', next(args, ''))
b = validate('b', next(args, ''))
c = validate('c', next(args, ''))
d=b**2-4*a*c #discriminant
if d >= 0 :
x1=((-b+sqrt(d))/2*a) #first solution
x2=((-b-sqrt(d))/2*a) #second solution
print(f"the roots {x1} and {x2}")
else:
print("the equation has no real-valued solutions")
You are raising un exception inside the catch block:
except IndexError:
raise IndexError(
'Oops! Looks like you have not entered all values. Try again.')
You can remove it and prompt the user this message using input() or something similar. for example:
except IndexError:
a= input('Oops! Looks like you have not entered all values. Enter the value again.')

Handling input data quality with checks & default value

I am trying to write a code for squaring the user input number in Python. I've created function my1() ...
What I want to do is to make Python to take user input of a number and square it but if user added no value it gives a print statement and by default give the square of a default number for e.g 2
Here is what I've tried so far
def my1(a=4):
if my1() is None:
print('You have not entered anything')
else:
b=a**2
print (b)
my1(input("Enter a Number"))
This is a better solution:
def my1(a=4):
if not a:
return 'You have not entered anything'
else:
try:
return int(a)**2
except ValueError:
return 'Invalid input provided'
my1(input("Enter a Number"))
Explanation
Have your function return values, instead of simply printing. This is good practice.
Use if not a to test if your string is empty. This is a Pythonic idiom.
Convert your input string to numeric data, e.g. via int.
Catch ValueError and return an appropriate message in case the user input is invalid.
You're getting an infinite loop by calling my1() within my1(). I would make the following edits:
def my1(a):
if a is '':
print('You have not entered anything')
else:
b=int(a)**2
print (b)
my1(input("Enter a Number"))
When I read your code, I can see that you are very confused about what you are writing. Try to organize your mind around the tasks you'll need to perform. Here, you want to :
Receive your user inputs.
Compute the data.
Print accordingly.
First, take your input.
user_choice = input("Enter a number :")
Then, compute the data you received.
my1(user_choice)
You want your function, as of now, to print an error message if your type data is not good, else print the squared number.
def my1(user_choice): # Always give meaning to the name of your variables.
if not user_choice:
print 'Error'
else:
print user_choice ** 2
Here, you are basically saying "If my user_choice doesn't exists...". Meaning it equals False (it is a bit more complicated than this, but in short, you need to remember this). An empty string doesn't contain anything for instance. The other choice, else, is if you handled your error case, then your input must be right, so you compute your data accordingly.
In your second line, it should be
if a is None:
I think what you want to do is something like the following:
def m1(user_input=None):
if user_input is None or isinstance(user_input, int):
print("Input error!")
return 4
else:
return int(user_input)**2
print(my1(input("Input a number")))

error displaying when trying to error capture

I am having the problem where i need some code to be error captioned, so if the user does not enter a number it should tell them that they have done something wrong. Below is the code that i would like to error capture, and i am not sure how to do about doing this.
if cmd in ('L', 'LEFT'):
Left_position = (int(input("How many places would you like to move left")))
if args:
step = int(args[0])
else:
step = Left_position
y -= step
This line:
Left_position = (int(input("How many places would you like to move left")))
Will throw an error if the input is not a string that can be turned into an integer. To capture this, surround this with a try block:
try:
Left_position = (int(input("How many places would you like to move left")))
except ValueError:
print('Error is handled here')
if args:
....
You might want to rearrange your code slightly. As far as I can see, you only actually want to ask the user for input if args haven't been provided. If this is the case, the following should work:
if args:
step = int(args[0])
else:
while True:
try:
Left_position = (int(input("How many places would you like to move left")))
break
except ValueError:
print 'This is not an integer! Please try again'
step = Left_position
y -= step
First, if there are args we use the first element and carry on. If there aren't, we enter a (potentially infinite) loop where the user is asked to provide an input. If this is not wrappable as an integer, an error message is printed and then the user is asked again for an input value. This terminates once an integer is provided - the break line can only be reached if an error isn't thrown by the input.

How to check if a string is included in a int and to remove it?

Hey I would like to know if there is a way I can make sure nobody type "1004gg0" into the game and crash it? It asks for a number and the number is an integer but I always get people either accidently or on purpose writing in strings into an integer place.
Instead of checking before, let int check it for you. Just catch the conversion exception and reject the number:
def get_number_from_user(message):
while True:
user_input = raw_input(message)
try:
number = int(user_input)
break
except ValueError:
# Keep asking
pass
return number
And you would use it as:
param = get_number_from_user("Insert number here: ")
print param
If you are using Python 3, then replace raw_input with input.
Convert the string to int, and let the user know if it fails:
try:
number = int(s)
except ValueError:
# This is not an int

Python input string error (don't want to use raw_input) [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 12 years ago.
I have a menu that asks for the user to pick one of the options. Since this menu is from 1 to 10, I'm using input besides raw_input.
My code as an if statement that if the number the user inputs is from 1 to 10 it does the option. If the user inputs any number besides that ones, the else statement says to the user pick a number from 1 to 10.
The problem is if the user types an string, lets say for example qwert. It gives me an error because its an string. I understand why and I don want to use raw_input.
What can I do to wen the user types a string it goes to my else statement and print for example "Only numbers are valid. Pick a number from 1 to 10"
I don't want to use any advanced programing to do this
Regards,
Favolas
EDIT
Thanks for all your answers and sorry for the late response but I had some health problems.
I couldn't use try or except because my teacher didn't allow it.
In the end, I've used raw_input because it was the simplest alternative but was glad to see that are many ways to solve this problem.
Regards,
Favolas
You can throw an exception when you try to convert your string into a number.
Example:
try:
int(myres)
except:
print "Only numbers are valid"
You should use raw_input(), even if you don't want to :) This will always give you a string. You can then use code like
s = raw_input()
try:
choice = int(s)
except ValueError:
# choice is invalid...
to try to convert to an int.
Im not sure what you consider advanced - a simple way to do it would be with something like this.
def getUserInput():
while True:
a = raw_input("Enter a number between 1 and 10: ")
try:
number = int(a)
if (0 < number <= 10):
return number
else:
print "Between 1 and 10 please"
except:
print "Im sorry, please enter a number between 1 and 10"
Here, I have used try/except statements, to ensure that the entered string can be converted to an integer. And a loop (which will keep running) until the entered number is between 1 and 10 (0< number <=10)
What you really are after is how to figure out if something could pass as an integer. The following would do the job:
try:
i = int(string_from_input)
ecxept ValueError:
# actions in case the input is anything other than int, like continuing the loop
You clearly have something against exception handling. I don't understand why -- it's a fundamental part of (not just Python) programming and something you should be comfortable with. It's no more 'advanced' than handling error codes, just a different mentality.
Here are the docs. It's pretty simple:
It is possible to write programs that
handle selected exceptions. Look at
the following example, which asks the
user for input until a valid integer
has been entered, but allows the user
to interrupt the program (using
Control-C or whatever the operating
system supports); note that a
user-generated interruption is
signalled by raising the
KeyboardInterrupt exception.
>>> while True:
... try:
... x = int(raw_input("Please enter a number: "))
... break
... except ValueError:
... print "Oops! That was no valid number. Try again..."
...
The try statement works as follows.
First, the try clause (the
statement(s) between the try and
except keywords) is executed. If no
exception occurs, the except clause is
skipped and execution of the try
statement is finished. If an exception
occurs during execution of the try
clause, the rest of the clause is
skipped. Then if its type matches the
exception named after the except
keyword, the except clause is
executed, and then execution continues
after the try statement. If an
exception occurs which does not match
the exception named in the except
clause, it is passed on to outer try
statements; if no handler is found, it
is an unhandled exception and
execution stops with a message as
shown above. A try statement may have
more than one except clause, to
specify handlers for different
exceptions. At most one handler will
be executed. Handlers only handle
exceptions that occur in the
corresponding try clause, not in other
handlers of the same try statement. An
except clause may name multiple
exceptions as a parenthesized tuple,
for example:
... except (RuntimeError, TypeError, NameError):
... pass
The last except clause may omit the
exception name(s), to serve as a
wildcard. Use this with extreme
caution, since it is easy to mask a
real programming error in this way! It
can also be used to print an error
message and then re-raise the
exception (allowing a caller to handle
the exception as well):
Personally, I liked my first answer better. However, this one should fit your requirements with more code.
import sys
def get_number(a, z):
if a > z:
a, z = z, a
while True:
line = get_line('Please enter a number: ')
if line is None:
sys.exit()
if line:
number = str_to_int(line)
if number is None:
print('You must enter base 10 digits.')
elif a <= number <= z:
return number
else:
print('Your number must be in this range:', a, '-', z)
else:
print('You must enter a number.')
def get_line(prompt):
sys.stdout.write(prompt)
sys.stdout.flush()
line = sys.stdin.readline()
if line:
return line[:-1]
def str_to_int(string):
zero = ord('0')
integer = 0
for character in string:
if '0' <= character <= '9':
integer *= 10
integer += ord(character) - zero
else:
return
return integer
May I recommend using this function in Python 3.1? The two arguments are the expected number range.
def get_number(a, z):
if a > z:
a, z = z, a
while True:
try:
line = input('Please enter a number: ')
except EOFError:
raise SystemExit()
else:
if line:
try:
number = int(line)
assert a <= number <= z
except ValueError:
print('You must enter base 10 digits.')
except AssertionError:
print('Your number must be in this range:', a, '-', z)
else:
return number
else:
print('You must enter a number.')

Categories

Resources