user8234938
user8234938

Reputation:

How to print an item from the list using Python?

can someone tell me what is wrong with my code?!!


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)

Upvotes: 0

Views: 758

Answers (5)

Sam Middleton
Sam Middleton

Reputation: 11

In your original code, number=int(input("blah")) ... was inside the function make_list() so make_list() never got called. Additionally, you need to return names at the end of make_list(), otherwise it implicitly returns None, the return value of print().

Upvotes: 0

Hasib Jaan
Hasib Jaan

Reputation: 1

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]}")

Upvotes: 0

Divyasri K
Divyasri K

Reputation: 1

you need to return the value from the function make_list to names in the main code

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")

Upvotes: 0

ankitbatra22
ankitbatra22

Reputation: 427

Rather than printing the name in the function, the fix is to return the names array.

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")

Sample Output:

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

Upvotes: 0

Tom Karzes
Tom Karzes

Reputation: 24052

In make_list, you're printing names, then implicitly returning None. Change the print to a return:

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

This way the caller will assign the list to names rather than None.

Upvotes: 1

Related Questions