Question:
Help using input in Python 3.1?
Tony
2011-04-11 21:43:55 UTC
I need help using input in Python 3.1. I am also unable to make my program do what I want. This is my program:

a=input('What number will be squared? ')
b=a*a
print('The square is ' +repr(b))

This is the output (with error message included):

What number will be squared? 5
Traceback (most recent call last):
File "Untitled", line 2
b=a*a
TypeError: can't multiply sequence by non-int of type 'str'
Three answers:
yz
2011-04-12 02:40:15 UTC
use the function type() to test the variable type



in this case type(a) == str



This is only true in 3.x.x, in python 2.x.x,

type(a) == int



Anyhow, now that you know the problem do a simple type cast:

before you do

b=a*a

convert a which is currently a string into a float:

a = float(a)

a would then equal 5.0

You can do int(a) as well to make it an integer but it's safer with float just in case the user types in something like 5.1



Anyhow, with

a = float(a)

in between the first and second lines of the program everything should work perfectly
?
2016-11-07 15:29:52 UTC
through no skill am I an authority in python, yet attempt in simple terms affirming your variables as numbers i.e. a = 32 b = 31 then attempt it as quickly as greater. additionally, in the experience that your coding utility has a debug mode they you are able to nicely be waiting to run it from there, or attempt compiling it and attempting out it. What your doing is in simple terms including 32 to the tip of the enter string making it say "Please choose a variety: 32" rather of asserting "Please choose a variety:" once you run it the 2nd way. This wont provide a or b actual information , it is going to in uncomplicated terms substitute what it says whilst it asks for the variety.
?
2011-04-11 22:46:53 UTC
Idk but I know the error message is saying: You can't multiply a because its a string.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...