Having trouble with multiplying a variable with a number
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 num开发者_运维百科ber 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
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.
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)
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.
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
I don't know this 'droid' kit, but I suspect that it's returning a string from dialogGetInput. If you multiply a string in python by N you get that string N times.
>>> s = 'foo' >>> s*4 'foofoofoofoo' >>>
So your program is seeing the STRING '1', not the integer 1. You need to convert your answer to an integer first:
>>> s = '1' # wrong >>> s * 4 '1111' >>> s = int('1') # right >>> s * 4 4 >>>
Also, be prepared to deal with someone putting in something other than a number(i.e. a typo or someone trying to be a jerk and crash you program on purpose)
>>> s = 'foo' >>> int(s) Traceback (most recent call last): File "", line 1, in ValueError: invalid literal for int() with base 10: 'foo' >>>
Always surround conversions of data with a try:
try:
s = 'foo'
i = int(s)
except ValueError, ex:
MessageBox('Try again!')
Here's how your code should be for your expected output:
def times4():
result = droid.dialogGetInput('Input', 'Enter a number between 1 and 10').result
number = int(result)
if number >= 1 and number <= 10:
number4 = number * 4
droid.dialogCreateAlert('%i' % number, '%i * 4 = %i' % (number, number4))
droid.dialogSetPositiveButtonText('Ok')
droid.dialogShow()
droid.dialogGetResponse()
Actually, dialogGetInput returns an object of class 'Result.' I'm having similar difficulty, because int() doesn't accept 'Result' as an argument. I'm not finding any reference in SL4A for what properties or methods the Result class supports.
Andrew
精彩评论