How to recall a list item from user input - python

Im looking for a way for a user to enter a variable and it recalls the lists information from a specific spot in the list
list = ["0","2","4","8"]
a = input("Enter the list entry you want to retrieve: ")
print (list[a])
if you enter 1 it will print 2, if you enter 2 it will print 4

Convert 'a' to int.
list = ["0","2","4","8"]
a = input("Enter the list entry you want to retrieve: ")
print (list[int(a)])

Related

How to get input numbers from the user and sort it before printing it in python

I want to get input numbers from the user and sort it then print it. But it gives attribute error:
AttributeError: 'str' object has no attribute 'sort'
-- with the code--
lucky_numbers = input("Write your favourite numbers: ")
ans = (lucky_numbers)
ans.sort()
print(ans)
Using split():
lucky_numbers = input("Write your favourite numbers with a space: ")
numberList = lucky_numbers.split()
numberList.sort()
print(numberList)
OUTPUT:
Write your favourite numbers with a space: 50 40 -10
['-10', '40', '50']
EDIT:
If you want to have the values in int:
numberList = [int(x) for x in numberList]
This can be possible answer. You also need to convert str values to int
lucky_numbers = input("Write your favourite numbers: ")
ans = lucky_numbers.split()
ans_int = [int(i) for i in ans]
ans_int.sort()
print(ans_int)
You can't sort it because the input function returns the string that has been typed by the user so it will be a string not a list and you can't sort it. Your approach must change and you must store user input and numbers in a list.
Something like this may work:
lucky_numbers = []
while True:
user_input = input('enter your favourite number or to exit enter Q:')
if user_input == 'Q':
break
else:
lucky_numbers.append(int(user_input))
lucky_numbers.sort()
print(lucky_numbers)
This only works for integers and there is more stuff you can do for type checking and making sure that user input is a number or no or the list is empty or not. It was just a simple example to show the overall process.

Trying to find item that corresponds to the item in an array

The problem which I am facing is how I cannot seem to identify the selected item in an array list. It's kind of complicated. Basically, I want to loop 4 times and for every time it loops around the code, append the item, item number, its description and reserve price into one single array. However, because its looping 4 times the array Finallist seems to have appended all 4 of the items and the variables into its list. In doing so, causes my code on the final 3 lines. (i.e. Item = input("please enter your desired item") to not work, as the item the user enters will inevitably print the whole array list of the 4 items and its variables. However, I just want the variables in one loop. To make it clearer for you, for example if the program loops once, the item will be cat, its item number will be 123456, its description will be "cats are cute" and its reserve price is 1000, however, if I were to loop 4 times the program will have to print all 4 items and the variables, whereas I just want the single looped item and its variable. So I just want the item to be cat, and its item number to be 123456, its description to be "cats are cute" and its reserve price to be 1000, without the other 4 entries. I know the explanation may be confusing but I hope it makes it clearer for you. Thanks!
ItemNum = []
description = []
ReservePrice = []
item = []
NumOfBids = 0
Finallist = []
for count in range (0,4):
user3 = input("please enter your item ")
item.append(user3)
user = input("please input your item number. ")
ItemNum.append(user)
user1 = input("Please enter your description for the product ")
description.append(user1)
user2 = input("Please enter your reserve price for the thing ")
ReservePrice.append(user2)
Finallist.extend(item)
Finallist.extend(ItemNum)
Finallist.extend(description)
Finallist.extend(ReservePrice)
Item = input("please enter your desired item")
if Item == Finallist:
print(Finallist)
Try a if Item in Finallist:.
This checks wether a object with the value of Item is inside the list Finallist.
Forthermore why do you .extend() the FinalList ? Asimple append() would do the trick and avoid multiplication of occurence of data.
EDIT:
Here a modification of your code :
ItemNum = []
description = []
ReservePrice = []
item = []
NumOfBids = 0
Finallist = []
def print_item(item_list, item):
start_index = item_list.index(item)
print(item_list[start_index:start_index+4])
for count in range (0,4):
user3 = input("please enter your item ")
item.append(user3)
user = input("please input your item number. ")
ItemNum.append(user)
user1 = input("Please enter your description for the product ")
description.append(user1)
user2 = input("Please enter your reserve price for the thing ")
ReservePrice.append(user2)
Finallist.append(user3)
Finallist.append(user)
Finallist.append(user1)
Finallist.append(user2)
Item = input("please enter your desired item")
if Item in Finallist:
print_item(Finallist, Item)
Edit :
Explanation of the get_item() function.
the function utilizes the so called list sliceing.
If you have a list like example_list = ["a", "b", "c", "d", "e", "f"]
we can acces "sub-lists" like ["c", "d"] via example_list[2:4]
A slice works like a_list[start:stop] which returns a list consisting of all entries of a_list within the indecees start and stop including the element with index start but excluding the item with index stop.
The Trick with the +4:
Since you have 4 entries which belong to a Item (ItemName, ItemNum, description, and ReservePrice) we allways want to find the intex of the ItemName and get it plus the next three entries BUT NOT THE 4th.
This is done by calling .index(item) this retrieves the index of item.
item_list[start_index:start_index+4] hence returns the sublist starting with item and ending with it's ReservePrice but does not include the next ItemName.
Further reading : About Slicing
I removed some unnecessary cruft from the code snippet.
Finallist = []
for count in range (0,4):
user1 = input("please enter your item ")
user2 = input("please input your item number. ")
user3 = input("Please enter your description for the product ")
user4 = input("Please enter your reserve price for the thing ")
Finallist.append(user1)
Finallist.append(user2)
Finallist.append(user3)
Finallist.append(user4)
Item = input("please enter your desired item")
# check only every 4th item in the list
# if we found a match, print it and the next 3
for i range(0, len(Finallist), 4)
if Item == Finallist[i]:
print(Finallist[i], Finallist[i+1], Finallist[i+2], Finallist[i+3])
break

How do I separate the numbers from an input in order to add them?

I am trying to have the user input a series of numbers (separated by commas) to receive the total of them.
I have tried (with no luck):
values = input("Input some comma seprated numbers: ")
numbersSum = sum(values)
print ("sum of list element is : ", numbersSum)
values = input("Input some comma seprated numbers: ")
list = values.split(",")
sum(list)
print ("The total sum is: ", sum)
If the user inputs 5.5,6,5.5 the expected output will be 17.
You're almost there.
After splitting, the values will still be strings, so you have to map them to float.
values = "5.5,6,5.5" # input("Input some comma seprated numbers: ")
L = list(map(float, values.split(",")))
print ("The total sum is: ", sum(L))
Output:
The total sum is: 17.0
Side note: Please don't name your variables list or sum, otherwise you will shadow the python built-ins!
After you split the values by comma into a list, you need to convert them from strings to numbers. You can do that with
values = input("Input some comma seprated numbers: ")
lst = values.split(",")
lst = [float(x) for x in lst]
total = sum(lst)
print("The total sum is: ", total)
For reference, see List Comprehensions in Python.
(Also, you shouldn't use list as a variable name, since that's a function in Python.)
You have to convert the inputs to float:
numbers = input("Input some comma seprated numbers: ")
result = sum([float(n) for n in numbers.split(',')])
print(result)
You have to convert to numbers before adding them together.
For example, you could convert them all into floats:
input_str = input("Input some comma seprated numbers: ")
# Option1: without error checking
number_list = [float(s) for s in input_str.split(',')]
# Option2: with error checking, if you are not sure if the user will input only valid numbers
number_list = []
for s in input_str.split(','):
try:
n = float(s)
number_list.append(n)
except ValueError:
pass
print("The list of valid numbers is:", number_list)
print("The sum of the list is:", sum(number_list))
# empty list to store the user inputs
lst = []
# a loop that will keep taking input until the user wants
while True:
# ask for the input
value = input("Input a number: ")
# append the value to the list
lst.append(value)
# if the user wants to exit
IsExit = input("enter exit to exit")
if 'exit' in IsExit:
break
# take the sum of each element (casted to float) in the lst
print("The sum of the list: {} ".format(sum([float(x) for x in lst])))
OUTPUT:
Input a number: 5.5
enter exit to exitno
Input a number: 6
enter exit to exitno
Input a number: 5.5
enter exit to exitexit
The sum of the list: 17.0
It's hard to know what went wrong w\o a sample of the error\output code.
I think the issue is in getting the sum of list (very bad name btw) when it's a list of strings.
please try the following
values = input("Input some comma seprated numbers: ")
lst = values.split(",")
lst = [int(curr) for curr in lst]
sum(lst)
print ("The total sum is: ", sum)
This code will work when expecting integers, if you want floats then change the list comprehension.
Try not to name objects with the same name of standard objects such as list,int,str,float etc...
use below
print('sum of input is :',sum(list(map(float,input('Input some comma separated numbers: ').split(',')))))

How would I loop this on Python?

How would I loop this code to make it so that the user inputs the number of friends they have, their names, and in the end, the program will be able to output the information? This is what I have so far, but I believe it's incorrect.
Friends = int(input("Please enter number of friends")
for i in range(Friends):
Name = input("Please enter friend number 1:")
Append each name to a list, then print the list. And use string formatting to put an appropriate number in the prompt.
friendList = []
Friends = int(input("Please enter number of friends")
for i in range(Friends):
Name = input("Please enter friend number %d: " % (i+1))
friendList.append(Name)
print(friendList)
Loop using the number of friends, and store the name for each of them:
friend_count = int(input("Please enter number of friends: "))
friend_list = []
for friend_index in range(friend_count):
name = input("Please enter friend number {}: ".format(friend_index + 1))
friend_list.append(name)
print(friend_list)
Here a try using list comprehension:
Friends = int(input("Please enter number of friends :"))
Names = [input("Please enter friend number {}:".format(i)) for i in range(1,Friends+1)]
print(Names)
You can use raw_input, from the documentation
If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.
Code
name_array = list()
num_friends = raw_input("Please enter number of friends:")
print 'Enter Name(s): '
for i in range(int(num_friends)):
n = raw_input("Name :")
name_array.append((n))
print 'Names: ',name_array

Inputting data into a paired list

Below is the code I am currently working with. Im trying to make it so I can add a second piece of data after the name so it reads (name1,data1),(name2,data2),(name3,data3). Is there a function that allows me to do this?
ListOfNames = []
while True:
Name = input('Input Band Member')
if Name != "":
ListOfNames.append(Name)
else:
break
You can store the information in two separate lists if you will and zip them together with zip() in the end.
You can try like so:
namel = []
bandl = []
while True:
n = input("Enter Name: ")
if n != '':
d1 = input("Enter data1: ")
namel.append(n)
bandl.append(d1)
else:
break
print(list(zip(namel, bandl)))
Demo output:
Enter Name: Rupee
Enter data1: India
Enter Name: Dollar
Enter data1: USA
Enter Name:
[('Rupee', 'India'), ('Dollar', 'USA')]
Or if you make sure the user enters 2 values separated by comma, you can try it like so:
l = []
while True:
n = input("Enter Name: ")
if n!='':
l.append(n.split(','))
else:
break
print(l)
Demo run:
Enter Name: Rupee, India
Enter Name: Dollar, USA
Enter Name:
[['Rupee', ' India'], ['Dollar', ' USA']]
You don't need a special function, just append a list instead of a string:
ListOfNames.append([Name, data])
Or, if you don't know what the data will be until later:
ListOfNames.append([Name])
and then:
ListOfNames[x].append(data)
Where x is the index of whatever list you want to append to.
Alternatively, if you prefer to build up the two lists independently first, you can use zip() to merge them them.
zip(ListOfNames, data_list)
That may or may not be more appropriate depending on your program's structure. Without knowing how or when or in what order your data_list is gathered, it's hard to say.

Categories

Resources