Having trouble with multiplying a variable with a number

44,759

Solution 1

You want:

number = int(number)

At the moment, 'number' is a string (i.e. '1' rather than 1) so multiplying it by four naturally just gives you '1111'. Using int() will give you an integer representation of the string.

Solution 2

Your variable number is a string and not an int. So it does a "string multiplication". Try casting number to int or float.

number = int (number)

number = float (number)

Solution 3

The problem is that when a user inputs a number (or anything), that input is stored as a string. Therefore, when you get the user's input, you are not getting 1 - rather, you are getting '1'.

>>> '1' * 4
'1111'

>>> 1 * 4
4

The fix is to change

number = droid.dialogGetInput('Input', 'Enter a number between 1 and 10').result

to

number = int(droid.dialogGetInput('Input', 'Enter a number between 1 and 10').result)

Cheers

Solution 4

I believe that your number is a string type. When you multiply a string by a number, it returns that many of the same string if you do something like this:

number4 = int(number) * 4 

It should work.

Share:
44,759
MasterDewie
Author by

MasterDewie

Updated on July 09, 2022

Comments

  • MasterDewie
    MasterDewie almost 2 years

    I'm trying to shorten my code and have more functionality but its not working right.

    Heres my code(basically)

    def times4():  
        number = droid.dialogGetInput('Input', 'Enter a number between 1 and 10').result  
        number4 = number * 4  
        if number == '1':  
            droid.dialogCreateAlert(number,number + ' * 4 =' + number4)  
            droid.dialogSetPositiveButtonText('Ok')  
            droid.dialogShow()  
            droid.dialogGetResponse()  
    

    And I get this:

    1,1 * 4 = 1111
    

    When I want to get this:

    1,1 * 4 = 4
    
    • user1066101
      user1066101 about 13 years
      Why are you claiming 1,1 is a valid number? Where have you seen this before?
    • bluepnume
      bluepnume about 13 years
      S.Lott: 1,1 is just his output -- droid.dialogCreateAlert(number,number + ' * 4 =' + number4)
    • user1066101
      user1066101 about 13 years
      @Daniel Brain: Thanks. That clarifies things. The question could be improved to make that more clear.