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.
Related
this is my homework:
Write a program that asks for the names and ages of 10 students.
Prints the names and ages of the students alphabetically in a table
format -- while also identifying the oldest student as the "Team
Leader".
And this is what I've done so far. Comments are what I think I'm supposed to do but not sure:
#from tabulate import tabulate
studentNames = []
for i in range(10):
item = input("Please enter a name: ")
if len(item) > 0 and item.isalpha():
studentNames.append(item)
#Something like this?
#print(tabulate(studentNames([[]], headers=['Team Leader', 'Students']))
My teacher didn't teach me tabulate but my research says I need to use it, but I think it's wrong and I don't know how to do it alphabetically. I'm sorry for the bad code, I'm embarrassed to even post it.
Any help would be appreciated. Thank you.
I don`t think it help when I solve the exercise for you. I would recommend you figure out how to add the input like the var table.
table = [("A", 20), ("Z", 21), ("C", 29), ("B", 24)]
sorted_table = sorted(table, key=lambda row: row[0])
leader = max(table, key=lambda row: row[1])
To print it you can simply iterate over the rows and print something like this:
print("{0} | {1}".format(row[0], row[1]))
My complete solution is this I would recommend you only use it if you are stuck again.
table = []
for i in range(10):
name = input("Please enter a name: ")
age = input("Enter the age: ")
if len(name) > 0 and name.isalpha():
table.append((name, age))
sorted_table = sorted(table, key=lambda row: row[0])
leader = max(table, key=lambda row: row[1])
print("{0:<12} | {1:<4}".format("Names", "Age"))
print("-" * 19)
for row in sorted_table:
print("{0:<12} | {1:<4}".format(row[0], row[1]))
print("Team Leader is: {0}".format(leader[0]))
Right... This is 90% of the Code... Considering it's your homework, you'll only need to find a quick way to add "Oldest Student" to the end of the Oldest Student which I'm sure you'll do pretty quick. I tried making it easy to read so you can learn. Good Luck!
# Python-3 (Change it slightly to make it usable for Python-2)
# Create an empty List to store input data...
studentDataList = []
# Little Extra to Spice up the Program...
numberOfStudents = int(input("Please Enter the Number of Students you Wish to Enter Data for: "))
studentCount = 1
# Create a Function for requesting data...
def getStudentData():
# Use variables outside this function
global studentCount
# Get Data and Verify
studentNameData = input("Enter Student (" + str(studentCount) + ") Name: ")
if len(studentNameData) != 0 and studentNameData.isalpha() == True:
studentAgeData = int(input("Enter Student (" + str(studentCount) + ") Age: "))
if studentAgeData != 0:
studentDataList.append(studentNameData + " " + str(studentAgeData))
studentCount += 1
else:
print("Invalid Entry")
getStudentData()
else:
print("Invalid Entry")
getStudentData()
# Run For Loop...
for num in range(numberOfStudents):
getStudentData()
# Sort List...
studentDataList.sort()
# Finally Print Table...
for item in studentDataList:
print(item)
Each time I enter a restaurant name and then go to print the list, it does not stay inside that list. I also need to be able to use the randomize command so that Randomize() will generate a random number and use it as an index to print the restaurant at that index to the screen.
while(True):
getInput=input("Enter a restaurant name: ")
list=[]
list.append(getInput)
if(str(getInput) == "List"):
print(list)
elif(str(getInput) == "Quit"):
break;
I end up getting this:
Enter a restaurant name: Name
Enter a restaurant name: Names
Enter a restaurant name: List
['List']
Enter a restaurant name:
I need to be able to enter a restaurant and then be able to pull up that certain restaurant with a number. I just started Python a couple of months ago. Thank you!
Couple things:
You don't want to use a name like "list" because it's a function and type in Python which can make things confusing so instead name it something like "my_list".
And your issue was every loop you were starting the list from scratch. You want to move that list outside the loop instead.
my_list = []
while True:
getInput = input("Enter a restaurant name: ")
my_list.append(getInput)
if getInput == "List":
print(my_list)
elif getInput == "Quit":
break
Edit:
To answer your comment question, you can add in a number using a manual counter if you wanted (for simplicity and understandability):
my_list = []
id = 0
while True:
getInput = input("Enter a restaurant name: ")
my_list.append(f'{id}_{getInput}')
id += 1
if getInput == "List":
print(my_list)
elif getInput == "Quit":
break
You are creating a new list each time the loop repeats. Instead you should create the list before the loop even starts.
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)])
I want to input how many victims, and then be able to input name and age for each victims.
But I can't seem to wrap my head around how to make a loop that ask for input for each victim. Right now I make one input and the same input is printed x times.
I can see the logic in how it works now, but I simply can't figure out how to do it without making 5 x separate input for "name" and 5 x separate input for "age".
num_victims = input("How many victims: ")
inc_numbr = 1
v_name = input(str(inc_numbr) + "." + " Victims " + "name: ")
v_age = input(str(inc_numbr) + "." + " Victims " + "age: ")
inc_numbr += 1
v_numbr = 1
v_one = (f"__Victim:__ \n"
f"Name: {v_name}\n"
f"Estimated age: {v_age} years old.\n\n")
v_numbr += 1
v_two = (f"__Victim " + str(v_numbr) + ":__\n"
f"Name: {v_name}\n"
f"Estimated age: {v_age} years old.\n\n")
v_numbr += 1
v_three = (f"__Victim " + str(v_numbr) + ":__\n"
f"Name: {v_name}\n"
f"Estimated age: {v_age} years old.\n\n")
v_numbr += 1
v_four = (f"__Victim " + str(v_numbr) + ":__\n"
f"Name: {v_name}\n"
f"Estimated age: {v_age} years old.\n\n")
v_numbr += 1
v_five = (f"__Victim " + str(v_numbr) + ":__\n"
f"Name: {v_name}\n"
f"Estimated age: {v_age} years old.\n")
v_numbr += 1
Added for output format example:
__Victim:__
Name: xxxxx
Age: xxxx
__Victim 2:__
Name: xxxxx
Age: xxxx
Ect..
You need to wrap it up in a for loop:
number_of_victims = int(input("How many victims? "))
victim_names = []
victim_ages = []
for i in range(1, number_of_victims+1):
victim_names.append(input("Name of victim "+str(i)+": "))
victim_ages.append(input("Age of victim "+str(i)+": "))
print(victim_names, victim_ages)
Note how I have created the victim_names and victim_ages objects outside of the for loop so that they're not overwritten. These objects are lists - they're empty initially, but we append data to them inside the for loop.
You could use a dictionary object for victims instead if you wanted, but as Alex F points out below, if you have two victims with the same name this may result in data being overwritten:
number_of_victims = int(input("How many victims? "))
victims = dict()
for i in range(1, number_of_victims+1):
name = input("Name of victim "+str(i)+": ")
age = input("Age of victim "+str(i)+": ")
victims[name] = int(age)
print(victims)
In the future, when approaching a problem like this, you might find it helpful to write pseudo-code. This is like a plan for what your code will look like without having to worry about the syntax and rules for actually writing it. For example some pseudo-code for this problem might look like:
ask for the number of victims
make an empty object to store the victim information
repeat this as many times as there are victims:
ask for the name of the victim
ask for the age of the victim
add victim information into the object
display the contents of the object
In answer to the question in the comments, how to format the printing, you could do something like this:
for v in range(number_of_victims):
print("Victim ",str(v+1),":")
print("Name:",victim_names[v])
print("Age:",victim_ages[v])
Loop is used for code that needs to be run multiple times, therefore if you need to ask for number of victims once, but then enter multiple name's and age's, you can do it like this:
number_of_victims = int(input("Enter the number of victims: "))
victims = []
for i in range(number_of_victims):
name = input("Victim #{} name: ".format(i+1))
age = input("Victim #{} age: ".format(i+1))
victims.append([name, age])
This way you get a list, where each element is a list of name and age. Now you can access file number i with victims[i-1] (because list indices start with 0).
Another option would be using a dictionary:
number_of_victimes = int(input("..."))
victims = {}
for i in range(number_of_victims):
name = input("...")
age = input("...")
victims[i] = [name, age]
You can access file number i with victims[i-1] (because range starts at 0 as well) but you can change this if you write for i in range(1, int(number_of_victims)+1):. Now each dictionary key is the "human" index (starting from 1), instead of "computer's" index (starting from 0), so you can access the same file number i using victims[i].
Alternatively, you could make a dictionary where each key is the name of the victim, but in case you ever have 2 identical names, the previous key-value pair you have added using that name will get overwritten:
number_of_victimes = int(input("..."))
victims = {}
for i in range(number_of_victims):
name = input("...")
age = input("...")
victims[name] = int(age)
I have a file called "periodic_table". Inside this file is multiple lines. Each line has an atomic number on the side and a corresponding element name on the right like this:
1 Hydrogen
2 Helium
3 Lithium
4 Beryllium
5 Boron
6 Carbon
7 Nitrogen
8 Oxygen
9 Fluorine
10 Neon
11 Sodium
12 Magnesium
13 Aluminium
14 Silicon
etc...
I made a program that asks for either the element name or number, and prints out the corresponding value in the dictionary. If the user inputs 1 it will print Hydrogen, similarly if the user inputs Silicon it will output 14. HOWEVER - I want the program to inform the user if he enters a non existent atomic number (such as 150) or a non existent element (such as Blanket or any other string). I tried using an if but it printed out an infinite loop:
element_list = {}
name = input("Enter element number or element name: ")
while name:
with open("periodic_table.txt") as f:
for line in f:
(key, val) = line.split()
element_list[int(key)] = val
if name == key:
print(val)
elif name == val:
print(key)
name = input("Enter element number or element name: ")
For minimal changes to your existing code, you could set a flag found if the element is found, and act on it accordingly. So:
found = False
for line in f:
# ....
if name == key:
print(val)
found = True
elif ...
if not found:
print("Not an element or atomic number: {}".format(name))
You could simply quit your program as soon as a match is found. If no match is found, the user will be prompted for input again. Otherwise the program will terminate after printing the corresponding number/name.
# http://docs.python.org/2/library/sys.html
import sys
#variable below is not doing much!
#element_list = {}
name = input("Enter element number or element name: ")
#Changed loop to be infinite
while True:
with open("periodic_table.txt") as f:
for line in f:
(key, val) = line.split()
element_list[int(key)] = val
if name == key:
print(val)
sys.exit()
elif name == val:
print(key)
sys.exit()
#If something is found, it will never reach this
print("No match found... try again!")
name = input("Enter element number or element name: ")
To efficiently solve this problem (without reading the file repeatedly) you need to break it down into two steps, which your current code is mixing together. First, read the file and prepare the dictionary mapping between element names and numbers. Second, process user input and check against the dictionary.
# step 1, build the mapping
element_list = {}
with open("periodic_table.txt") as f:
for line in f:
number, name = line.split()
element_list[number] = name
element_list[name] = number # map in both directions
# step 2, test user input (quits after an empty input)
user_entry = input("Enter element number or name: ")
while user_entry:
try:
print(element_list[user_entry])
except KeyError:
print("Unrecognized number or name.")
user_entry = input("Enter element number or name: ")