Python 为什么它会显示我所有输入的副本?

Python 为什么它会显示我所有输入的副本?,python,Python,这个程序是否正确地涵盖了这个问题:编写一个包含四位美国总统姓名的列表的程序。你可以随意使用。然后,运行一个循环,在列表中再添加四位总统。以列表作为其唯一参数调用另一个函数。第二个函数应该对列表进行排序,然后在列表中循环,将每位总统的名字打印在自己的行中 例如,它将我的输出显示为: pres = ["Kennedy", "Lincoln", "Washington", "Trump"] for presidents in pres: print ("%s" % presidents)

这个程序是否正确地涵盖了这个问题:编写一个包含四位美国总统姓名的列表的程序。你可以随意使用。然后,运行一个循环,在列表中再添加四位总统。以列表作为其唯一参数调用另一个函数。第二个函数应该对列表进行排序,然后在列表中循环,将每位总统的名字打印在自己的行中

例如,它将我的输出显示为:

pres = ["Kennedy", "Lincoln", "Washington", "Trump"]

for presidents in pres:
    print ("%s" % presidents)

add = input("Please enter a president: ")
if add not in pres:
    pres.append(add)
pres.insert(-1,add)
add = input("Please enter a president: ")
if add not in pres:
    pres.append(add)
pres.insert(-1,add)
add = input("Please enter a president: ")
if add not in pres:
    pres.append(add)
pres.insert(-1,add)
add = input("Please enter a president: ")
if add not in pres:
    pres.append(add)
pres.insert(-1,add)
print (pres)
因此,拆下第二个插件

add = input("Please enter a president: ")
if add not in pres:
    pres.append(add) #adding president if name is not present.
pres.insert(-1,add) #adding president again(doesn't matter if present or not)
此外,您还必须运行一个循环来添加四位总统,以便:

 add = input("Please enter a president: ")
if add not in pres:
    pres.append(add)
最后,创建一个函数并将总统姓名作为参数传递,使用sort函数(使用sort()或sorted())并打印列表


希望有此帮助。

它显示重复,因为您要添加它两次-首先使用
pres.append(add)
,然后使用
pres.insert(-1,add)
。你不需要最后一份声明,因为如果总统不在名单上,你已经在添加了。
 add = input("Please enter a president: ")
if add not in pres:
    pres.append(add)
For i in range(4):
    add = input("Please enter a president: ")
    if add not in pres:
       pres.append(add);
    else:
       i = i-1;  #to add president, not already present.