Running different functions based on the user's input - python

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())

Related

An attribute error appeared when I tried to make a code allowing a user to create their own record

I am trying to allow a user to create their own record and output their record. When I run my code this message appears:
File "filename", line 25, in
record = user_class(fact_list)
File "filename", line 17, in init
self.feild_list[i]=feild_list[i]
AttributeError: 'user_class' object has no attribute 'feild_list'
This is my code:
user_list = []
choice=input("Enter choice (Y/N):")
if choice == "Y":
feild_list = []
record_length = int(input("Enter record length:"))
for i in range(record_length):
feild = input("Enter a feild:")
feild_list.append(feild)
class user_class():
def __init__(self, feild_list):
for i in range(record_length):
self.feild_list[i]=feild_list[i]
fact_list = []
for i in range(len(feild_list)):
fact = input("Enter a fact:")
fact_list.append(fact)
record = user_class(fact_list)
user_list.append(record)
print(user_list)
choice=input("Enter choice (Y/N):")
elif choice == "N":
print("Program Ended.")
else:
while choice != "Y" or choice != "N":
print("Invalid choice")
choice = input("Enter choice (Y/N):")
In user_class.__init__() you don't have a self.feild_list variable. I assume you want one (see below). Alternatively you could just clone the list self.feild_list = feild_list[:].
user_list = []
choice = input("Enter choice (Y/N):")
if choice == "Y":
feild_list = []
record_length = int(input("Enter record length:"))
for i in range(record_length):
feild = input("Enter a feild:")
feild_list.append(feild)
class user_class():
def __init__(self, feild_list):
self.feild_list = []
for i in range(record_length):
self.feild_list.append(feild_list[i])
fact_list = []
for i in range(len(feild_list)):
fact = input("Enter a fact:")
fact_list.append(fact)
record = user_class(fact_list)
user_list.append(record)
print(user_list)
choice = input("Enter choice (Y/N):")
elif choice == "N":
print("Program Ended.")
else:
while choice != "Y" and choice != "N":
print("Invalid choice")
choice = input("Enter choice (Y/N):")
Also fixed the logic error in the choice retry. Consider moving that retry logic to the start so always get a valid choice:
while True:
choice = input("Enter choice (Y/N):")
if choice in "NY":
break
print("Invalid choice")

I am getting an error when using update statement of mysql using python (mysql.connector module)

I have made two functions to update any value of a student's record. When I'm updating the rollno, class or any of the marks, the programme works great but every time I try to update the name it gives the following error:
1054 (42S22): Unknown column 'colum_name' in 'field list'
Both of the functions are perfectly correct I think because everything except name updates fine.
The two functions are:
def update(_class, _rollno):
"""
Takes in the class and roll non as arguments
and updates the details of a single student.
"""
print(
"\n-----Enter what you want to update-----\n"
"\n1) Class"
"\n2) Roll no."
"\n3) Name"
"\n4) Maths Marks"
"\n5) Physics Marks"
"\n6) Chemistry Marks"
"\n7) English Marks"
"\n8) Computer science Marks"
"\n9) Exit the update section"
)
choice = input('\nEnter your choice - ')
if not choice.isnumeric():
print("\nPlz check your input and try again.....")
update(_class, _rollno)
elif int(choice) == 1:
nclass = input("Enter the new class of the student = ")
_update(nclass, "class", _class, _rollno)
update(nclass, _rollno)
elif int(choice) == 2:
nrollno = input("Enter the new rollno of the student = ")
_update(nrollno, "roll_no", _class, _rollno)
update(_class, nrollno)
elif int(choice) == 3:
nname = input("Enter the new name of the student = ")
_update(nname, "student_name", _class, _rollno)
update(_class, _rollno)
elif int(choice) == 4:
nmaths = input("Enter the new math marks of the student = ")
_update(nmaths, "math_marks", _class, _rollno)
update(_class, _rollno)
elif int(choice) == 5:
nphy = input("Enter the new phy marks of the student = ")
_update(nphy, "phy_marks", _class, _rollno)
update(_class, _rollno)
elif int(choice) == 6:
nchem = input("Enter the new chem marks of the student = ")
_update(nchem, "chem_marks", _class, _rollno)
update(_class, _rollno)
elif int(choice) == 7:
neng = input("Enter the new eng marks of the student = ")
_update(neng, "eng_marks", _class, _rollno)
update(_class, _rollno)
elif int(choice) == 8:
ncs = input("Enter the new cs marks of the student = ")
_update(ncs, "comp_marks", _class, _rollno)
update(_class, _rollno)
elif int(choice) == 9:
start()
def _update(new, value, _class, _rollno):
"""
Takes in the updated value, name of value, class
and roll no. of the students and updates the value.
"""
flag = 0
try:
qry = "update students set " + value + " = " + new + \
" WHERE class = " + _class + " and roll_no = " + _rollno
execute(qry)
mydb.commit()
if cursor.rowcount == 1:
print("\nData updated successfully.")
else:
print("\nValue not found. Please check if this is present in database.")
except Exception as e:
print("\n",e)
flag = 1
if flag != 0:
print("\nOops!!! Something went wrong. "
"Please check your input data and try again.")
You can find the entire code here:
https://github.com/Hrshl-Gunjal/Class_12_Python_Mysql_CBSE_Project
Can anyone please help me in finding the solution to this problem ???

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

tkinter GUI quiz that uses buttons for answers

I am writing a quiz in python tkinter and when the user click on the answers if the answer is wrong the correct answer text color is changed to green I got that working but when I add the disable function so the user can't answer the question again it's not showing the correct answer in green.
def check(self, guess):
#compares the guess to the correct answer
print ("guess " + guess)
correct = self.problems[self.counter].correct
print ("correct " + correct)
self.btnA.config(state='disabled')
self.btnB.config(state='disabled')
self.btnC.config(state='disabled')
self.btnD.config(state='disabled')
if guess == correct:
#update ans
if guess == "A":
self.astatus["text"] = "✓"
elif guess == "B":
self.bstatus["text"] = "✓"
elif guess == "C":
self.cstatus["text"] = "✓"
else:
self.dstatus["text"] = "✓"
self.marks+=10
else:
if guess == "A":
self.astatus["text"] = "x"
elif guess == "B":
self.bstatus["text"] = "x"
elif guess == "C":
self.cstatus["text"] = "x"
else:
self.dstatus["text"] = "x"
if correct == "A":
self.btnA["fg"] = 'green'
elif correct == "B":
self.btnB["fg"] = 'green'
elif correct == "C":
self.btnC["fg"] = 'green'
else:
self.btnD["fg"] = 'green'

How to flatten nested IF statements which all contain strings?

I'm making a Choose Your Own Text Adventure game which, so far, contains far too much nesting. Example code is below = mine's in the same format, just with far more nesting - sometimes approaching 10 layers deep.
My question is: Any way to flatten it? The strings mean I need every IF statement to print something every time it's valid, so I can't just use 'AND' like this:
if A and B:
do something
elif C and D:
do something else
I've thought of putting the parts that repeat in their own functions, but then that won't improve readability in this case - at least, not that I can figure out.
Help?
print "First String"
choice = raw_input("Choose A or B")
if choice == "A":
print "You Chose A"
choice = raw_input("Choose C or D")
if choice == "C":
print "You Chose C"
choice = raw_input("Choose E or F")
if choice == "E" or choice == "F":
print "END"
elif choice == "D":
print "You Chose D"
choice = raw_input("Choose G or H")
if choice == "G" or choice == "H":
print "END"
elif choice == "B":
print "You Chose B"
choice = raw_input("Choose I or J")
if choice == "I":
print "You Chose I"
choice = raw_input("Choose C or D")
if choice == "C":
print "You Chose C"
choice = raw_input("Choose E or F")
if choice == "E" or choice == "F":
print "END"
elif choice == "D":
print "You Chose D"
choice = raw_input("Choose G or H")
if choice == "G":
print "END"
elif choice == "H":
print "You Chose H"
choice = raw_input("Choose K or L")
if choice == "K" or choice == "L":
print "END"
If the mappings are straightforward, like , lets say , if I chose A first, i can chose C or D , also if I chose B first I can chose C or E. Now when in C , irrespective of whether the first choice was A or B, the choices you get are same. Then you can use recursion along with a dictionary like -
dict = {'-1':['A','B'], 'A' : ['C','D'] , 'B':['I','J'], 'C':['E','F'] ..}
Then a recursive function like -
def choose(previousChoice, num):
print str(num) + " String"
choice = raw_input("Choose " + ' or '.join(dict[previousChoice]) + " :")
if dict.get(choice) != None and len(dict.get(choice)) > 0:
choose(choice, num + 1)
In the above example you start with -
choose('-1',1)

Categories

Resources