如果是python 3.3.3中的代码(计数奇数,正值!!?)

2024-03-28 17:45:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码是关于:计算有多少值是偶数、正数、负数 但它不起作用: 谢谢你的帮助

e = [ ] 

for c in range(5):

    c=float(input())
    if c<0:
        e.append(c)
        print("{} valor(es) negativo(s)".format(len(e)))
    if c>0:
        e.append(c)
        print("{} valor(es) positivo(s)".format(len(e)))
    if c%2!=0:
        e.append(c)
        print("{} valor(es) par(es)".format(len(e)))
    if c%2==0:
        e.append(c)
        print("{} valor(es) impar(es)".format(len(e)))

我希望o/p是这样的:

三价票面价值

2英勇

1积极的勇气

3勇气否定

当我输入五(int)个 当输入==4时退出


Tags: 代码informatforlenifesrange
1条回答
网友
1楼 · 发布于 2024-03-28 17:45:28

首先,对所有值类型使用相同的列表。计数只有第一次是正确的!奇偶数见下文。上述正/负错误相同。你知道吗

其次,这是功能性错误:

if c%2!=0:
    e.append(c)
    print("{} valor(es) par(es)".format(len(e)))
if c%2==0:
    e.append(c)
    print("{} valor(es) impar(es)".format(len(e)))

定义:

pares = []
impares = []

在你的循环中,写下这个

if c%2==0:
    pares.append(c)
    print("{} valor(es) par(es)".format(len(pares)))
else:
    impares.append(c)
    print("{} valor(es) impar(es)".format(len(impares)))

概念的证明,尽可能的做个Python (我已经使这个例子不具有交互性,并且只使用整数。正如ShadowRanger所指出的,浮点数上的模运算在这段代码中不会很好地工作)

# define 4 lists
the_list = [list() for i in range(4)]
negative_values,positive_values,odd_values,even_values = the_list

z=[1,2,-5,-7,0,3,-4]
for c in z: #range(5):

    #c=float(input())
    if c<0:
        negative_values.append(c)
    elif c>0:
        positive_values.append(c)
    if c%2==0:
        even_values.append(c)
    else:
        odd_values.append(c)

print("{} negative values, {} positive values, {} odd values, {} even values".format(*tuple(len(x) for x in the_list)))

相关问题 更多 >