Python || Snippet – How To Input Numbers Into A List & Display Its Contents Back To User
This snippet demonstrates how to place numbers into a list. It also shows how to display the contents of the list back to the user via stdout.
REQUIRED KNOWLEDGE FOR THIS SNIPPET
Insert & Display Items In A List
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
def main(): # declare variables arry = [] # initialize the list numElems = 0 # ask user how many items they want to place in list numElems = int(input("How many items do you want to place into the list?: ")) # print a newline print("") # user enters data into list using a for loop # you can also use a while loop, but for loops are more common # when dealing with lists for x in range(0, numElems): arry.append(int(input("Enter item #%d: " % (x+1)))) # display data print("nThe current items inside the list are: ") for x in range(0, numElems): print("Item #%d: %d" % ((x+1),arry[x])) if __name__ == "__main__": main() # http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Once compiled, you should get this as your output
How many items do you want to place into the list?: 3
Enter item #1: 6
Enter item #2: 4
Enter item #3: 2008The current items inside the list are:
Item #1: 6
Item #2: 4
Item #3: 2008
Related
Was this article helpful?
👍 YesNo
Leave a Reply