def firstdecision():
decision1 = ""
while decision1 != "Y" and decision1 != "N":
decision1 = input(" Do you belive the old man's story ? ( Y / N ) ")
if decision1 == "Y" :
print ("You take a bite of from the apple")
elif decision1 == "N" :
print ("You unsheath your hidden dagger and hold it to the old man's throat")
elif decision1 != "Y" and "N" :
return decision1
firstdecision()
So trying to make a text based game as a project to help me understand functions, loops better and what better way to actually learn than to get involved. Anyways kind of stuck here after the user inputs Y or N how would I code it where I can make a new def function() where depending on their answer (Y / N ) a different outcome happens?
What you should do is define the functions you want to call for each part of the dialogue and have a main function to call each one on answer, like:
def main():
if (decision1()):
decision2()
else:
decision3()
Where decision1() will return true or false depending on the user's answer.
By the way that is not a very smart way to make such game as you will soon run into a lot of function and if/elses, good exercise for beginners tough.
You don't define a new function at that point. Instead, you define both functions above this point in the code. Based on the user's response, you call one function or the other.
Related
This is difficult without just laying the function out first so here we go. FYI, this is essentially a medical diagnostic program I'm making.
def patient_discussion(patient, q_count): #q_count keeps track of the number of questions asked.
response_list = ['n', 'menu']
if q_count == 0:
question = input('''What would you like to ask the patient? You can ask them for/about:
N = Their name.
Or type "main" to go back to the main screen. ''')
else:
question = ('What would you like to ask the patient? ') #This is to avoid spitting out a huge block of text. I think it's important the first time but not the rest.
if question.lower() == "n":
print("My name is "+ patient['Name'] + ". ")
q_count += 1
print()
patient_discussion(patient, q_count) #This is to loop back in case the player wants to ask additional questions.
if question.lower() == "main": #To bring the patient back to the main screen if they want.
menu(patient)
if question.lower() not in response_list: #To prevent an error.
print("What the heck are you even asking me, doc?")
print()
q_count += 1
patient_discussion(patient, q_count)
When I do this, there's a recursively loop error.
RecursionError: maximum recursion depth exceeded while calling a Python object
And I know what's happening. The original function is called as
patient_discussion(patient, 0)
And when I ask a question, the q_count goes up to 1 then 2 and so on and so forth. I just don't know why it's even looping to an incorrect answer since "n" would be in the above list.
I'd appreciate any help.
I'm trying to figure out how to work with loops in Python and I need a little help. The code I wrote is just something I'm playing with. It's not an assignment or anything like that.
What I'm trying to figure out is how to loop the program so that it asks the user to input something to start the questions over. This is what I have so far:
def monkeys():
apes = "This is not a monkey!"
monkey_yes = "This is a monkey!"
is_it_a_monkey = apes + monkey_yes
monkey_question = input("Type in Gorilla, Chimp or Macaque and make sure they're capitalized: ")
for question in is_it_a_monkey:
if monkey_question == 'Gorilla' or monkey_question == "Chimp":
print(apes)
continue
else:
print(monkey_yes)
break
def main():
while True:
if again not in {"y","n"}:
print("Please enter valid input")
elif again == "n":
return "Good bye!"
elif again == "y":
return monkeys()
monkeys()
I'm trying to get main() to do most of the work since that's what my teacher wants on our assignments. Everything under main() is something I copied to see if that would work but it only returns this:
Type in Gorilla, Chimp or Macaque and make sure they're capitalized: Gorilla
This is not a monkey!
This is not a monkey!
This is not a monkey!
This is not a monkey!
It was a lot longer than just the 4 lines but this is not what I'm looking for.
I see a couple of problems here...
First of all, you're concatenating two strings...
apes = "This is not a monkey!"
monkey_yes = "This is a monkey!"
is_it_a_monkey = apes + monkey_yes
When you go into your for-loop, the interpreter is looking at each character of that concatenated string. This is why you output 38 lines of "This is not a monkey!" For what you're trying to do, you don't need a for-loop. Try this instead:
def monkeys():
apes = "This is not a monkey!"
monkey_yes = "This is a monkey!"
monkey_question = input("Type in Gorilla, Chimp or Macaque and make sure they're capitalized: ")
if monkey_question == 'Gorilla' or monkey_question == "Chimp":
print(apes)
else:
print(monkey_yes)
The next issue I see is that you don't call the main function at all. Instead of calling moneys() at the bottom of your code, call main().
Next issue is using "while True:". If you're going to use a boolean as a while condition, make sure you put logic in your code to change that condition. Changing it to "False" should be what exits your main, not a return statement. Your main() would be better off starting like this:
def main():
keep_going = True
while keep_going:
monkeys()
Notice you should call your monkeys() function first, otherwise nobody will know what to input when the program starts. You also need code asking if they want to continue running the program. Right after your monkey() call, do something like this:
monkeys()
again = input("Would you like to try again? (y/n) ")
The next issue is your use of return statements. Instead of doing this:
elif again == "n":
return "Good bye!"
do this...
elif again == "n":
print("Good bye!")
keep_going = False
Lastly, you have "if again not in {"y","n"}:". You have to assign a value to "again" or you'll get more errors. If you use the example above, it should meet your needs.
Keep plugging at it and don't lose hope. You're getting close to understanding it.
First of all, you call monkeys() but you should call main() instead since that's where the loop is. Second, return causes a function to halt execution and to continue where you called it. In order to continue looping, remove the returns in main().
To get a better understanding of how your code works read this article about debugging. It shows some tips that allow you to see step-by-step what your code is doing.
You should use this code instead, which (as many have pointed out including #Code-Apprentice above) calls the function main() as you intend. #Code-Apprentice 's answer also includes a good explanation of why this works. This code is almost exactly the same as yours above; only the last line is different:
def monkeys():
apes = "This is not a monkey!"
monkey_yes = "This is a monkey!"
is_it_a_monkey = apes + monkey_yes
monkey_question = input("Type in Gorilla, Chimp or Macaque and make sure they're capitalized: ")
for question in is_it_a_monkey:
if monkey_question == 'Gorilla' or monkey_question == "Chimp":
print(apes)
continue
else:
print(monkey_yes)
break
def main():
while True:
if again not in {"y","n"}:
print("Please enter valid input")
elif again == "n":
return "Good bye!"
elif again == "y":
return monkeys()
main()
The reason I am submitting this answer is to point out that, despite calling main(), you are going to encounter another problem right away. You refer to a variable again in main(), but you never assign a value to again in the first place (if you run this code, you can expect to see an error of the form, "NameError: global name 'again' is not defined."). Addressing this next error is beyond the scope of your question; there are lots of ways that you can re-write this code to accommodate again, if you choose.
I am currently taking part of a beginner Python code challenge and whilst my code runs how it should, the solution is written differently to my program.
As I am just starting out, I was wondering which way is more preferable to write the program,
The solution is:
# Prompt user if they want to proceed. Y/N?
should_proceed = input("Do you want to proceed? Y/N ")
# If they want to proceed
if should_proceed.lower() == "y":
# print out to the screen "SOLD!" to confirm purchase
# TODO: Gatjer credit card information and process it.
print("SOLD!")
# and then decrement the tickets remaining by the number of tickets purchased
tickets_remaining -= num_tickets
# Otherwise...
else:
# Thank them by name
print("Thank you anyways, {}!".format(name))
Whereas, I have put:
# Prompt user if they want to proceed. Y/N?
proceed = input("Would you like to proceed? Y/N ").upper()
# If they want to proceed
if proceed == "Y":
# print out to the screen "SOLD!" to confirm purchase
# TODO: Gatjer credit card information and process it.
print("SOLD!")
# and then decrement the tickets remaining by the number of tickets purchased
tickets_remaining = tickets_remaining - ticket_request
print(tickets_remaining)
# Otherwise...
elif proceed == "N":
# Thank them by name
print("Thank you for your time, {}".format(customer_name))
Was it incorrect to call upper() on the input?
Is there any other errors I have done?
Many thanks,
Was it incorrect to call upper() on the input?
No, this is a perfectly fine way to allow case-insensitive input. Their solution shows an alternative that works just as well.
Both ways are fine with one caveat. Because you are specifically checking for both Y and N, your way is probably better in that case since you would otherwise have to call upper() twice:
proceed = input("Would you like to proceed? Y/N ")
if proceed.upper() == "Y":
doSomething()
elif proceed.upper() == "N":
doSomethingElse()
On that enhanced checking, your code is slightly different in that it does nothing if the input is neither Y nor N (the other code treats anything that's not y as n). In that case, you're probably wise to ensure it is one of those values, with something like:
proceed = ""
while proceed != "Y" and proceed != "N":
proceed = input("Would you like to proceed (Y/N)? ").upper()
myName = input("Hey there, what's your name?")
print("Hello",myName,"!")
print("Here's a game called ''Guess my number'', in this game you will have to guess my number in 5 tips, I will think of a number between 1 and 20.")
ready = input("Are you readyyyy!?")
if ready = "yes" or "yeah" or "totally" or "hell yeah" or "yupp" or "yepp" or "uhumm" or "sure": <-- here's the problem it says, at "sure"'s 1st "-sign
print("Let's go!")
loop = "y"
else:
print("I'm sorry to hear that.")
loop "n"
Could please anyone help, beginner here. I tried to delete and add new word, I restared the program and the computer because there's something clearly wrong. If I delete a word like "sure" the pointer will still point to the same exact place but there's nothing there...
You're using a single = sign in your if statement. That's not allowed. If you want to check for equality, you'll need to use ==. The = operator is only for assignment statements.
While changing = to == will fix the syntax error, your code still won't work exactly right. That's because == will not be distributed over all the or options you show. The expression a == b or c gets interpreted as (a == b) or c, and if c is "truthy" (as any non-empty string will be), the expression will be considered true.
Instead, you probably want to use something like if ready in {"yes", "yeah", "totally"}. This creates a constant set object and tests if the value of the ready variable is in the set (which is a fast check).
You are using a = instead of a == in your if statement. However, I would recommend doing if ready.lower() in {"yes", "yeah", "totally", "hell yeah", "yupp", "yepp"} to account for them using all uppercase.
Also, you seem to be missing your actual loop statements. I noticed you had variables named loop that are 'y' and 'n' but don't actually use them. You should also do something like this:
myName = input("Hey there, what's your name?")
print("Hello",myName,"!")
print("Here's a game called ''Guess my number'', in this game you will have to guess my number in 5 tips, I will think of a number between 1 and 20.")
loop = True
while loop:
ready = input("Are you readyyyy!?")
if ready.lower() in {"yes", "yeah", "totally", "hell yeah", "yupp", "yepp", "uhumm", "sure"}:
print("Let's go!")
loop = False
#To break out of the while loop that will keep asking them when they are ready
else:
print("I'm sorry to hear that.")
In the book "Python for the absolute beginner" by Michael Dawson, in the chapter on Lists and Dictionaries I have learned a great deal and am trying to make a new program as practice using the old Magic 8-Ball as my inspiration. Below is the code I have come up with so far.
It works up to a point...the random generated number gets generated but the elif doesn't seem to work. I know there are better ways and simpler ways, but I am doing this to reinforce my understanding of dictionaries.
I have put several print statements in to see if I was getting a number selected and the else statement is if all goes bad. As the code stands now all I get is the number printed and the else produces "Does not compute. Exit works fine. I have also confirmed the dictionary is fine using the commented out print "ball" statement.
So my issue is why does the elif statement seem to not process the random number generated. Whom ever answers has my heartfelt thanks and appreciation.
# Import the modules
import sys
import random
# define magic 8-ball dictionary
ball = {"1" : "It is certain.",
"2" : "Outlook is good.",
"3" : "You may rely on it.",
"4" : "Ask again later.",
"5" : "Concentrate and ask again.",
"6" : "Reply is hazy, try again later.",
"7" : "My reply is no.",
"8" : "My sources say no"}
# for items in ball.items():
# print(items)
ans = True
while ans:
question = input("Ask the Magic 8 Ball a question: (press enter to quit) ")
answer = random.randint(1,8)
print(answer)
if question == "":
sys.exit()
elif answer in ball:
response = ball[answer]
print(answer, response)
else:
print("\nSorry", answer, "does not compute.\n")
random.randint() returns an integer. Your dictionary's keys are all strings. Thus, when you do answer in ball, it will always be False, because "1" != 1
What you can do is either make all the keys integers (remove the quotation marks), or make answer a string by doing:
answer = str(random.randint(1,8))
Note that you shouldn't be using an elif here. If your input is nothing, both your if and elif will be True, and most of the time you don't want this. Instead, change your elif/else to just an if/else:
if question == "":
sys.exit()
if answer in ball:
response = ball[answer]
print(answer, response)
else:
print("\nSorry", answer, "does not compute.\n")
One final thing. answer will always be in ball, because you dynamically created the dictionary. Here, you can use dict.get(). Eg:
if not question: # You can do this instead
sys.exit()
print(ball.get(answer))
You are looking up on the dictionary with a number whereas the keys are strings in the dict. So, you have to convert the number to string with str.
Change
answer = random.randint(1,8)
to
answer = str(random.randint(1,8))
The string "1" is not the int 1. So answer is actually not in ball.
Try converting it like answer = str(random.randint(1,8))