首页 > 解决方案 > 我的五个 - 存储五个姓名和五个数字,然后才被提升为需要输入的数字

问题描述

对于课程,我需要创建一个代码,将您朋友的五个姓名和五个数字存储在两个单独的数组中,然后输出您的五个朋友的列表。然后将提示用户输入 1 到 5 之间的号码,程序将确定要拨打的人和号码。

它应该看起来像 -

1. Jack Black
2. Robert Downey Jr.
3. Chris Evens
4. Scarlett Johansson 
5. Harry Potter

Please enter a number (1-5): *4*

Calling Scarlett Johansson at 416-568-8765

现在我有:

name = ["Paige"]
number = ["519-453-4839"]

#populate with a while loop
 while True:

      #add an element or q for quit
       addname = input("Enter a name, or q to quit ").lower()
 
 if addname == "q":
     break
 else:
     theirnumber = input("Enter their number ")
     #adds to the end of the list
     name.append(addname)
     number.append(theirnumber)

#when they break the loop
#print the lists side by side
 print()
 print("Name \t\t\t Number")
 print("----------------------------------")
 for x in range(len(name)):
     print(f"{name[x]} \t\t\t {number[x]}")

 #search for a gift and who gave it
 searchItem = input("What name are you looking for? ")
 if searchItem in name:
     nameNumber = name.index(searchItem)

     print(f"{name[nameNumber]} is the number {number[nameNumber]}")
 else:
     print("that is not a saved name, please enter a different name")

我不确定如何在不询问数字的情况下做到这一点,如果有人有任何想法,我很想听听。

标签: python-3.x

解决方案


@Mitzy33 - try to this and see if you follow, or have any other questions:

# two array for names, and the numbers
names = []
numbers = []

#populate with a while loop
while True:
     # get the name and numbers:

    name = input("Enter a name, or q to quit ")
     
    if name == "q":
        break
    else:
        number = input("Enter his/her number ")
        #adds to the end of the list
        names.append(name)
        numbers.append(number) 

#when they break the loop
#print the lists side by side
print(names)
print(numbers)

searchPerson = input("What name are you looking for? ").strip()

#print(searchPerson)

index = names.index(searchPerson)

print(f' {searchPerson} at {numbers[index]} ')

Output:

Enter a name, or q to quit John
Enter his/her number 9081234567
Enter a name, or q to quit Mary
Enter his/her number 2121234567
Enter a name, or q to quit Ben
Enter his/her number 8181234567
Enter a name, or q to quit Harry
Enter his/her number 2129891234
Enter a name, or q to quit q
['John', 'Mary', 'Ben', 'Harry']
['9081234567', '2121234567', '8181234567', '2129891234']
What name are you looking for? Harry
 Harry at 2129891234 

推荐阅读