Im trying to print the email of the student, in the while loop at the bottom im also trying to input the students email but I cannot figure how to do it correctly.
Code:
array1 = []
numstudents = int(input("How many students are in the class?: "))
for i in range (numstudents):
studentname,studentemail,dayofbrith,monthofbrith,yearofbrith = input("Enter the student name, the
student's email and the date of birth in the form 'name, email, day of birth, month of birth, year
of birth' : ").split("")
array1.append(studentname+studentemail+dayofbrith+monthofbrith+yearofbrith)
if studentname == "stop":
print("")
break
else:
print("")
print(array1)
while True:
email = input("From which student's email you want: ")
if email any in array1[0]:
print("")
print(array1[1])
students = []
numstudents = int(input('How many students are in the class?: '))
for _ in range(numstudents):
print("Please enter the following: ")
print("The student's name, The student's email, day of birth, month of birth, year of birth")
students.append(input().split())
target = input("Which studen't email you want: ")
for i in students:
if i[0] == target:
print(f"The student's email is {i[1]}")
Try if this is what you want
Ah, definitely a problem for a dictionary.
dict1= {}
numstudents = int(input("How many students are in the class?: "))
for _ in range (numstudents): #As nk03 correctly points out - we don't need to carry the iterator, so can use an _ instead
studentname,studentemail,dayofbirth,monthofbirth,yearofbirth = input("Enter the student name, the student's email and the date of birth in the form 'name,email,day of birth,month of birth,year of birth' : ").split(",")
if studentname == "stop":
break
else:
dict1[studentname] = {'email':studentemail, 'dOB':dayofbirth, 'mOB':monthofbirth, 'yOB':yearofbirth}
while True:
name = input("From which student's email you want: ")
if name in dict1:
print(dict1[name]['email'])
else:
print(name + " not found in dict")
Related
Im doing an exercise where I have to ask for input of info and input of medical records, and I'm not sure how to "link" a medical record from one dictionary, to a patient of my other dictionary.
So far, I've got this.
For patient info:
info_patients = []
while True:
Name = input("Insert name: ")
Lastname = input("Insert last name: ")
Birth = input("Insert date of birth: ")
Nationality = input("Insert nationality:")
repeat = input("Do you need to add more data? (yes / no): ")
info_patients.append({
"Name": Name,
"Lastname": Lastname,
"Birth": Birth,
"Nationality": Nationality
})
if repeat == 'no' or repeat == 'NO':
break
print(info_patients)
For medical records:
med_record = []
while True:
Date = input("Insert date of treatment: ")
Reason = input("Insert reason of treatment: ")
Doctor = input("Insert doctor in charge of treatment: ")
Remark = input("Insert any remarks:")
repeat = input("Do you need to add more data? (yes / no): ")
med_record.append({
"Date": Date,
"Reason": Reason,
"Doctor": Doctor,
"Remark": Remark
})
if repeat == 'no' or repeat == 'NO':
break
print(med_record)
How can I make it so, by an user input, link a medical record from my last dict to a patient of my first dict?
Hi am new just started Computer Science at London Met we have programming in Python. In this code am trying to add items to already existing appended list list.append([student_name, student_age, student_sex]) from user input student_grade. How can i do this for each item in range. SO next time i print student_grade will be added to at the end of statement in form {each_item[3]} and 3 in the case will be student_grade ?
thanks in advance
from io import StringIO
import sys
number_student = int(input("How many students You want to add: "))
list = []
for i in range(0, number_student):
student_name = input("Whats Your name student? ")
student_age = input("Whats Your age student? ")
student_sex = input("Female or male? ")
list.append([student_name, student_age, student_sex])
comment withhash student_1 = (student_name, student_age + "years old", student_sex)
for each_item in list:
print(f"Student name is {each_item[0]}, you are {each_item[1]} years old and you are {each_item[2]}")
student_grade = input("Add student grade: ")
list.extend(["student_grade"])
#list.extend([student_grade])
for each_item in list:
print(f"Student name is {each_item[0]}, you are {each_item[1]} years old and you are {each_item[2]}, and your grades are", student_grade)
You shouldn't be adding student_grade to list, you should be adding it to each_item, the list for the current student.
Then when printing the grade, you use each_item[3] to get it.
Also, don't use list as a variable name, because it's a built-in function. I've renamed it to student_list below.
number_student = int(input("How many students You want to add: "))
student_list = []
for i in range(0, number_student):
student_name = input("Whats Your name student? ")
student_age = input("Whats Your age student? ")
student_sex = input("Female or male? ")
student_list.append([student_name, student_age, student_sex])
#student_1 = (student_name, student_age + "years old", student_sex)
for each_item in student_list:
print(f"Student name is {each_item[0]}, you are {each_item[1]} years old and you are {each_item[2]}")
student_grade = input("Add student grade: ")
each_item.append(student_grade)
for each_item in student_list:
print(f"Student name is {each_item[0]}, you are {each_item[1]} years old and you are {each_item[2]}, and your grades are {each_item[3]}")
This is my exercise: get the user's first name, last name and birth year. Create initials from the name (first letter) and calculate the age of the user.
I wrote a script:
def age_name():
# var= firstName ,lastName ,year
is_running=True
firstName =input("What is your name?").lower()
while is_running==True:
if firstName.isalpha() and len(firstName)>0:
lastName = input("What is your last name?").lower()
if lastName.isalpha() and len(lastName) > 0:
year = input("What is your birth year?")
if year.isnumeric() or len(year)==4:
year=int(year)
print("Your initials are {0}{1} and your age is {2}.".format(firstName[0],lastName[0],2018-year))
#print("Your initials are ",firstName[0],lastName[0],"and your age is ",str(2018-year))
else:
print("invalid year. please type your birth year")
year = input("What is your birth year?")
else:
print("invalid last name. please type your last name")
lastName = input("What is you last name?").lower()
else:
print("invalid name. please type your name")
firstName = input("What is you name?").lower()
age_name()
I've tested the code and this is what I get:
What is your name?p5
invalid name. please type your name
What is you name?peter
What is your last name?p5
invalid last name. please type your last name
What is you last name?pen
What is your last name?pen
What is your birth year?p5
invalid year. please type your birth year
What is your birth year?10
What is your last name?pen
What is your birth year?1800
Your initials are pp and your age is 218.
What is your last name?
First of all, I think my code is a bit repetitive - if someone has ideas to shorten it. Second and biggest problem - I keep getting the last name question. Where is my bug?
I think the best readable while least error prone way would be sth like below. The input lines are programmed only once each and everything is dependent on the state of response_invalid.
def age_name():
response_invalid = True
while response_invalid:
firstName = input("What is your name?").lower()
if firstName.isalpha() and len(firstName)>0:
response_invalid = False
else:
print("invalid name. please type your name")
response_invalid = True
while response_invalid:
lastName = input("What is your last name?").lower()
if lastName.isalpha() and len(lastName) > 0:
response_invalid = False
else:
print("invalid last name. please type your last name")
response_invalid = True
while response_invalid:
year = input("What is your birth year?")
if year.isnumeric() or len(year)==4:
response_invalid = False
else:
print("invalid year. please type your birth year")
year=int(year)
print("Your initials are {0}{1} and your age is {2}.".format(firstName[0],lastName[0],2018-year))
However, this is the verbose variant of a very common way to implement this, which is I think the shortest, but a little rude...:
def age_name():
while True:
firstName = input("What is your name?").lower()
if firstName.isalpha() and len(firstName)>0:
break
print("invalid name. please type your name")
while True:
lastName = input("What is your last name?").lower()
if lastName.isalpha() and len(lastName) > 0:
break
print("invalid last name. please type your last name")
while True:
year = input("What is your birth year?")
if year.isnumeric() or len(year)==4:
break
print("invalid year. please type your birth year")
year=int(year)
print("Your initials are {0}{1} and your age is {2}.".format(firstName[0],lastName[0],2018-year))
How does this look?
def age_name():
firstname=input("What is your name?")
while firstname.isalpha()!=True:
print("Invalid name, enter again")
firstname = input("What is your name?")
lastname = input("What is your last name?")
while lastname.isalpha()!=True:
print("Invalid name, enter again")
lastname = input("What is your last name?")
year = input("What is your birth year?")
while len(year) != 4 and year.isdigit():
print("Invalid year, enter again")
year = input("What is your birth year?")
year = int(year)
print("First Name:",firstname,"\nLast Name:",lastname,"\nBirth Year:",year)
age_name()
That looks so much better. Thank you.
but look at the error I get when I type year whis letters:
What is your birth year?g5
ValueError: invalid literal for int() with base 10: 'g5'.
i've changed the last while operator from and to or and it works beautifully.
I need help with a python file to make a simple Grade Book print properly. I've gotten it to print but its not doing exactly what I need it to. The print results look like this,
{'Fred': '99', 'Fred2': '99', ...}
Ideally I'd like it to print just the name and grade next to each other, on a new line for each name / grade. Something like this:
"Name: Fred | Grade: 99"
I have to use a list / dictionary and need the while loop
Here is the best solution I have tried thus far:
student_grades = {}
entries = input('Would you like to enter a students name and grade? (Y/N): ')
entries = entries.lower()
while entries == "y":
name = input('Enter a students name: ')
grade = input('Enter the student\'s grade: ')
#Put in dictionary
student_grades[name] = grade
#Print
print(student_grades)
entries = input('Would you like to enter a students name and grade? (Y/N)')
entries = entries.lower()
else:
names = list(student_grades.keys())
grades = list(student_grades.values())
print()
print(' Grade Book ')
print('--------------------')
print(student_grades)
for student,grade in student_grades.iteritems():
print "Name:%s, Grade:%s"%(student,grade)
This is the Final Working code for anyone who may need it in the future! Thanks to all who helped!
student_grades = {}
entries = input('Would you like to enter a students name and grade? (Y/N): ')
entries = entries.lower()
while entries == "y":
name = input('Enter a students name: ')
grade = input('Enter the student\'s grade: ')
#Put in dictionary
student_grades[name] = grade
#Print
print(student_grades)
entries = input('Would you like to enter a students name and grade? (Y/N): ')
entries = entries.lower()
else:
names = list(student_grades.keys())
grades = list(student_grades.values())
print()
print(' Grade Book ')
print('--------------------')
print()
for name in student_grades:
print("Name: "+name+" "+"Grade: "+student_grades[name])
If I create a dictionary that I need to access in multiple functions what would be the best way to pass it?
What I currently am doing keeps reseting the dictionary to empty. If I print in the addDictionary() I get the result I want. However, when I go to look up a element using the key in lookUpEntry(), I can't find it. When I print I get an empty dictionary. I also have to eventually pickle and unpickle so if anyone has any feedback on that, that would also help.
import pickle
def dictionary():
addressBook = {}
return addressBook
def addPerson():
personLastName = input("Enter the last name of "
"the person you want to add: ").lower()
personFirstName = input("Please enter the first name of "
"the person you want to add: ")
localPart = input("Please enter the local part of the email address")
while not localPart.isalnum():
localPart = input("Please enter a valid input, a-z and numbers 0-9: ")
domain = input("Please enter the domain of the email addres: ")
while not domain.isalnum():
domain = input("Please enter a valid input, a-z and numbers 0-9: ")
topLevelDomain = input("Please enter the top level domain, examples: com, net, org: ")
while not topLevelDomain.isalnum() or len(topLevelDomain) > 3:
topLevelDomain = input("Please enter only letters, a-z and not more then 3 characters: ")
personEmail = localPart + "#" + domain + "." + topLevelDomain
personStreetAddress = input("Please enter house number and street of the person you want to add: ")
personCityState = input("Please enter the city, state abbreviation and zipcode of the person you want to add: ")
personPhone = input("Please enter the phone number of the person you want to add: ")
personPhoneStr = personPhone.strip("-")
while not personPhoneStr.isdigit() and not len(personPhoneStr) == 10:
personPhone = input("Error. That is not a valid phone number. Try again: ")
personPhoneStr = personPhone.strip("-")
return personLastName, personFirstName, personEmail, personStreetAddress, personCityState, personPhone
def addDictionary():
addressBook = dictionary()
personLastName, personFirstName, personEmail, personStreetAddress, personCityState, personPhone = addPerson()
addressBook[personLastName] = personFirstName, personEmail, personStreetAddress, personCityState, personPhone
print(personFirstName,personLastName, "has been added to the address book!")
print(addressBook)
return addressBook
def lookUpEntry():
addressBook = dictionary()
keyName = input("Enter the last name of the person you are trying to find.")
while not keyName in addressBook:
keyName = input("That name is not in the address book. Please try again.").lower()
x = input("Enter '1' if you want to look up a email. Enter '2' if you want to look "
"up a persons address. Enter '3' to look up a persons phone number: ")
if x == "1":
print("The email of", addressBook[keyName[0]], keyName, "is:", addressBook[keyName[1]])
elif x == "2":
print("The address of", addressBook[keyName[0]], keyName, "is:", addressBook[keyName[2]], addressBook[keyName[3]])
elif x == "3":
print("The phone number of", addressBook[keyName[0]], keyName, "is:", addressBook[keyName[4]])
else:
print("Sorry that item is not stored in this address book.")
def main():
addDictionary()
lookUpEntry()
main()
Currently you define dictionary as
def dictionary():
addressBook = {}
return addressBook
Here you create a new dictionary every time it is called. Try replacing this with
# a global dictionary
_addressBook = {}
def dictionary():
return _addressBook