I have a student management program and I use a for loop to look up in dictionaries inside a list so I have if and elif conditions to search for student data. However, it gives output with 3 or 4 elif conditions also. I want that if the program doesn't find student data it only prints "student not found" once and if I have student data only the if clause should run not elif.
import json
while True:
student={}
with open('Data file for student management system.json','r') as f:
students=json.load(f)
print('''\n"1 or add" to Add Student''')
print('''"2 or edit" to Edit Student''')
print('''"3 or delete" to Delete Student''')
print('''"4 or search" to Search Student''')
print('''"5 or display" to Display all Students''')
while True:
try:
option=str(input('''\nPlease enter any option given above:'''))
if option not in ['1','2','3','4','5','add','delete','edit','search','display']:
print('''\n"Please select a correct options"''')
else:
break
except ValueError:
print('''"Please enter a correct number only"''')
if option in ['1','add']:
student["Name"] = input ("\nStudent's Name:").title()
student["Father Name"] = input ("Father's Name:").title()
student["Age"] = input ("Student's Age:")
student["Address"] = input ("Address:").title()
students.append(student)
with open('Data file for student management system.json','w') as f:
json.dump(students,f)
student={}
print('''\n"Addition Successful"''')
elif option in ['2','edit']:
Name=input("\nPlease type name:").title()
new_name=input("\nWhat is new name:").title()
for s in list(students):
for d in s:
if s['Name']==Name:
s['Name']=new_name
print('''\n"Edit Successful"''')
with open('Data file for student management system.json','w') as f:
json.dump(students,f)
elif s['Name']!=Name:
print('''\n"Student not found"''')
break
elif option in ['3','delete']:
del_name=input("\nPlease type name of student you want to delete:").title()
for s in list(students):
for d in s:
if s['Name']==del_name:
ind=students.index(s)
while True:
sure=input('\nAre you sure you want to delete?\n\nYes or No:').lower()
if sure in ['yes','y']:
del students[ind]
print('''\n"Deletion Successful"''')
with open('Data file for student management system.json','w') as f:
json.dump(students,f)
break
elif sure in ['no','n']:
print("\nStudent data not deleted")
break
else:
print('''"\nPlease enter a coorect option"''')
break
elif s['Name']!=del_name:
print('''\n"Student not found"''')
break
elif option in ['4','search']:
s_name=input("\nEnter name of student:").title()
for d in students:
for k,v in d.items():
if d['Name']==s_name:
print(" ____________________________________________________________________________________________________________________________")
print("| | | | |")
print("| S-No | Name | Father Name | Address |")
print("|__________|________________________________|_________________________________|______________________________________________|")
print(f"| |{d['Name']: <32}|{d['Father Name']: <33}|{d['Address']: <46}|")
print("|__________|________________________________|_________________________________|______________________________________________|")
break
elif d['Name']!=s_name:
print('''\n"Student not found"''')
break
elif option in ['5','display']:
print(" ____________________________________________________________________________________________________________________________")
print("| | | | |")
print("| S-No | Name | Father Name | Address |")
print("|__________|________________________________|_________________________________|______________________________________________|")
for s in students:
for k,v in s.items():
pass
print(f"| |{s['Name']: <32}|{s['Father Name']: <33}|{s['Address']: <46}|")
print("|__________|________________________________|_________________________________|______________________________________________|")
while True:
Repeat=input("\nDo you want to repeat?\n\nYes or No:")
Repeat=Repeat.lower()
if Repeat not in ["yes","y","no","n"]:
print("\nPlease select correct option")
else:
break
if Repeat in ["yes","y"]:
continue
else:
if Repeat in ["no","n"]:
print("\n-----Thank you for using-----")
input()
break
json file
[{"GR#": 1, "Name": "Daniyals", "Age": 12, "Father Name": "Ajaz", "Address": "Flat-123, Block ABC"}, {"GR#": 2, "Name": "Shahrukh Khan", "Age": 9, "Father Name": "Ajeeb Khan", "Address": "Khan Mansion"}, {"Name": "Waseem Munir", "Father Name": "Sdasd", "Age": "asdasdas", "Address": "Asdasdas"}, {"Name": "Saad", "Father Name": "Asdsadas", "Age": "asdasdas", "Address": "Asdas"}, {"Name": "Sdasd", "Father Name": "Adsadas", "Age": "dasdas", "Address": "Dasdas"}]
I suggest use pandas dataFrame it will make it so much easier.
import pandas as pd
df = pd.DataFrame(
{'Name': ['a','b','c','d'], #Your name list here
'Fathers Name': np.zeros(4), #Your data here
'Address': np.zeros(4), #Your data here and add more columns
})
s_name=input("\nEnter name of student:").title()
for i in range(len(df)):
if df['Name'][i] == s_name:
print(df.loc[i])
Related
I need to sort this data chronologically, hopefully, by date and them by time, but right now I just want to sort it by date... the information is on a TXT file:
2022/5/10 at 10 the client Mari has appointment with the Dra. Windrunner
2022/1/5 at 2 the client Ian has appointment with the Dr. Stark
2022/1/4 at 10 the client Amy has appointment with the Dra. Windrunner
2022/1/5 at 2 the client Josh has appointment with the Dr. Stark
2022/2/22 at 5 the client Mike has appointment with the Dr. Pool
2022/2/22 at 4 the client Pedro has appointment with the Dr. Stark
This is my code right now:
Docs = ("Dr. Stark", "Dra. Windrunner", "Dr. Pool")
x = 0
loop = False
DocsConverter = {
"0" : "Dr. Stark",
"1" : "Dra. Windrunner",
"2" : "Dr. Pool",
"dr. stark": "Dr. Stark",
"dra. windrunner" : "Dra. Windrunner",
"dr. pool" : "Dr. Pool",
"stark" : "Dr. Stark",
"windrunner" : "Dra. Windrunner",
"pool" : "Dr. Pool"
}
with open("appointment_hospital.txt", "a") as file_ap:
pass
def menu():
option = input("select a option 1. new appointment 2.show appointments 3. Exit: (1/2/3)\n")
if option == "1":
new_appointment()
elif option == "2":
print_appointments()
elif option == "3":
file_ap.close()
exit()
else:
print("Wrong option")
def new_appointment():
global x
name_client = input("Enter the name of the client:\n")
schedule_day = input("Enter the year, month and the day of the appointment:(Y/M/D)\n")
schedule_time= input("Enter at what hour is the appointment:\n")
while x != 3:
print(f"{Docs[x]}, id = {x}")
x += 1
x = 0
which_doc = input("Enter the name or the Id of the doctor: ")
appointment_info = f"{schedule_day} at {schedule_time} the client {name_client} has appointment with the " \
f"{DocsConverter.get(which_doc)}\n"
with open("appointment_hospital.txt", "a") as file:
file.write(appointment_info)
#this is where i tried to sort the information in the txt
def print_appointments():
with open("appointment_hospital.txt", "r") as file:
lines_appointments = []
for line in file:
temp = line.split()
for i in temp:
lines_appointments.append(i)
lines_appointments.sort()
with open("sort_appointments", "w") as sort_file:
for i in lines_appointments:
sort_file.writelines(i)
sort_file.writelines(" ")
sort_file.close()
with open("sort_appointments", "w") as sort_file:
read_appointments = sort_file.read()
print(read_appointments)
while not loop:
menu()
So in def print_appointments(): I tried to sort the data, and this was my last tried, None of the ones I have done have given me a moderately positive result.
You have some mistakes:
no file extension open("sort_appointments"
to sort by dates residual split the file by lines
when writing a list to a file, you need to open it for appending "a"
when reading a file, you must put the letter "r"
def print_appointments():
with open("appointment_hospital.txt", "r") as file:
lines_appointments = []
for line in file:
lines_appointments.append(line)
lines_appointments.sort()
with open("sort_appointments.txt", "a") as sort_file:
sort_file.writelines(lines_appointments)
with open("sort_appointments.txt", "r") as sort_file:
read_appointments = sort_file.read()
print(read_appointments)
print_appointments()
So the code I'm doing right now as to create a catalogue, so first it asks the user how many items he wants to add to the catalogue and the to introduce 7 attributes to this item, being name, type, color, power, light type, price and units. In addition to this I'm also storing the id (first item would be 1, second is 2, etc) and the price + taxes.
lee_entero is a function that makes sures the number introduced is positive and an integer.
To do this i do the following:
prod={}
l=[]
n= lee_entero("how many items? ")
for i in range(1,n+1):
p_nombre = input("Name: ")
p_tipo = input("Type: ")
p_color = lee_color("Color: ")
p_potencia = lee_RealPositivo("Power(K): ")
p_tipoLuz = lee_luz("Light type (amarillo, azul o blanco): ")
p_precio = lee_RealPositivo("Price without taxes: ")
if (p_precio <= 50):
print("Low price ")
elif (p_precio <= 100):
print("Medium Price ")
else:
print("High price ")
p_total = p_precio + p_precio*IVA/100
p_unidades = lee_entero("Units: ")
ids=i
prod={"Product nº":ids, "name": p_nombre, "type": p_tipo, "color": p_color, "power": p_potencia, "light type": p_tipoLuz, "price": p_precio, "total": p_total, "units": p_unidades }
l.append(prod)
i=i+1
And then I want this to be displayed as a table for which i have tried:
print("{:<15} {:<15} {:<15} {:<15} {:<15} {:<15} {:<15} {:<15} {:<15}".format("id", "Nombre", "Tipo", "Color", "Potencia", "Tipo Luz", "Precio", "Precio IVA", "Unidades"))
print("*******************************************************************************************************************************************************")
for key, value in prod.items():
elid, nombre, tipo, color, potencia, tipoluz, precio, precioiva, unidades = value
print("{:<15} {:<15} {:<15} {:<15} {:<15} {:<15} {:<15} {:<15} {:<15}".format(elid, nombre, tipo, color, potencia, tipoluz, precio, precioiva, unidades))
but this doesn't work.
Overall im looking for a way to store the values of each product and then display them as a table without importing any libraries, but right now is giving me the TypeError: cannot unpack non-iterable int object and I haven't been able to make it work, so any help is appreciated.
You are iterating over a dict, so using
for key, value in prod.items():
will generate pair
key == "Product nº"
value == ids
in the first iteration. So you are trying to unpack value, which is int. To achieve what you want, to can do something like:
for value in prod.values():
print("{:<15}".format(value),end=" ")
print()
which will print all values from the dictionary without a new line, and then add a new line at the end
I want to control my python script output with values in a csv:
I select a Category and some parameters like that:
csv1
or like that csv2
In my python-script I got the Values of each parameter in a list that looks like that:
A_Names = ("Anton", "Berta", "Charlie")
Ages = ("32","18","23")
Nicknames = ("Agent A", "Agent B", None)
Birthdays = ("03.03.1986", "02.02.2000", "01.01.1995")
IDs = (100, 200, 300)
The idea now is to have a script that will combine these information so the output for csv1 would be:
Anton
A_Name: Anton
Age: 32
Nickname: Agent A
Birthday: 03.03.1986
Berta
A_Name: Berta
Age: 18
Nickname: Agent B
Birthday: 02.02.2000
Charlie
A_Name: Charlie
Age: 23
Nickname: No Nickname yet
Birthday: 01.01.1995
and the output for the csv2 would be:
Anton
Nickname: Agent A
A_Name: Anton
ID: 100
Berta
Nickname: Agent B
A_Name: Berta
ID: 200
Charlie
Nickname: No Nickname yet
A_Name: Charlie
ID: 300
and of course it should also work both together in a csv3 like that, and the same outputs just after another.
So the first idea was just to code my output like that:
#let's assume i got the columns from the csv in lists like that:
Categories = ("Agents", "Agents")
Parameter1 = ("A_Name", "Nickname")
Parameter2 = ("Age", "A_Name")
Parameter3 = ("Nickname", "ID")
Parameter4 = ("Birthday")
#then the most unflexible code would look like that:
def Show_Values():
for n in range (0,len(A_Names)):
print A_Names[n]
print " %s: %s" % (Parameter1[0], A_Names[n])
print " %s: %s" % (Parameter2[0], Ages[n])
print " %s: %s" % (Parameter3[0], Nicknames[n])
print " %s: %s" % (Parameter4[0], Birthdays[n])
for n in range (0,len(A_Names)):
print A_Names[n]
print " %s: %s" % (Parameter1[1], Nicknames[n])
print " %s: %s" % (Parameter2[1], A_Names[n])
print " %s: %s" % (Parameter3[1], IDs[n])
Show_Values()
So this is very stupid code and I repeat myself there over and over and always need to add the correct value for the 2nd %s.
My question now is how can I create a smarter, shorter Code, that knows that A_Name[0] is the first Element of A_Names.
And that he should add the "%s: %s" % (parameter, value), automatically for the amount of parameters I am looking for via the csv. I think I need
the length of the row for that so two more lists from the csv:
Row0 = (Agents, A_Name, Age, Nickname, Birthday)
Row1 = (Agents, Nickname, A_Name, ID)
len(Row0)-1
len(Row1)-1
edit:
Ok thank you so far, here's my new approach, reading rows only from a csv:
import csv
with open("TableAgentsComma.csv", "rb") as file:
reader = csv.reader(file, delimiter=",")
inputHeader = next(reader)
rows=[r for r in reader]
A_Names = ["Anton", "Berta", "Charlie"]
Ages = ["32","18","23"]
Nicknames = ["Agent A", "Agent B", None]
Birthdays = ["03.03.1986", "02.02.2000", "01.01.1995"]
IDs = [100, 200, 300]
def Show_Values():
for n in range (0, len(A_Names)):
print A_Names[n]
print " %s: %s" % (rows[0][1], A_Names[n])
print " %s: %s" % (rows[0][2], Ages[n])
print " %s: %s" % (rows[0][3], Nicknames[n])
print " %s: %s" % (rows[0][4], Birthdays[n])
for n in range (0, len(A_Names)):
print A_Names[n]
print " %s: %s" % (rows[1][1], Nicknames[n])
print " %s: %s" % (rows[1][2], A_Names[n])
print " %s: %s" % (rows[1][3], IDs[n])
Show_Values()
But of course it's still an inflexible script and I would like it to respond to the csv, and generate its output depending on the amount of rows and the parameters inside.
Also I need to find out how the script will know that the parameter "ID" is found in the list IDs etc.
The csv file:
Category,Parameter1,Parameter2,Parameter3,Parameter4,Parameter5,
Agents,A_Name,Age,Nickname,Birthday,,
Agents,Nickname,A_Name,ID,,,
Agents,A_Name,Age,,,,
Agents,ID,,,,,
If you store the data as a dictionary you can look up the key based on the name in the csv file:
data = {
"A_Names" : ["Anton", "Berta", "Charlie"],
"Ages" : ["32","18","23"],
"Nicknames": ["Agent A", "Agent B", None],
"Birthdays": ["03.03.1986", "02.02.2000", "01.01.1995"],
"IDs": [100, 200, 300]
}
def Show_Values():
for row in rows:
for n in range (0, len(data["A_Names"])):
print data["A_Names"][n]
for header in row:
if header == "Agents" or header == "": # This field doesn't match any thing in the data.
continue
header = header.strip()
header += "s"
print " %s: %s" % (header, data[header][n])
Since the data is now in a dict we can look up the value based on the parameter which we got from the file. I probably should have called it "parameter" rather than "header".
Show_Values()
Output:
Anton
A_Names: Anton
Ages: 32
Nicknames: Agent A
Birthdays: 03.03.1986
Berta
A_Names: Berta
Ages: 18
Nicknames: Agent B
Birthdays: 02.02.2000
Charlie
A_Names: Charlie
Ages: 23
Nicknames: None
Birthdays: 01.01.1995
And then from the second row in the .csv:
Anton
Nicknames: Agent A
A_Names: Anton
IDs: 100
Berta
Nicknames: Agent B
A_Names: Berta
IDs: 200
Charlie
Nicknames: None
A_Names: Charlie
IDs: 300
I'm working on assignment for my Python 3 programming class. It's a database to look up movies and the year they came out. However, I'm having a hard time printing the output without extra brackets and quotes:
# Build a dictionary containing the specified movie collection
list_2005 = [["Munich", "Steven Spielberg"]]
list_2006 = [["The Departed", "Martin Scorsese"], ["The Prestige", "Christopher Nolan"]]
list_2007 = [["Into the Wild", "Sean Penn"]]
movies = {
'2005': list_2005,
'2006': list_2006,
'2007': list_2007
}
# Prompt the user for a year
# Displaying the title(s) and directors(s) from that year
user_year = str(input("Enter a year between 2005 and 2007:\n"))
if user_year in movies:
for name in movies[user_year]:
print("%s" % ', '.join(name))
print()
elif user_year not in movies:
print("N/A")
# Display menu
user_choice = ''
while user_choice != 'q':
print("MENU\nSort by:\ny - Year\nd - Director\nt - Movie title\nq - Quit")
print()
user_choice = str(input("Choose an option:\n"))
if user_choice == 'y':
for key, value in sorted(movies.items()):
print("%s:" % key)
print(" %s" % ''.join(str(movies[key])))
# Carry out the desired option: Display movies by year,
# display movies by director, display movies by movie title, or quit
I would like this output to be:
2005:
Munich, Steven Spielberg
2006:
The Prestige, Christopher Nolan
The Departed, Martin Scorsese
etc.
The output I am getting:
2005:
['Munich', 'Steven Spielberg']
2006:
[['The Prestige', 'Christopher Nolan'], ['The Departed', 'Martin Scorsese']]
etc.
Replace
print(" %s" % ''.join(str(movies[key])))
with
print("\t" + '\n\t'.join("{}, {}".format(m[0], m[1]) for m in movies[key]))
dic = {
'key_1':['val_1','val_2'],
'key_2':['val_3','val_4'],
'key_3':['val_5','val_6']
}
info = {
'i_1':'good',
'i_2':'bad'
}
for k,v in dic.items()
print 'Jack scrd'+info[i_2]+"in both subjects"+dic[val1]+'&'+dic[val2]
I know the print code is not right but gave it here for understanding what I really wanted to do here. I want only the above similar line in printing command.
The following does this. The format command allows you to easily substitute {} with the variables of your choice in a string. When it comes to the dictionary dic[k] would render all the lists which ['val_1','val_2'] is one. So you would give dic[k][0] to get the first value, and dic[k][1] to get the second value.
for k,v in dic.items():
msg = 'Jack scrd {} in both subjects {} & {}'
print msg.format(info['i_2'], dic[k][0], dic[k][1])
# Jack scrd bad in both subjects val_1 & val_2
# Jack scrd bad in both subjects val_5 & val_6
# Jack scrd bad in both subjects val_3 & val_4
Perhaps you want to do this?
Remove the for loop
print 'Jack scrd'+info['i_2']+'in both subjects'+str(dic['key_1'][0])+"&"+str(dic['key_1'][1])
you can use .join to join all list items with a given separator. If you want to print all keys of dic you can use:
dic = {
'key_1':['val_1','val_2'],
'key_2':['val_3','val_4'],
'key_3':['val_5','val_6']
}
info = {
'i_1':'good',
'i_2':'bad'
}
for keys in dic:
# .join will join all list items for a particular key with & and store it in variable subjects
subjects = ' & '.join(dic[keys])
print "jack scored " + info['i_1'] + " in both subjects " + subjects
output:
jack scored good in both subjects val_1 & val_2
jack scored good in both subjects val_5 & val_6
jack scored good in both subjects val_3 & val_4
place_iraq = {
'shrine_1' : ['karbala','imam hussein as.'],
'shrine_2' : ['najaf', 'imam ali as.'],
'yard' : ['karbala', 'wadi-us-salam'],
'shrine_3' : ['karbala', 'abbas as.']
}
type = {
't1':'shrine',
't2': 'grave yard'
}
print 'The '+str(type['t1'])+' of '+str(place_iraq['shrine_1'][1])+' is situated in ' +\
str(place_iraq['shrine_1'][0])
print 'The '+str(type['t1'])+' of '+str(place_iraq['shrine_2'][1])+' is situated in ' +\
str(place_iraq['shrine_2'][0])
print 'The '+str(type['t1'])+' of '+str(place_iraq['shrine_3'][1])+' is situated in ' +\
str(place_iraq['shrine_3'][0])
print 'The '+str(type['t2'])+' of '+str(place_iraq['yard'][1])+' is situated in ' +\
str(place_iraq['yard'][0])