Home > Net >  How to multiply a variable with a variable?
How to multiply a variable with a variable?

Time:11-26

So I'm trying to do a project where I have to multiply a variable with a variable, and I get an error.

sprite = codesters.Sprite("person1")
choice = sprite.ask("What is the thing you want to log?")
my_var=choice
choice2 = sprite.ask("amount of times you "   my_var   " a day?")
my_var2=choice2
AmountPerYear=choice2*365
choice3=sprite.ask("How much money per day")
MoneyPerYear=choice3*365
Choice3= sprite.ask("How long does it take to "   my_var   " in seconds")
my_var3=Choice3
TimePerDay = my_var3 * my_var2

That last line does not work:

Oops! can't multiply sequence by non-int of type 'str' on line: 12 
  TimePerDay = my_var3 * my_var2

CodePudding user response:

By default, passing input into Python takes your input in the form of a string. Because of this, your program is attempting to multiply two strings, which isn't allowed, such as "5" * "6". You want to convert your values to int types before multiplying, so it can properly carry out the operation like 5 * 6:

TimePerDay = int(my_var3) * int(my_var2)

You may want to also check though beforehand that the user is inputting a proper int input

CodePudding user response:

This is happening because my_var2 and my_var3 are strings. They might be strings that contain a number, but this is not guaranteed. Suppose your user puts in apple and pear. What is apple x pear? It's meaningless.

You need to 'cast' the variables to integers. Try this:

TimePerday = int(my_var3) * int(my_var2)

This will work if the strings contain numbers, e.g. int('2') = 2, but if they do not, e.g. int('apple'), you will get an error.

  • Related