How to compact python code? - python

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!")

Related

why am i getting Local variable 'employee' value is not used " for employee on line 7?

lstEmployees = []
lstNames = []
counter = 0
def export_employee():
for employee in lstEmployees:
with open("file.txt", "w") as output:
output.write(str(lstEmployees))
def search_uen():
uen = input("Enter employee UEN: ")
for employee in lstEmployees:
if uen == employee[1]:
print("-----------------" + employee[0] + "------------------------")
print("UEN: " + employee[1])
print("Phone: " + employee[2])
print("Email: " + employee[3])
print("Salary: £" + employee[4])
return employee
return -1
def edit_employee():
search = search_uen()
if search == -1:
print("Employee not found...")
else:
name = input("Enter the new name of the employee: ")
uen = input("Enter the new UEN of the employee: ")
phone = input("Enter the Phone number of the employee: ")
email = input("Enter the email of the employee: ")
salary = input("Enter the salary of the employee: ")
search[0] = name
search[1] = uen
search[2] = phone
search[3] = email
search[4] = salary
def add_employee():
global counter
while counter < 5:
print("----------------------------------------------------------\n")
print(" Number of employee ({0:d})" .format(counter))
print("----------------------------------------------------------\n")
name = input("enter employee name: ")
lstNames.insert(counter, name)
uen = input("enter employee UEN: ")
phone = input("enter employee phone number: ")
email = input("enter employee email: ")
salary = input("enter employee salary: ")
lstEmployees.append([name, uen, phone, email, salary])
if counter > 5:
break
else:
continue
def print_employee():
for employee in lstEmployees:
print("-----------------" + employee[0] + "------------------------")
print("UEN: " + employee[1])
print("Phone: " + employee[2])
print("Email: " + employee[3])
print("Salary: £" + employee[4])
def menu():
while True:
print('-------------------------------------------\n')
print('Welcome to the Employee Management System -\n')
print('-------------------------------------------\n')
print('[1] Add An Employee: \n')
print('[2] View All Employees: \n')
print('[3] Search Employees By UEN: \n')
print('[4] Edit Employees Information: \n')
print('[5] Export Employee Records: \n')
user_option = input("Please select an option ")
if user_option == "1":
add_employee()
elif user_option == "2":
print('\n' * 3)
print_employee()
print('\n' * 3)
elif user_option == "3":
found = search_uen()
if found == -1:
print("Employee not found...")
elif user_option == "4":
edit_employee()
elif user_option == "5":
export_employee()
else:
print("Please select valid option...")
if __name__ == "__main__":
menu()
i have no idea what to do here, on line its saying that the variable 'employee' is not used and i dont know why and when i switch the code to make the add_employee function look like this: (see image)code line 7 change
when i run the code i cant add employees and the string will always say 0 even after i have add details in.
other info: im using both latest version of pycharm and python sdk.
You're calling the main() function but there's no main function defined. I think you want to use menu().
Your if __name__ block should look like this:
if __name__ == "__main__":
menu()
Your export_employee function never uses the employee variable in the loop. Every time you just write out the entire list of employees. Below, we open the file before we iterate over the list.
def export_employee():
with open("file.txt", "w") as output:
for employee in lstEmployees:
output.write(str(employee))

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:

Running different functions based on the user's input

I am new to Pycharm, and Python as a whole, and for my first project I decided to do a random name/object selector which chooses a name from a pre-made variable of letters and prints that result.
I wanted to expand on this and have the user either use the default names in the code or add their own names to be used.
I gave it my best effort but when it came to the script running 1 of two functions I was unable to figure out how to do that.
Any help?
import string
import random
import os
letters = 'wjsdc' #*Default letters*
choice = random.choice(letters)
decision = input("Hello, use default? y/n")
print("You have chosen " + decision + ", Running function.")
def generator():
if decision == "y": #*Default function*
choice = random.choice(letters)
print("Name chosen is " + generator())
elif decision == "n": #*Attempted new function*
new_name1 = input("Please add a name")
new_name2 = input("Please add a name")
new_name3 = input("Please add a name")
new_name4 = input("Please add a name")
new_name5 = input("Please add a name")
if choice == "w":
finalname = new_name1
elif choice == "j":
finalname = new_name2
elif choice == "s":
finalname = new_name3
elif choice == "c":
finalname = new_name4
elif choice == "d":
finalname = new_name5
name = finalname
return name
print("Name chosen is " + name)
def generator(): #*Default function script*
if choice == "w":
finalname = "Wade"
elif choice == "j":
finalname = "Jack"
elif choice == "s":
finalname = "Scott"
elif choice == "d":
finalname = "Dan"
elif choice == "c":
finalname = "Conall"
name = finalname
return name
print("Name chosen is " + generator())
Your code is pretty weird, and I'm not sure what you are trying to achieve.
you define two functions generator; you should give them different names
instead of chosing from one of the letters and then selecting the "long" name accordingly, just chose from the list of names in the first place
you can use a list for the different user-inputted names
I'd suggest using something like this:
import random
def generate_name():
names = "Wade", "Jack", "Scott", "Dan", "Conall"
decision = input("Use default names? Y/n ")
if decision == "n":
print("Please enter 5 names")
names = [input() for _ in range(5)]
return random.choice(names)
print("Name chosen is " + generate_name())

Variable not defined when file updating

I am currently learning Python and I am making a tennis coach program. On the option 3 where you can update it is not working as it says nameUnder is not defined in the else statement. Please help as I really don't understand why its not working. I have also tries it without the split but that to doesn't work
import os, sys
print("Please select an option:")
print("[1] Add a student")
print("[2] Read a students data")
print("[3] Update a students data")
print("[4] Delete a students data")
menuSelect = int(input("Make your number selection: "))
#/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if menuSelect == 1:
amountDone=0
amounttodo=int(input("Enter the number of contestants you would like to add: "))
while amounttodo>amountDone:
ageOne=int(input("Enter the age of the contestant: "))
if ageOne <= 11:
underFile=open("Under11s.txt","a")
nameUnder=input("Enter the first name of the student: ")
genderUnder=input("Enter the gender of the student: ")
posUnder=int(input("Input the last position of the student: "))
underFile.write("\n"+str(nameUnder) + " | " + str(genderUnder) + " | " + str(posUnder))
underFile.close()
amountDone=amountDone+1
elif ageOne >= 12:
overFile=open("Over11s.txt","a")
nameOver=input("Enter the first name of the student: ")
genderOver=input("Enter the gender of the student: ")
posOver=int(input("Input the last position of the student: "))
overFile.write("\n"+str(nameOver) + " | " + str(genderOver) + " | " + str(posOver))
overFile.close()
amountDone=amountDone+1
else:
print("Invalid, Please enter a number")
#/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
elif menuSelect == 2:
print("Enter the file you would like to open.")
print("1) Under 11's")
print("2) Over 11's")
fileToOpen=int(input("Enter the number of your selection: "))
if fileToOpen == 1:
f = open("Under11s.txt", "r")
file_contents = f.read()
print(file_contents)
elif fileToOpen == 2:
f = open("Over11s.txt", "r")
file_contents = f.read()
print(file_contents)
#/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
elif menuSelect == 3:
studentName = input("Enter the student name you are looking for:")
file = open("Under11s.txt","r")
found=False
for line in file:
details = line.split(",")
writefile = open("Under11supdated.txt","a")
details = line.split(",")
if details[0] == studentName:
found=True
nameUnder=input("Enter the first name of the student: ")
genderUnder=input("Enter the gender of the student: ")
posUnder=int(input("Input the last position of the student: "))
file.write("\n"+str(nameUnder)[0] + " | " + str(genderUnder)[1] + " | " + str(posUnder)[2])
else:
file.write("\n"+nameUnder[0] + " | " + genderUnder[1] + " | " + posUnder[2])
file.close()
file.close()
os.remove("Under11s.txt")
os.rename("Under11supdated.txt","Under11s.txt")
if found==True:
print("Details updated")
else:
print("That student cannot be found in the file, no changes made")
#/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
else:
print("Sorry, this option is not available yet!")
#/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
nameUnder only gets defined if this statement is true if details[0] == studentName:
Not a 100% of your logic here, but make sure to set nameUnder= "" before the if statement so the variable is declared and can be used in your else clause.
I would recommend you to structure your code with functions for the each options etc., will make it easier to read and possible reuse some of the code.
Partly updated code:
writefile = open("Under11supdated.txt","a")
details = line.split(",")
nameUnder = ""
if details[0] == studentName:
found=True
nameUnder=input("Enter the first name of the student: ")
genderUnder=input("Enter the gender of the student: ")

Edit list of entries using 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.

Categories

Resources