我想过创建一个函数,它会在满足某个条件的情况下同时给出一系列输入。
1
love
3
love
5
love
7
love
9
输出:
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'
“哇,这太好了”(我想)。然后我决定添加更多条件,使我的程序看起来成熟。那不是我想的那样!!!
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:/ $
印刷时我得到了:
public class RuoloModelView: role
{
public enum MODEVIEW
{
NEW,
EDIT,
}
public MODEVIEW ModeView { get; set; }
}
此时如何传递更多条件。
答案 0 :(得分:2)
这是由于您设置条件语句的方式。想想在其中一个案例成立后会发生什么。通过x % 2 == 0
后,您将x
的值更改为"love"
。任何后续条件现在都将引用x
的新值,当然,尝试对字符串使用模数运算没有任何意义,从而导致错误。
要解决此问题,请使用其他变量来存储生成的字符串,或者直接打印它,而不是覆盖x
的值。
另一种方法是将if
语句链更改为if/elif/else
序列,以保证只执行其中一个代码块。
答案 1 :(得分:1)
如果输入了if
中的两个,x
将被分配一个字符串,而不再是一个整数,因此您无法在其上使用modulu运算符(事实上) ,%
被解释为字符串格式运算符)。您只需打印所需的字符串即可清理代码,而无需将其分配给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'
答案 2 :(得分:1)
我不确定你究竟想要实现什么,但错误很简单。你不能对字符串执行数学运算,它必须是整数。此外,您的代码不是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'