user162698 user162698 - 1 year ago 96
Python Question

How do I multiply a variable by itself?

I am very new (as in one day) to python and cannot figure it out.

A = raw_input ("Enter A length - ")
B = raw_input ("Enter B length - ")
C = raw_input ("Enter C length - ")
if A*A + B*B > C*C:

As you can see above, I am trying to multiply 'A' by itself and then 'b' by itself and then see if it is less than C multiplied by itself.
Probably really simple, but I cannot find it in my Python book or online.

Answer Source

You need to use int to convert the numbers into integers because raw_input returns a string.

A = int(raw_input("Enter A length - "))
B = int(raw_input("Enter B length - "))
C = int(raw_input("Enter C length - "))

if A * A + B * B > C * C:
    # do stuff

What int does is take an object and convert it into an integer. Before, raw_input returned a string. You need to cast to integer with int.

>>> A = raw_input('Test: ')
Test: 3
>>> A

As you can see, raw_input returns a string. Convert to integer:

>>> int(A)

Note: input is not a good idea as it evaluates input taken as literal code. This can raise many errors for wrong inputs—NameError to name one. It can also be dangerous in the sense that malicious code can be executed by the user. Also, for handling wrong inputs, use a try/except. It will raise a ValueError if the object passed is not convertible.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download