0

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?? my error screenshot

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

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you sooo much:)
0

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)) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.