如何使用python打印列表中的项目?

6g8kf2rb  于 2021-08-20  发布在  Java
关注(0)|答案(5)|浏览(404)

有人能告诉我我的代码有什么问题吗?!!

def make_list(number):
      names =[]
      for item in range(0,number):
          names.append(input("Enter your name"))
      print(names)

number = int(input("How many names need to be entered?"))
names = make_list(number)
for name in names:
    if name[0] == "A":
        print("Name", name)
nfs0ujit

nfs0ujit1#

在里面 make_list ,你在印刷 names ,然后隐式返回 None . 改变 printreturn :

def make_list(number):
    names =[]
    for item in range(0,number):
        names.append(input("Enter your name with a capital letter."))
    return names

这样,调用者将把列表分配给 names 而不是 None .

wgeznvg7

wgeznvg72#

修复方法是返回names数组,而不是在函数中打印名称。

def make_list(number):
      names =[]
      for item in range(0,number):
          names.append(input("Enter your name with a capital letter. "))
      return (names)

number = int(input("How many names need to be entered? "))
names = make_list(number)
for name in names:
    if name[0] == "A":
        print("Name", name, "starts with A")

样本输出:

How many names need to be entered? 2
Enter your name with a capital letter. Andrew
Enter your name with a capital letter. Abby
Name Andrew starts with A
Name Abby starts with A
uxhixvfz

uxhixvfz3#

您需要将函数make_list中的值返回到主代码中的名称

def make_list(number):
  names =[]
  for item in range(0,number):
      names.append(input("Enter your name with a capital letter."))
  print(names)
  return names

number = int(input("How many names need to be entered?"))
names = make_list(number)
for name in names:
    if name[0] == "A":
       print("Name", name, "starts with A")
arknldoa

arknldoa4#

def make_list(number):
    names =[]
    for item in range(0,number):
        names.append(input("Enter your name with a capital letter. "))
    return (names)

number = int(input("How many names need to be entered? "))
names = make_list(number)
for name in names:
    print(f"Name {name} starts with {name[0]}")
uz75evzq

uz75evzq5#

在原始代码中, number=int(input("blah")) ... 在函数内部 make_list() 所以 make_list() 从未接到过电话。此外,您需要 return names 在…的结尾 make_list() ,否则它将隐式返回 None 的返回值 print() .

相关问题