Skip to main content
 首页 » 编程设计

python之在 python 中询问数字并返回列表

2025年05月04日32bluestorm

大家好,我卡在了练习的一部分。我应该做的是要求一个数字(练习说我需要输入数字(4、-3、-15、0、10、22、-9999),其中 -9999 是中断号。它应该制作 3 个列表。列表 a 是所有输入的数字,列表 p 是所有正数,列表 n 是所有负数。这是我到目前为止的代码:

a = [] 
p = [] 
n = [] 
total = -9999 
 
while(True): 
    user_input = int(input('Please enter a number:')) 
    if(user_input == -9999): 
    break 
elif(user_input >= 0): 
    p.append(user_input) 
elif(user_input <= 0): 
    n.append(user_input) 
 
 
 a = p + n 
 print('The list of all numbers entered is:', '\n', a) 

当我运行这个程序并使用这些数字时,我得到 [4, 0, 10, 22, -3, -15] 这是正确的,但是当我查看这个练习的答案时,它的数字顺序不同[4, -3, -15, 0, 10, 22]。我一直在研究如何按此顺序获取数字。

还有一个问题。在本练习的 b 部分,我应该找到所有数字、正数和负数的平均值。当我打印 a, p, n 时,它不会将 0 添加到否定列表中,即使我有 user_input <= 0 这会偏离平均值。我错过了什么?

谢谢大家。

请您参考如下方法:

第一部分使用这个

while(True): 
    user_input = int(input('Please enter a number:')) 
    if(user_input == -9999): 
        break 
    elif(user_input >= 0): 
        p.append(user_input) 
    elif(user_input <= 0): 
        n.append(user_input) 
    #always append to a, makes the order the same as input order. 
    a.append(user_input) 

(我认为识别问题是错误的复制粘贴) 对于第二部分,您可以像这样制作 elif 以使其适用于 0

    elif(user_input >= 0): 
        p.append(user_input) 
    if(user_input <= 0 and user_input != -9999): 
        n.append(user_input) 

它失败的原因是因为一旦它被存储在 p 中,它就会跳过剩余的 elif else block 。