Edit list of entries using Python - python

My script so far:
#DogReg v1.0
import time
Students = ['Mary', 'Matthew', 'Mark', 'Lianne' 'Spencer'
'John', 'Logan', 'Sam', 'Judy', 'Jc', 'Aj' ]
print("1. Add Student")
print("2. Delete Student")
print("3. Edit Student")
print("4. Show All Students")
useMenu = input("What shall you do? ")
if(useMenu != "1" and useMenu != "2" and useMenu != "3" and useMenu != "4"):
print("Invalid request please choose 1, 2, 3, or 4.")
elif(useMenu == "1"):
newName = input("What is the students name? ")
Students.append(newName)
time.sleep(1)
print(str(newName) + " added.")
time.sleep(1)
print(Students)
elif(useMenu == "2"):
remStudent = input("What student would you like to remove? ")
Students.remove(remStudent)
time.sleep(1)
print(str(remStudent) + " has been removed.")
time.sleep(1)
print(Students)
elif(useMenu == "3"):
So I'm trying to be able to let the user input a name they want to edit and change it.
I tried looking up the function for editing list entries and I haven't found one I'm looking for.

How about this?
elif(useMenu == "3"):
oldName = input("What student would you like to edit? ")
if oldName in Students:
index = Students.index(oldName)
newName = input("What is the student's new name? ")
Students[index] = newName
time.sleep(1)
print(str(oldName) + " has been edited to " + str(newName))
time.sleep(1)
else:
print('Student' + oldName + 'not found!')
print(Students)
with output:
1. Add Student
2. Delete Student
3. Edit Student
4. Show All Students
What shall you do? '3'
What student would you like to edit? 'Mary'
What is the student's new name? 'Marry'
Mary has been edited to Marry
['Marry', 'Matthew', 'Mark', 'LianneSpencerJohn', 'Logan', 'Sam', 'Judy', 'Jc', 'Aj']

Suppose the user wants to change 'Mary' to 'Maria':
student_old = 'Mary'
student_new = 'Maria'
change_index = Students.index(student_old)
Students[change_index] = student_new
Note that you will have to add proper error handling - for example, if the user asks for modifying 'Xavier' who is not in your list, you will get a ValueError.

Related

If statement not working as intended (Python)

This code I wrote for my study on if statements in Python doesn't seem to work properly since it asks the same question twice after the first one being asked.
Identity = input("Who are you? ")
if Identity == "Jane":
print("You must be John's sister.")
elif Identity != "John":
print("My database doesn't recognise you. Who are you I wonder...")
elif Identity == "John":
if input("What is your last name? ") != "Travolta":
print("False! John's name is Travolta and not " + input("What is your last name? ") + ".")
elif input("How old are you? ") == "Travolta":
if input("How old are you? ") != "20 yo":
print("False! John is 20 yo and not " + input("How old are you? ") + ".")
elif input("How old are you? ") == "20 yo":
print("You must in fact be John!")
if input("What is your last name? ") != "Travolta":
print("False! John's name is Travolta and not " + input("What is your last name? ") + ".")
Here you aren't storing the value of the input and printing it. You are asking the person to input again "what is your last name?".
Do something like
last_name = input("What is your last name? ")
and use it instead of the input() in the if statement.
Here I am putting the snippet in the way I would've done it.
identity = input("Who are you? ")
if identity == "Jane":
print("You must be John's sister.")
elif identity != "John":
print("My database doesn't recognise you. Who are you I wonder...")
elif identity == "John":
last_name = input("What is your last name? ")
if last_name != "Travolta":
print("False! John's last name is Travolta and not " + last_name + ".")
else:
age = input("How old are you? ")
if age != "20 yo":
print("False! John is 20 yo and not " + age + ".")
else:
print("You must in fact be John!")
It is working properly for every possibility. Examples:

I can't let the data to remain in the dictionary, it keeps updating instead

I got myself a python book. Currently, in the book, I am learning about dictionaries. The book gave me an exercise about dictionaries. This is the question.
"Create a program that pairs student's name to his class grade. The user should be able to enter as many students as needed and then get a printout of all students' names and grades. The output should look like this:
Please give me the name of the student (q to quit): [input]
Please give me their grade: [input]
[And so on...]
Please give me the name of the student (q to quit): [input]: q
Okay, printing grades!
Student Grade
Student1 A
Student2 B
[And so on...] "
def student():
studentmarks = {}
while True:
name = raw_input("Please give me the name of the student ('q' to quit):")
if name == "q":
break
elif name.isalpha() == True:
grade = raw_input("Please give me their grade ('q' to quit):")
if grade == "q":
break
elif grade.isalpha() == True:
print "Grade is a number! Please try again"
continue
elif grade.isdigit() == True:
studentmarks = {name: grade}
else:
print "Error, please try again"
continue
else:
print "Please try again. {} is not the right input".format(name)
continue
print studentmarks
continue
student()
I modified the code a bit to test the dictionary. I also use python 2
you made only one mistake witch is when you append the data to dictionary:
studentmarks = {name: grade}
it should be like this :
studentmarks[name] = grade
You're overwriting the dictionary every time you get to this line:
studentmarks = {name: grade}
It should be like this:
studentmarks[name] = grade

How to remove the parenthesis and a comma in the output

I am writing a program in python for a banking application using arrays and functions. Here's my code:
NamesArray=[]
AccountNumbersArray=[]
BalanceArray=[]
def PopulateAccounts():
for position in range(5):
name = input("Please enter a name: ")
account = input("Please enter an account number: ")
balance = input("Please enter a balance: ")
NamesArray.append(name)
AccountNumbersArray.append(account)
BalanceArray.append(balance)
def SearchAccounts():
accounttosearch = input("Please enter the account number to search: ")
for position in range(5):
if (accounttosearch==AccountNumbersArray[position]):
print("Name is: " +NamesArray[position])
print(NamesArray[position],"account has the balance of: ",(BalanceArray[position]))
break
if position>4:
print("The account number not found!")
while True:
print("**** MENU OPTIONS ****")
print("Type P to populate accounts")
print("Type S to search for account")
print("Type E to exit")
choice = input("Please enter your choice: ")
if (choice=="P"):
PopulateAccounts()
elif (choice=="S"):
SearchAccounts()
elif (choice=="E"):
print("Thank you for using the program.")
print("Bye")
break
else:
print("Invalid choice. Please try again!")
Everything is fine now, but when I run the program and search for an account. For example, when I search an account the output shows ('name', 'account has the balance of: ', 312) instead of name account has the balance of: 312 How do I fix this?
In the line
print(NamesArray[position],"account has the balance of: ",(BalanceArray[position]))
you should use string concatenation to add the different strings. One way to do this would be like this:
print(NamesArray[position] + " account has the balance of: " + str(BalanceArray[position]))
u are using old python version,
replace your line with this :
print(NamesArray[position] + "account has the balance of: " + (BalanceArray[position]))
use ' + ' instead of comma

How to compact python code?

so I'm trying to make this search function that shows the person's horoscope when name is entered. I did it the manual way with 4 names, and I know there's a way to compact the code with the dictionary that I have(but not using), but I can't remember.
Horoscopes = {
"A": "Scorpio",
"B": "Gemini",
"J": "Sagittarius",
"P": "Gemini",
}
def horoscope(name):
if name == "A" or name == "a":
print ("Hello " + name + ", you are a Scorpio!")
print("Welcome to the Horoscope Search!")
name = input("What is your name? ")
horoscope(name)
elif name == "B" or name == "b":
print ("Hello " + name + ", you are a Gemini!")
print("Welcome to the Horoscope Search!")
name = input("What is your name? ")
horoscope(name)
elif name == "J" or name == "j":
print ("Hello " + name + ", you are a Sagittarius!")
print("Welcome to the Horoscope Search!")
name = input("What is your name? ")
horoscope(name)
elif name == "P" or name == "p":
print ("Hello " + name + ", you are a Gemini!")
print("Welcome to the Horoscope Search!")
name = input("What is your name? ")
horoscope(name)
else:
print ("Sorry " + name + ", you are not registered in our
system!")
print("Welcome to the Horoscope Search!")
name = input("What is your name? ")
horoscope(name)
print("Welcome to the Horoscope Search!")
name = input("What is your name? ")
horoscope(name)
You should define your dictionary with keys starting from small letter, so you can parse all answers to lower letters and compare it this way:
Horoscopes = {
"a": "Scorpio",
"b": "Gemini",
"j": "Sagittarius",
"p": "Gemini",
}
def horoscope(name):
if name.lower() in Horoscopes:
print("Hello " + name + " you are a " + Horoscopes[name.lower()] + "!")
else:
print("Sorry " + name + ", you are not registered in our system!")
This can be achieved with something like so:
horoscopes = {
"Angelina": "Scorpio",
"Bernice": "Gemini",
"Jessica": "Sagittarius",
"Peniel": "Gemini",
}
print("Welcome to the Horoscope Search!")
name = input("What is your name? ")
if name in horoscopes: # If name is a key in horoscopes dict
print("Your Horoscope is {}!".format(horoscopes[name]))
Please note this is a case sensitive check for a given name in horoscopes, i.e. if a name is input as 'angelina', it will not match to the dictionary key 'Angelina'. To account for this, if dictionary keys were known to be in lower case, one might use the string method .lower():
name = input("What is your name? ").lower()
This way no matter how the name is entered, there will still be a match.
If you wanted the user to be prompted until a valid name was entered, then:
horoscopes = {
"angelina": "Scorpio",
"bernice": "Gemini",
"jessica": "Sagittarius",
"peniel": "Gemini",
}
print("Welcome to the Horoscope Search!")
while True: # Until a name is matched to horoscopes
name = input("What is your name? ").lower()
if name in horoscopes: # If name is a key in horoscopes dict
print("Your Horoscope is {}!".format(horoscopes[name]))
break # A valid name has been entered, break from loop
else:
print("Please enter a valid name!")

How do I use getattr and setattr properly in Python? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I created a class in Python called Student. I need to create five instances of the class, and then be able to return an attribute from an instance of the user's choice, as well as set an attribute to a new value. Here is my code:
class Student:
# Initializer for Student Class
def __init__(self):
self.name = str(input("What is the name of the student? "))
self.id_number = int(input("What is the i.d. number of " + self.name + "? "))
self.gpa = float(input("What is " + self.name + "'s GPA? "))
self.expected_grade = int(input("What is the expected grade of " + self.name + "? "))
self.work_status = str(input("Does " + self.name + " work full-time or part-time? "))
menu = str("1. Look up and print the student GPA." + '\n' +
"2. Add a new student to the class." + '\n' +
"3. Change the GPA of a student." + '\n' +
"4. Change the expected grade of a student." + '\n' +
"5. Print the data of all the students in a tabular format." + '\n' +
"6. Quit the program. ")
# Student list
student_list = []
# Print a list of the instances of Student in alphabetical order
def display_students(self):
Student.student_list.sort()
print("")
for n in Student.student_list:
print(n)
print("")
# Print tabulated format of all instances of Student and attributes
def display_student_info(self):
Student.student_list.sort()
print("Name\tI.D. #\t\tGPA\t\tExpected Grade\t\tEmployment")
print("----------------------------------------------------------")
for name in Student.student_list:
print(name, '\t', getattr(name, "id_number"),
'\t', getattr(name, "gpa"), '\t', getattr(name, "expected_grade"), '\t', getattr(name, "work_status"))
# Menu selection for user
def menu_selection(self):
valid_input = False
user_input = int(input())
while valid_input == False:
try:
if int(user_input) not in range(1, 6):
raise ValueError
else:
valid_input = True
except ValueError:
print("You have entered an invalid selection for the menu. Please enter a number from 1 to 6. ")
user_input = int(input(str()))
# Look up and print student GPA
if user_input == 1:
Student.display_students(self)
name = str(input("Which student would you like to look up the GPA for? "))
print(name + ": " + getattr(Student.name, "gpa"))
# Add a new student to the class
if user_input == 2:
print("")
print("Okay. Let's add a new student to the class. ")
Student.__init__(self)
Student.student_list.append(Student.name)
# Change the GPA of a student
if user_input == 3:
print("")
print("Okay. Let's change the GPA of a student in the class.")
self.display_students(Student)
name = str(input("Which student's GPA would you like to change? "))
new_gpa = str(input("What would you like " + name + "'s new GPA to be? "))
setattr(Student.name, Student.gpa, new_gpa)
# Change the expected grade of a student
if user_input == 4:
print("")
print("Okay. Let's change the expected grade of a student.")
print("Which student's expected grade would you like to change? ")
self.display_students()
name = str(input("Which student's expected grade would you like to change? "))
new_expected_grade = float(input("What would you like " + name + "'s new expected grade to be? "))
setattr(Student, str(Student.expected_grade), new_expected_grade)
# Print the data of all the students in a tabular format
if user_input == 5:
print("")
print("Okay, here is all the data for the currently entered students: ", '\n')
Student.display_student_info(self)
# Quit the program
if user_input == 6:
print("")
print("Okay. Now quitting the program.")
quit()
def main():
count = 0
while count < 5:
Student.__init__(Student)
Student.student_list.append(Student.name)
print("")
count += 1
print("Now that the students information has been entered, you can select from the menu below to alter student data or quit the program."
+ '\n' + "Please make a selection: " + '\n')
print(Student.menu)
Student.menu_selection(Student)
main()
I can not get my getattr or setattr methods working. How can I get them working?
The second argument to getattr and setattr are strings that name the attribute you want. That is, getattr(name, "expected_grade"). Using a variable as the second argument means that the value of the variable is used as the name. Generally, though, there is no real difference between name.expected_grade and getattr(name, 'expected_grade'), although you can supply getattr an optional third argument that is returned (instead of raising an AttributeError) if the named attribute does not exist.
There is nothing in your code to indicate that you need getattr or setattr; just use the dotted name syntax to access the attributes.

Categories

Resources