I'm taking an online-coure in Udemy
Doing my coffee-machine project, I made some functions like
def machine_input():
coffee_needs = input("What would you like?, espresso, latte or cappuccino\n").lower()
if coffee_needs == 'report':
print(f"The current resource values \n Water:{resources['water']} ml \n milk:{resources['milk']} \n coffee:{resources['coffee']}")
return False
coffee_machine()
else:
return coffee_needs
and
def coffee_machine():
while keep_working:
coffee_needs = machine_input()
check_resources(coffee_needs)
total_money = get_coins()
check_transaction(total_money, coffee_needs)
dimming_resources(coffee_needs)
if not check_transaction:
coffee_machine()
but in this case, two functions didn't work as I expected.
It show me an error when I input 'report' in machine_input().
I'd like to restart the function 'coffee_machine()' in 'machine_input()'
But now I'm thinking that I may not be able to inter-refer two functions.
Like coffee_machine in machine_input in coffee_machine in machine_input in coffee_machine in machine_input in....
Is it possible to do like this in python?
(I'm doing this with 3.10.2 ver)
It looks like you're doing unintended recursion. You're actually creating multiple separate coffee machines that spawn even more coffee machines. Unless it's supposed to be a weird coffee machine factory, it only seems that your code is doing what you think it is.
What I assume you mean by inter-referencing is just going back and forth between the two functions.
You don't need to explicitly go back from machine_input() by calling coffee_machine() there. Just return something to finish the function and you'll be back wherever you called it from. Otherwise you're spawning a totally new coffee machine, inside the first one.
You don't have to call coffee_machine() in your coffee_machine(). You're already in a while loop, so I'm guessing you wanted to continue by starting over on the same coffee machine. Otherwise you're creating a totally new coffee machine, again.
def machine_input():
coffee_needs = input("What would you like?, espresso, latte or cappuccino\n").lower()
if coffee_needs == 'off':
print('Turning off th machine')
return False
elif coffee_needs == 'report':
print(f"The current resource values \n Water:{resources['water']} ml \n milk:{resources['milk']} \n coffee:{resources['coffee']}")
return True
else:
return coffee_needs
def coffee_machine():
while keep_working:
coffee_needs = machine_input()
if not coffee_needs:
print('No coffee needs specified.')
continue
check_resources(coffee_needs)
if not check_resources:
print('Not enough resources.')
continue
total_money = get_coins()
check_transaction(total_money, coffee_needs)
dimming_resources(coffee_needs)
if not check_transaction:
print('Insufficient funds.')
continue
Consider tea.
You are basically trying to build a state machine, but the bad way (by cross-referencing functions).
To keep this simple, you could use a while loop with a global variable for the state ("working", "input" and "stop" here for example), which you modify accordingly in each of the state (= each function) and use it to select which function to run next.
Related
I am making a small text-based game in Python. It involves many inputs and so to avoid bugs, there are a few things I have to check every time an input exists. Naturally, to speed up the process I wanted to put the code into a def in order to simplify the writing process. When I put the code in the def, it red underlines the continue and break commands (meaning they are incorrect), and if you run the code using the def name, a Traceback occurs. I have tried putting the def section at the beginning of the program, after the while True: (The program is supposed to run infinitely until a certain action is taken that breaks the loop) I have also made sure to try putting it under any variables referenced and in the loop so that no part of it is not defined and so that everything would work if I were to just put the code in there.
Here is the code I am trying to put into a def.
def input_bugs():
if letter_one.lower() == "done" and total_count == 0:
print("You have to play at least one game!")
continue
elif letter_one.lower() == "done":
break
elif len(letter_one) > 1:
print("Sorry, you gotta pick a single letter, no more. Otherwise, type 'done' to end the game and see your stats.")
continue
Here is the Traceback I get every time I try to run it.
line 20
continue
^^^^^^^^
SyntaxError: 'continue' not properly in loop
At this point, I don't even care if I have to write it out every time, I can just copy and paste. I am simply curious as to why it doesn't work so that I know in the future. In case you could not tell, I am pretty new to programming so I want to learn from any mistake I make. Also sorry if I referred to some things in the wrong way. Hopefully, you understood what I meant.
choice="y"
again="y"
coin=0
credit=0
allowed=[0,10,20,50,100,200]
def money_insert():
global again
global coin
global credit
global allowed
while again=="y":
try:
coin=int(input("insert coin"))
except:
print("thats not a coin")
while coin not in allowed:
print("invalid coin")
coin = 0
credit+=coin
again=input("another coin y/n?")
money_insert()
print("you have",credit,"p")
print("")
print("**********")
print("**1 coke 100p**")
print("*2 haribo 100p*")
print("*3 galaxy 100p*")
print("**4 mars 100p**")
print("*5 crisps 50p*")
selection=int(input("what would you like? 1-5"))
while choice=="y":
if selection==1:
if credit>99:
print("Here's your coke")
credit-=100
else:
print("not enough credit")
money_insert()
The last bit keeps displaying not enough credit continuously and I don’t know what to do
Sorry if this is a really dumb question I’m really new to python
choice is never altered, so you can never escape the while choice='y': loop. Then assuming the selection chosen was 1 you continue on to buying your coke. If you have previously entered coins via the money_insert function, presumably you would have at some point answered no to the question "another coin y/n?". You never reset the again variable, so subsequent calls to money_insert will just skip your for loop and not let you enter more money. You then basically follow the same path over and over again: while choice='y': → if selection==1: → if credit>99: ... else: → print("not enough credit")
I should also like to point out the issue with your money_insert function is a direct result of using a global variable where you don't need to. Global variables can be useful in certain instances, but they are generally frowned upon for cases such as this where you generally assume running a function with the same inputs will give the same result, but since the global variable has changed, the function now behaves differently. In this instance you don't need again to be global because it isn't used anywhere else, so you can move again='y' inside the function definition and remove the line global again to solve that particular issue. The same applies to coin and allowed as they aren't used anywhere but inside the function, and although they aren't causing a problem at the moment, leaving them available outside the function to be changed could cause a problem if you try to name something else by the same name somewhere else.
I would like to know why this code does not work; it should exit at the "GAME OVER" point, but it continues to my next defined function.
I have tried other variations on exit() such as: sys.exit(), quit() and SystemExit.
run_attack = input("What do you do: Run/Attack\n")
run = ['run', 'Run', 'RUN']
attack = ['attack', 'Attack', 'ATTACK']
run_attack = 1
while run_attack < 10:
if run_attack == ("run") or ("Run") or ("RUN"):
print ("You turn to run from the wolf but he quickly pounces
you...")
time.sleep(2)
print("You are quickly ripped apart and just about get to see
yourself be eaten.")
print("GAME OVER")
break
exit() #This is where the game should exit, yet after input it
continues to the next function
elif run_attack == ("attack") or ("Attack") or ("ATTACK"):
print("You brace yourself for a bite and have no time to reach"
"for any kind of weapon form your backpack.")
time.sleep("2")
input("You clock the dog hard, twice on the muzzle.")
print("The dog recoils in pain and retreats back to the woods.")
print("You quickly start running as you assume there will be a den in the woods.")
break
else:
input("Type Run or Attack...")
You have several problems in your code; why did you write this much without testing it?
First, you read the user's input, immediately replace is with 1, and then try to test it (incorrectly) as if it were still a string. Your posted code has several syntax errors, so I have some trouble reproducing the problem. However, the immediately obvious problem is here:
break
exit() # This is where ...
You can't get to the exit statement, as you break from the loop just before you can get there.
I strongly recommend that you back up to a few lines and use incremental programming: write a few lines at a time, debug those, and don't continue until they do what you want.
Also look up how to test a variable against various values. Your if statement is incorrect. Instead, try the list inclusion you're trying to set up:
if run_attack in run:
...
elif run_attack in attack:
...
I took the liberty of rewriting your whole program to show you a few things wrong with it and a few tricks. I've done it without the loop, since you never use it anyway... you can add the while loop later once you've mastered it, but you should really go back to basics on some things here:
run_attack = input("What do you do: Run/Attack\n")
if run_attack.lower() == "run":
print("""some
stuff
with
multiple
lines and GAME OVER""")
exit()
elif run_attack in ("attack", "Attack", "ATTACK"):
print("""some
stuff
with
multiple
lines""")
else:
input("Type Run or Attack...")
Some notes:
Using """ for strings enables you to write multiple lines without multiple print statements
Using str.lower() on strings makes everything easy to compare because you only have to compare it to the lowercase version of each string. However for attack you can notice I used a different inclusion test, without multiple conditions. Either way works here.
Like the other answer here (and many comments), you should use only exit() to leave the program entirely, or only break to exit the loop and continue to other code that's beneath the entire loop.
When you rewrite your loop, with a condition like while number_of_turns < 10 don't forget to add 1 to the number of turns on each loop, otherwise that condition is always True and you'll have an infinite loop...
I'm actually quite surprised this code had any resemblance to the behavior you expected from it, my suggestion is to go back over to the basics of python, learn loops, string methods, basic commands. The rest is already said in the other answer here (which is better than mine, frankly) just wanted to add some ideas.
I thoroughly searched for an answer to my question but couldn't find anything that would explain my results. I truly hope that anyone of you can point me in the right direction.
At the moment I am trying to program a text-based adventure game using Python 3 in order to better understand the language.
While doing so I created a function that should ask the user for input and print a specific statement depending on the users input. In case the users input is invalid the function should then keep asking for input until it is valid.
Unfortunately the function only seems to keep asking for input, without ever executing the if/elif statements within the function. Due to no errors being shown I am currently at a loss as to why this is the case...
print("If You want to start the game, please enter 'start'." + "\n" +
"Otherwise please enter 'quit' in order to quit the game.")
startGame = True
def StartGame_int(answer):
if answer.lower() == "start":
startGame = False
return "Welcome to Vahlderia!"
elif answer.lower() == "quit":
startGame = False
return "Thank You for playing Vahlderia!" + "\n" + "You can now close
the window."
else:
return "Please enter either 'r' to start or 'q' to quit the game."
def StartGame():
answ = input("- ")
StartGame_int(answ)
while startGame == True:
StartGame()
You fell into the scoping trap: you are creating a new variable startGame inside the function that is discarded after you leave it. You would instead need to modify the global one:
def StartGame_int(answer):
global startGame # you need to specify that you want to modify the global var
# not create a same-named var in this scope
# rest of your code
This other SO questions might be of interest:
Python scoping rules
Asking the user for input until they give a valid response
Use of global keyword
and my all time favorite:
How to debug small programs (#1) so you enable yourself to debug your own code.
The last one will help you figure out why your texts that you return are not printed and why the if does not work on 'r' or 'q' and whatever other problems you stumble into. It will also show you that your if are indeed executed ;o)
Other great things to read for your text adventure to avoid other beginner traps:
How to copy or clone a list
How to parse a string to float or int
How to randomly select an item from a list
I have followed a tutorial on making a simple text based game in Python. I'm going to use what I learned from it to make a post-apocalyptic text adventure. Everything works, but I don't really want to use just the command console as the game. Instead, I want to use a window, which I know can be done with Tkinter. I just don't know how.
What I'm asking is if there's a way to add a GUI or window to my existing functions. The code is below:
#A simple text-based game test
global table
table=0
def start():
print 'Welcome'
global gold
gold=0
lobby()
def lobby():
print 'You are in the lobby.'
command=prompt()
if command=='north':
bedroom()
elif command=='gold':
currentGold()
lobby()
elif command=='end':
return
else:
lobby()
def prompt():
x=raw_input('Type a command: ')
return x
def currentGold():
global gold
print 'current gold: ', gold
def bedroom():
global gold, table
print 'You are in the bedroom'
command=prompt()
if command=='south':
lobby()
elif command=='bed':
print 'You return to your bed and find nothing'
bedroom()
elif command=='table':
if table==0:
print 'You go to the table and find 50 gold'
gold=gold+50
table=1
bedroom()
else:
print 'There is nothing else on the table'
bedroom()
elif command=='gold':
currentGold()
bedroom()
elif command=='end':
return
else:
bedroom()
start()
Basically, you start in a lobby, and then explore a bedroom (not really, it's just a simple test). I'd appreciate anyone's help or input.
In general, a GUI program has to be rewritten as an event loop, rather than just a sequence of code.
For example, if you write a function which just waits forever for input, then the entire GUI is waiting forever for input, which means you can't respond to mouse drags or anything else, and your window manager will display a beachball or pop up a "dead program" dialog or in some other way alert the user that your program is "frozen".
Instead, you have to write a function which just puts up an input dialog, attaches a handler or callback that gets run when the input comes in to the dialog, and then returns.
So, code that looks like this:
def lobby():
print 'You are in the lobby'
command=prompt()
if command == 'north':
bedroom()
elif command=='gold':
currentGold()
lobby()
elif command=='end':
return
else:
lobby()
… has to be split in half, like this:
def lobby():
display_text('You are in the lobby')
prompt_window = PromptWindow(handler = lobby_handler)
prompt_window.show()
def lobby_handler(command):
if command == 'north':
bedroom()
elif command=='gold':
currentGold()
lobby()
elif command=='end':
return
else:
lobby()
If this doesn't make sense, you probably want to follow some tutorials to build some simple GUI apps first, and only then come back to converting your existing program into a GUI app.
Just splitting functions in half is the quick & dirty way to turn sequential code into event-based code, but it isn't always the best. It's a great way to end up in "callback hell".
For example, what if currentGold is popping up a dialog and waiting for the user to click it, and we don't want to go back to lobby until they click it? The only way to make this work is for lobby_handler to pass lobby to currentGold, so currentGold can pass it to currentGoldHandler. And what if currentGold_handler needs to access local variables from currentGold? You have to define currentGold_handler locally so you can use it as a closure, or use functools.partial to bind them in. And so on. Before you know it, you've got code indented 60 characters, inconsistently using some callback-passing convention that you didn't design until you'd written 100 functions, 40 of which violate it in some subtle way.