Reputation: 51
I thought of creating a function which will give a range of an input at the same time change the value if a certain condition is met.
def num(u) :
for x in range(1,u):
if (x) %2==0:
x ='love'
print x
print num(10)
output :
1
love
3
love
5
love
7
love
9
'Wow this was great' (i thought). Then I decided to add more conditions to make my program look mature. Well it wasn't as I thought!!!
def num(u) :
for x in range(1,u):
if (x) %2==0:
x ='love'
print x
if (x) %3==0:
x ='fux'
if (x) %5==0:
x ='buzz'
On printing I got :
output :
/data/data/org.qpython.qpy/files/bin/qpython.sh "/storage/sdcard0/qpython/scripts/.last_tmp.py" && exit
python/scripts/.last_tmp.py" && exit <
Traceback (most recent call last):
File "/storage/sdcard0/qpython/scripts/.last_tmp.py", line 8, in <module>
print num (10)
File "/storage/sdcard0/qpython/scripts/.last_tmp.py", line 5, in num
if (x) %3==0:
TypeError: not all arguments converted during string formatting
1|u0_a115@g150_g:/ $
How can I pass in more conditions at this point.
Upvotes: 1
Views: 54
Reputation: 12910
I am not sure what exactly you are trying to achieve but error is every simple. you can not perform mathematical operation on string, it has to be integer. Also, your code is not pythonic :)
def num(u):
for x in range(1, u):
if x % 2 == 0:
x = 'love'
print x
# Following code will throw error as now x is not INT
if x % 3 == 0:
x = 'fux'
if x % 5 == 0:
x = 'buzz'
Upvotes: 1
Reputation: 311163
If two of the if
s are entered, x
will be assigned a string, and no longer be an int, so you can't use the modulu operator on it (in fact, %
is interpreted as the string format operator). You can clean up the code by just printing the strings you want without assigning them to x
:
def num(u) :
for x in range(1,u):
if (x) %2==0:
print 'love'
if (x) %3==0:
print 'fux'
if (x) %5==0:
print 'buzz'
Upvotes: 1
Reputation: 294
This is due to the way you've set up your conditional statements. Think about what happens after one of the cases is true. After x % 2 == 0
passes, you change the value of x
to "love"
. Any of the subsequent conditions will now be referencing the new value of x
, and of course trying to use the modulus operation on a string doesn't make any sense, thus causing the error.
To fix this, use a different variable to store the resulting string, or simply print it directly, rather than overwriting the value of x
.
An alternative would be to change the chain of if
statements to an if/elif/else
sequence, to guarantee that only one of the blocks of code will execute.
Upvotes: 2