对于类,我需要创建一个代码,将朋友的五个名字和五个数字存储在两个单独的数组中,然后输出五个朋友的列表。然后,系统会提示用户输入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 ttt Number")
print("----------------------------------")
for x in range(len(name)):
print(f"{name[x]} ttt {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")
我不知道如何在不询问数字的情况下做到这一点,如果有人有任何想法,我很乐意听到。
@Mitzy33-试试这个,看看你是否有其他问题:
# 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]} ')
输出:
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
不使用两个数组,而是使用Python Dictionaries。使用名称作为关键字,使用数字作为相应的值。
peoples = {"Paige": "519-453-4839"}
你可以添加这样的项目:
poeples["newName"] = "111-111-1111"
然后你可以访问这样的号码:
peoples["Paige"]
因此,您可以询问姓名并返回号码:
searchName = input("What name are you looking for? ")
print(f"{searchName} is the number {peoples[searchName]}")
如果你必须只使用数组,那么你可以从名称中找到索引:
searchName = input("What name are you looking for? ")
index = name.index(searchName)
print(f"{name[index]} is the number {number[index]}")