如何允許用戶輸入添加到字典

2024-04-20 13:41:08 发布

您现在位置:Python中文网/ 问答频道 /正文

嘿,所以我试着用这个函数和while循环一起使用user input()来添加到字典中,例如:user input=artist name,album name,and track number,它存储在字典中,一旦用户输入完成,就可以从输入数据中打印新字典。在

以及if input == 'q' to quit.

谢谢,如果我的问题不清楚,很抱歉,因为这是我在SOF上的第一个问题。在

def make_album(artist_name, album_name, track_number):
    """Returns a dictionary of an Artist"""
    full_block = {'artist': artist_name, 'album': album_name, 'track': track_number}
    return full_block

musician = make_album('Jimi Hendrix', 'The experience', 23)
print(musician)

Tags: and函数namenumberinputalbummake字典
2条回答

多亏了你,我终于找到了解决办法:)

def make_album(artist_name, album_name, track_number):
""""Returns a dictionary of an Artist"""

artist_name = artist_name.strip()                   #removes the spaces
album_name = album_name.strip()                     #removes the spaces
track_number = track_number.strip()                 #removes the spaces

full_block = {'artist': artist_name, 'album': album_name, 'track': track_number}
return full_block


while True:     #I enter into the while loop
block_0 = input("Enter artist name: ")
if block_0 == 'q':
    print("quitting...")
    break

block_1 = input("Enter an album name: ")
if block_1 == 'q':
    print("quitting...")
    break

block_2 = input("Enter how many tracks: ")
if block_2 == 'q':
    print("quitting....")
    break

else:
    in_full = make_album(artist_name=block_0.title(), album_name=block_1.title(),    track_number=block_2.title())  
    print(in_full)
print("End...")
break

给你!在

def make_album(artist_name, album_name, track_number):
    """Returns a dictionary of an Artist"""

    artist_name = artist_name.strip() #Removes any spaces in the beginning or end
    album_name = album_name.strip() #Removes any spaces in the beginning or end
    track_number = track_number.strip() #Removes any spaces in the beginning or end


    full_block = {'artist': artist_name, 'album': album_name, 'track': track_number}
    return full_block

while True: #I enter into the while loop
    block = input("Enter artist, album, track seperated by comma")
    #Seperate artist, album, track by a COMMA. This is crucial
    if block == 'q':
        print("You pressed q, quitting...")
        break #I break out of the while loop if block which is the string variable that stores the input == 'q'

    else:
        album = block.split(",") #Split the string by comma into a list where each element will be the contents of the dictionary.
        musician = make_album(album[0], album[1], album[2])
        #Element in index 0 is artist_name
        #Element in index 1 is album_name
        #Element in index 2 is track_number
        print(musician)

如果需要,请分别输入三个细节,然后:

^{pr2}$

相关问题 更多 >