How to choose between input in Python 3.2 - python

input("Would you like to read: comedy, political, philisophical, or tragedy?")
a = "comedy"
b = "political"
c = "philisophical"
d = "tragedy"
if a:
input("Would you like the author's nationality to be: English or French?")
e = "French"
d = "English"
if e:
print("Tartuffe")
elif d:
print("Taming of the Shrew")
When I run the program is just defaults to comedy and then to Tartuffe.
How do I get it to recognize the difference genres in the string?

you need to store the input and then compare it to what you want, for example:
a = "comedy"
b = "political"
c = "philisophical"
d = "tragedy"
user_input = input("Would you like to read: comedy, political, philisophical, or tragedy?")
if user_input == a:
user_input = input("Would you like the author's nationality to be: English or French?")
if user_input == e:
#do more stuff
A better way to do this (in my opinion) would be to do something like:
def comedy():
print("comedy")
def political():
print("political")
def philisophical():
print("philisophical")
def tragedy():
print("tragedy")
types = {"comedy":comedy,
"political":political,
"philisophical":philisophical,
"tragedy":tragedy
}
user_input = input()
types[user_input]()
because its easier to manage and read the different inputs.

You are just testing if the value of e is true (the string is not null, hence it is true).
You are not storing the input either.
selection = input("Would you like the author's nationality to be: English or French? ")
if selection == e:
print("Tartuffe")
elif selection == d:
print("Taming of the Shrew")

Highly extensible code.
choices = {'e': ('French', 'Tartuffe'), 'd': ('English', 'Taming of the Shrew')}
cstr = ', '.join('%r = %s' % (k, choices[k][0]) for k in sorted(choices))
prompt = 'What would you like the author\'s nationality to be (%s): ' % cstr
i = input(prompt).lower()
print('%s: %s' % choices.get(i, ('Unknown', 'Untitled')))

Related

Print output for data list python

I am trying to print an output but I just can't figure out method.
keepAsking = True
author = ""
booktitle = ""
purchaseprice = float()
sellprice = float()
stockcount = int()
margin = float()
bookList = []
priceList = []
while keepAsking == True :
print("Enter Book Data: -")
author = input("Author: ")
if author == "" :
print("Blank Entry")
else :
booktitle = input("Title: ")
if booktitle == "" :
print("Blank Entry")
else :
purchaseprice = input("Purchase Price: ")
if purchaseprice == "" :
print("Incorrect Value")
else :
sellprice = input("Sell Price: ")
if sellprice == "" :
print("Incorrect Value")
else :
bookList.append(author)
bookList.append(booktitle)
if purchaseprice > sellprice :
bookList.remove(author)
bookList.remove(booktitle)
else :
priceList.append(purchaseprice)
priceList.append(sellprice)
stockcount = input("In Stock: ")
if stockcount == "" :
print("Incorrect Value")
else :
priceList.append(stockcount)
margin = ((float(sellprice)-float(purchaseprice))/float(purchaseprice))*100
marginround = round(margin,2)
priceList.append(marginround)
checkContinue = True
while checkContinue == True :
continues = input("Continue? [y/n]")
continuesLower = continues.lower()
if continues == "y" :
checkContinue = False
if continues == "n" :
checkContinue = False
keepAsking = False
and I am trying to get an output like this:
output
I don't really understand array and I have tried a few methods but failed to output it as the image shows. If possible, I would need some explanation too because I want to learn rather than get the answer straight out. So, if you have a solution, I might ask for more information on it too. (you don't have to explain it if you are not comfortable, but I just wish to learn more)
Thank you for attempting to help me. I am sorry if this is just a simple task but I am less than a beginner and trying to improve myself.
I am currently not outputting anything enter image description here
my print code is
for a in bookList :
counter = 0
while counter == len(bookList) :
print(bookList[0] + bookList[1])
print("Purchase Price: " + priceList[0] + "Sell Price: " + priceList[1] + "In Stock: " + priceList [2] + "Margin: " + priceList [3])
If you want to print multiple Book names and prices, etc you should put each one of them into a separate list in this case. (with append)
If you want to print them out you can do like this:
for i in range(0, len(booklist)):
print(author[i] + ' Purchase:' + purchase[i] + ' Sell:' + sell[0]))
... etc to the right format in wich purchase and sell are all lists. Don't forget to add spaces.
To check if the person actually input numbers you can use the method .isdigit()
if purchaseprice.isdigit() != true :
print("Incorrect Value, input numbers")

Last paragraph of code is running when it does not need to

I am working on a username generator in Python, and everything is going well but one thing: the "IF" statement at the very end of the code is malfunctioning. The first part of the code works, but the last paragraph kicks in, even when I have typed in a supposedly valid choice.
The code:
[import random, tkinter
#variables that make up the name. the "1" symbolises the first part and the "2" symbolises the last part of the username
general1 = \["noob","baby","dude","soldier","discount"\]
general2 = \["kid","plant","painter","officer","conscience"\]
animal1 = \["frantic","fiesty","quick","quiet","loud"\]
animal2 = \["ferret","dog","hampster","cat","rabbit"\]
food1 = \["delicious","disgusting","stinky","fried","bitter"\]
food2 = \["pickle","chocolate","rice","water","lemonade"\]
name1 = \["dylan","eve","chris","simon","adele"\]
name2 = \["christopher","sharp","smith","james","baker"\]
#the main part
category = str(input("**USERNAME GENERATOR**\n\nWhat category do you want?\n1 for general\n2 for animals\n3 for food\n4 for human names\n\n"))
if category == "1":
output1 = random.choice((general1))
output2 = random.choice((general2))
endNumber = random.randint(0, 100)
print("\nYour random username is: ",output1,output2,endNumber)
if category == "2":
output1 = random.choice((animal1))
output2 = random.choice((animal2))
endNumber = random.randint(0, 100)
print("\nYour random username is: ",output1,output2,endNumber)
if category == "3":
output1 = random.choice((food1))
output2 = random.choice((food2))
endNumber = random.randint(0, 100)
print("\nYour random username is: ",output1,output2,endNumber)
if category == "4":
output1 = random.choice((name1))
output2 = random.choice((name2))
endNumber = random.randint(0, 100)
print("\nYour random username is: ",output1,output2,endNumber)
if category != ("1","2","3","4"):
print("\nPlease enter a valid option:")
category = str(input("What category do you want?\n1 for general\n2 for animals\n3 for food\n4 for human names\n\n"))][1]
if category != ("1","2","3","4"):
This only checks if category is equal to the tuple ("1","2","3","4"). You want to check if category is equal to any value of the tuple. Do that by changing that line to this:
if category not in ("1","2","3","4"):
After an if statement ends, the next line is executed.
In your case, the next line is the next if paragraph.
And after that the next one and so on.
e.g.:
if a:
do_action_a()
if b:
do_action_b()
if c:
do_action_c()
if not(a or b or c):
do_action_all_others()
Here you will always execute each paragraph independently of the previous one(s).
To avoid this, you can put each of the following statements in the
else of the previous if statement:
if a:
do_action_a()
else:
if b:
do_action_b()
else:
if c:
do_action_c()
else:
do_action_all_others()
However, there is an idiom for this: elif
so the pythonic is to use:
if a:
do_action_a()
elif b:
do_action_b()
elif c:
do_action_c()
else:
do_action_all_others()
Change the last conditional statement to
if category not in ('1', '2', '3', '4'):
print('\nPlease enter a valid option:')
category = str(input('. . .'))
My Refined Implementation of your code
import random
general_first = ['noob', 'baby', 'dude', 'soldier', 'discount']
general_last = ['kid', 'plant', 'painter', 'officer', 'conscience']
animal_first = ['frantic', 'fiesta', 'quick', 'quiet', 'loud']
animal_last = ['ferret', 'dog', 'hamster', 'cat', 'rabbit']
food_first = ['delicious', 'disgusting', 'stinky', 'fried', 'bitter']
food_last = ['pickle', 'chocolate', 'rice', 'water', 'lemonade']
name_first = ['dylan', 'eve', 'chris', 'simon', 'adele']
name_last = ['christopher', 'sharp', 'smith', 'james', 'baker']
def endNumber(): return str(random.randint(0, 100))
def firstName(values): return random.choice(values)
def lastName(values): return random.choice(values)
def generate_usernames(category):
if category == 1:
return firstName(general_first) + lastName(general_last) + endNumber()
elif category == 2:
return firstName(animal_first) + lastName(animal_last) + endNumber()
elif category == 3:
return firstName(food_first) + lastName(food_last) + endNumber()
elif category == 4:
return firstName(name_first) + lastName(name_last) + endNumber()
else:
return None
input_prompt = "What category do you want?" \
"\n'1' for general" \
"\n'2' for animals" \
"\n'3' for food" \
"\n'4' for human names" \
"\n\nCHOICE : "
invalid_prompt = "\nPlease enter a valid option"
print('\tUSERNAME GENERATOR')
while True:
input_category = int(input(input_prompt))
username = generate_usernames(input_category)
if username is not None:
print(f'Your Random Username is : {username}')
break
else:
print(invalid_prompt)

Cannot use a returned value

New to python, probably a dumb question. It's saying the "addAns" in the last line is undefined. How do I get it to use the value from the add function
def add (addL):
c = 0
while c < 4:
x = input("Type a number to add. " )
c += 1
addL.append(x)
if x == "end":
c += 5
addL.remove("end")
addStep = [int(i) for i in addL]
addAns = sum(addStep)
return addAns
userIn = input("What function would you like to perform? ")
if userIn == 'add':
add(addL)
print(addAns)
You should assign the output of the function:
if userIn == 'add':
addAns = add(addL)
print(addAns)
It doesn't need to be the same name, the scopes are independent:
if userIn == 'add':
output = add(addL)
print(output)
You can also directly use the output in print:
if userIn == 'add':
print(add(addL))

How to get one item and do something specifically in a for loop in Python 3?

This is the code:
ls = ['apple', 'banana', 'pear']
for z in ls:
x = input("Do you like %s ?" %z)
if x == 'yes':
print('Cool, ' + z + ' is very good.')
break
elif x == 'no':
continue
else:
print('I am not sure what you want')
With this code, there are two things i'd like to do:
1 - after it loops by the second time (Do you like banana?) i'd like to print a message. But ONLY after the 'do you like banana' and not on the other times it loops.
So is there a way to print a message only for one of the loops? Because if i try like this:
elif x == 'n':
print('are you sure you do not like it?')
continue
it will print the message for all the 3 items in the list (apple, banana and pear).
2 - The other thing is to set that when the else statement runs (the user inputs something different from 'yes' or 'no') , i'd like it to restart in the beginning of the loop (ask the user again 'Do you like apple?' instead of continue to the second item ('Do you like banana').
Is there a way to set the loop to go back to the beginning?
Hope the questions are clear enough.
Thanks
I think this is what you need:
ls = ['apple', 'banana', 'pear']
i = 0
flag = True
while i<len(ls) :
x = input("Do you like %s ?" %ls[i])
if x == 'yes':
print('Cool, ' + ls[i] + ' is very good.')
flag = True
break
elif x == 'no':
if i >=1 and flag:
print('are you sure you do not like it?')
i = i -1
flag = False
else:
i = -1
flag = True
i+=1
output:
1.
Do you like apple ?no
Do you like banana ?no
are you sure you do not like it?
Do you like banana ?no
Do you like pear ?no
2.
Do you like apple ?yes
Cool, apple is very good.
3.
Do you like apple ?no
Do you like banana ?yes
Cool, banana is very good.
If it's okay for you I did it with enumerate and a flag:
while True:
successful_flag = True
for i, z in enumerate(ls):
x = input("Do you like %s ?" %z)
if x == 'yes':
print('Cool, ' + z + ' is very good.')
elif x == 'no':
if i == 1:
print('Are you sure you do not like it?')
else:
print('I am not sure what you want')
successful_flag = False
break
if successful_flag:
break
Output:
Do you like apple ?yes
Cool, apple is very good.
Do you like banana ?no
Are you sure you do not like it?
Do you like pear ?get out
I am not sure what you want
Do you like apple ?
What is called a "state machine" would describe your problem quite well
Each circle/square in the diagram is a "state." The user's input controls transitions between states
CODE:
class YesNoStateBase:
pass
class ExitState(YesNoStateBase):
def ask_for_instructions(self):
return ""
def ask_for_data(self):
return str(self)
def ask_for_geography(self, *args):
return self
ExitState.ExitState = ExitState
class YesNoState:
def __init__(self, prompt, *, yes=ExitState, no=ExitState):
self._prompt = prompt + " "
self._yes = yes
self._no = no
def set_yes(self, state):
self._yes = state
def ask_for_instructions(self):
return self._prompt
def ask_for_data(self):
return self._data
def ask_for_geography(self, x_stryng):
i_stryng = str(x_stryng).strip().lower()
nxt_state = type(self).ExitState
if i_stryng == "y" or i_stryng == "yes":
self._data = self._prompt + " yes"
nxt_state = self._yes
elif i_stryng == "n" or i_stryng == "no":
self._data = self._prompt + " no"
nxt_state = self._no
else:
nxt_state = YesNoState(
"I don't understand. Please try again\n" + self._prompt,
yes=self._yes,
no=self._no
)
return nxt_state
YesNoState.YesNoState = YesNoState
YesNoState.ExitState = ExitState
class StateMiner:
def __init__(self):
self._data = list()
def go_to_work(self, state):
while True:
# `msg`............`message`
msg = state.ask_for_instructions()
nxt_state = state.ask_for_geography(input(msg))
datum = state.ask_for_data()
self._data.append(datum)
if nxt_state== state.ExitState:
return
state = nxt_state
GoAgainQ = YesNoState("Do you want to play again? ")
PearQ = YesNoState("Do you like pears? ", yes=GoAgainQ, no=GoAgainQ)
SureBananaQ = YesNoState("Are you certain that you do not like bananas (yes = hate bananas)?", yes=PearQ, no=PearQ)
BananaQ = YesNoState("Do you like bananas? ", yes=PearQ, no=SureBananaQ)
AppleQ = YesNoState("Do you like apples? ", yes=BananaQ, no=BananaQ)
GoAgainQ.set_yes(AppleQ )
bob = StateMiner()
bob.go_to_work(AppleQ)
print(40*"#", "RESULTS:", 40*"-", sep="\n")
print("\n".join(bob._data))
print(40*"-", sep="\n")
Example output:
########################################
RESULTS:
----------------------------------------
Do you like apples? yes
Do you like bananas? yes
Do you like pears? yes
Do you want to play again? yes
Do you like apples? yes
Do you like bananas? yes
Do you like pears? yes
Do you want to play again? no
----------------------------------------
Process finished with exit code 0

How to repeat blocks of code in Python

I've created a code that allows a user to view the average score of the values that are in the file. In Example the Text File would look like the following:
Text File For Class 1: it is similar for each text file ; 2 and 3. just different names and values
Matt 2
Sid 4
Jhon 3
Harry 6
There are 3 classes altogether in which the user is prompted to choose which class they want to preview.
Code:
def main_menu():
print ("\n Main Menu ")
print ("1.Average Score of class = 'avg'")
main_menu()
option = input("option [avg]: ")
option_class = input("class: ")
one = "1.txt"
two = "2.txt"
three = "3.txt"
if option.lower() == 'avg' and option_class == '1':
with open(one) as f:
the_list = [int(l.strip().split()[-1]) for l in f]
b = sum(the_list)
length = len(the_list)
avg = float(b) / length if length else 0
print ("Average of Class is: ", avg)
if option.lower() == 'avg' and option_class == '2':
with open(two) as f:
the_list = [int(l.strip().split()[-1]) for l in f]
b = sum(the_list)
length = len(the_list)
avg = float(b) / length if length else 0
print ("Average of Class is: ", avg)
if option.lower() == 'avg' and option_class == '3':
with open(three) as f:
the_list = [int(l.strip().split()[-1]) for l in f]
b = sum(the_list)
length = len(the_list)
avg = float(b) / length if length else 0
print ("Average of Class is: ", avg)
Question
If i wanted to Keep Repeating the code above so that the user can keep using it until they want to exit. so, is it possible to put the code into a while loop and only stop the code if the user wants to, i.e the user is prompted if they want to choose another option and class.
NB: there will be other options such as alphabetical order however right now i only want to know how to do it for the average section.
Best thing you can do is to make a loop for user input and write a function for listing the file.
def main_menu():
print ("\n Main Menu ")
print ("1.Average Score of class = 'avg'")
main_menu()
option = ""
options = ["1", "2", "3"]
one = "1.txt"
two = "2.txt"
three = "3.txt"
def read_text_file(file): # standalone function for viewing files to reduce duplicate code
file += ".txt"
with open(file) as f:
the_list = [int(l.strip().split()[-1]) for l in f]
b = sum(the_list)
length = len(the_list)
avg = float(b) / length if length else 0
print ("Average of Class is: ", avg)
while True:
option = input("option [avg]: ").lower()
if option == "exit":
break # checks if user want to exit a program
else:
option_class = input("class: ")
if option == 'avg' and option_class in options:
read_text_file(option_class)
else:
print("nothing to show, asking again")
print("end of program")
As I mentioned in the comment section, you should leverage the power of functions here. By breaking down your components to manageable pieces, you actually afford yourself readability and flexibility. See code below, where I have two functions, one for averages and one for totals.
def get_class_average(class_number):
filename = "{0}.txt".format(class_number)
try:
with open(filename) as f:
the_list = [int(l.strip().split()[-1]) for l in f]
b = sum(the_list)
length = len(the_list)
avg = float(b) / length if length else 0
return avg
except:
print "No file with that name found."
def get_class_total(class_number):
filename = "{0}.txt".format(class_number)
try:
with open(filename) as f:
the_list = [int(l.strip().split()[-1]) for l in f]
b = sum(the_list)
return b
except:
print "No file with that name found."
def check_class_number(string_input):
try:
int(string_input)
return True
except ValueError:
return False
if __name__ == "__main__":
while True:
input_val = raw_input(
"Enter class number (enter 'exit' to quit program): ")
if input_val == 'exit':
break
if check_class_number(input_val): # If it's a valid class number.
method = raw_input("Enter method: ")
if method == 'avg':
avg = get_class_average(int(input_val))
print "The average of Class {0} is {1}".format(input_val, avg)
elif method == 'sum':
total = get_class_total(int(input_val))
print "The total of Class {0} is {1}".format(input_val, total)
else:
print "That is not a valid class number."
continue
Sample run:
The really fun part here is that you can even refactor get_class_average and get_class_total to be a single function that checks if the passed in method is avg or sum and returns the respective values from there (this is easily doable since you have practically the same lines of code for both functions, get_class_average just has an extra division involved).
Have fun.
Yes, you can just put your code within a while-loop and prompt the user for input:
def main_menu():
print ("\n Main Menu ")
print ("1.Average Score of class = 'avg'")
# End main_menu()
one = "1.txt"
two = "2.txt"
three = "3.txt"
keepGoing = True
while(keepGoing):
main_menu()
option = input("option [avg]: ")
option_class = input("class: ")
if option.lower() == 'avg' and option_class == '1':
with open(one) as f:
the_list = [int(l.strip().split()[-1]) for l in f]
b = sum(the_list)
length = len(the_list)
avg = float(b) / length if length else 0
print ("Average of Class is: ", avg)
if option.lower() == 'avg' and option_class == '2':
with open(two) as f:
the_list = [int(l.strip().split()[-1]) for l in f]
b = sum(the_list)
length = len(the_list)
avg = float(b) / length if length else 0
print ("Average of Class is: ", avg)
if option.lower() == 'avg' and option_class == '3':
with open(three) as f:
the_list = [int(l.strip().split()[-1]) for l in f]
b = sum(the_list)
length = len(the_list)
avg = float(b) / length if length else 0
print ("Average of Class is: ", avg)
# Prompt user for input on whether they want to continue or not:
while(True):
keepGoingStr = input("Would you like to continue? (Y/N)\n>>> ").lower()
if(keepGoingStr[0] == 'y'):
# Keep going
keepGoing = True
break
elif(keepGoingStr[0] == 'n')
# Stop
keepGoing = False
break
else:
print("Sorry, your input did not make sense.\nPlease enter either Y or N for yes or no.")
# end if
# end while - keep going input
# End While(keepGoing)
As mentioned in the comments, though, you should consider breaking up your code into functions.

Categories

Resources