Python Forum

Full Version: Prompting user for number, reading number, squaring it and returning result
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello.
What would be the code for a program that prompts the user for a number, reads that number, squares that number, and returns the resulting number?
Thank you!
It's very simple to do this.
What have you done yet?
Hi gontajones. Thank you for your reply.
Listen, I am new to Python. I have taken a couple of online courses that lasted a few hours each. Now I need to code.
Having said that, this is what I have done:

input("Enter a number")
user_answer = input("Enter a number")
user_answer_squared = user_answer**2
print(user_answer_squared)
That's a start!
Check this and tell me if you understand it.

user_answer = input("Enter a number: ")
user_answer_squared = int(user_answer)**2
print(user_answer_squared)
PS: Use the python code tag when post code.
Awesome, thank you very much! Greatly appreciated.
(Sep-12-2018, 11:19 PM)JHPythonLearner Wrote: [ -> ]Hi gontajones. Thank you for your reply.
Listen, I am new to Python. I have taken a couple of online courses that lasted a few hours each. Now I need to code.
Having said that, this is what I have done:

input("Enter a number")
user_answer = input("Enter a number")
user_answer_squared = user_answer**2
print(user_answer_squared)
In Python 3.x (which I hope you are using) ALL input is a string. That is, a series of unicode characters that Python does not treat as a numeric value.

You need to tell Python to cast a string to the kind of number you want. IF the string is not valid as a number, an exception will be raised and your programme will halt with an error message.

num = int(user_answer)
will attempt to convert the string referenced by user_answer into an integer referenced by num which you can then use in your subsequent code.

You can use float() to cast to a floating point number.