Add user input to a list in Python - bobbyhadz

文章推薦指數: 80 %
投票人數:10人

Declare a variable that stores an empty list. Use a range to iterate N times. On each iteration, prompt the user for input. append the value to ... ☰HomeBookAboutContactsHomeBookAboutContactsGitHubLinkedinTwitterAdduserinputtoalistinPythonBorislavHadzhievLastupdated:Jun21,2022PhotofromUnsplashAdduserinputtoalistinPython#ToadduserinputtoalistinPython:Declareavariablethatstoresanemptylist.UsearangetoiterateNtimes.Oneachiteration,prompttheuserforinput.appendthevaluetothelist.main.pyCopied!shopping_list=[] list_length=3 foridxinrange(list_length): item=input('Enteritemtobuy:') shopping_list.append(item) print(shopping_list)#👉️['apple','banana','kiwi'] Thecodesamplepromptstheuserforinput3timesandaddseachvaluetothe list.The list.append() methodaddsanitemtotheendofthelist.Theexampleusesthe rangeclass,butyou canalsouseawhileloopifyouwanttomakesurethelisthasalengthofat leastNitems.main.pyCopied!shopping_list=[] max_length=3 whilelen(shopping_list)



請為這篇文章評分?