def you ():
gi=input("what up")
if gi in ["Nothing much", "nothing much", "nothing"]:
print("cool")
you()
elif gi in ["stuff"]:
print("sounds good")
I apparently cannot do this, however In a bigger program I am working on, I have a function that is used twice, however based of the user input, different results happen, so I tried to include my large function, and like the above program have an if else be continued throughout the function, because there are different options for user input, based on where the person is in the program.
I am just trying to figure out a good way to run a game, where the beginning is the same (function), however the game can progress in different ways, therefore a function won't work for all of it, so I just want to know if I can have an if else statement run through a function like in the small example above?
As James already said, no you cannot continue an if statement outside of a function. Referring to your question if functions are useful in a larger program: yes they are. You can use data generated in functions in your main program or other functions by returning your results. For instance:
def you ():
gi=input("what up")
return gi
result = you()
if result in ["Nothing much", "nothing much", "nothing"]:
print("cool")
elif result in ["stuff"]:
print("sounds good")
Related
Slowly progressing with my learning with Python and would love a little hand with some code I've tried to create.
I previously had this program running with Global Variables to get a proof of concept to learn about passing variables between functions. Fully worked fine. However, rather than running the function and returning to the menu, it will just stop where I return the value and not progress back to the main menu I created. It is at the point of "return AirportDetailsGlobal".
I'm sure its a simple one, and as said - still learning!
Really appreciate any help on this!
Full code is on pastebin for further reference - pastebin 89VqfwFV
print("\nEnter airport code for overseas")
osCode = input()
airports = airData
for line in airports:
if osCode in line:
print (osCode, "Found\n\n")
print("Airport Name:",line[1])
OverseaCodeGlobal = osCode
x = int(line[2])
AirDataGlobal = x #changed here
return AirportDetailsGlobal
break
else:
print('Incorrect Choice')
menu()
menu()
If you do a return then your code goes back to where it was called from. If it wasn't called from anywhere (ie. you just ran that script directly) then calling return is in most ways equivalent to calling sys.exit(), ie. the program terminates. It'll never hit your break, leave the loop, or hit your call to menu().
Also, your indentation as given there isn't right, the else is at the same level as the for, not the if. I don't think that's the problem but you might hit it next. ;-)
I am writing a game, similar to mastermind, and I want a choice bewteen an easy or hard version. I'm not sure how to do this as I need the question before the actual game starts but then there's an error because the function is being called to run before it has been assigned.
def difficulty():
difficulty = input("would you like to the easy or hard version?")
if difficulty == ("easy"):
easy()
elif difficulty == ("hard"):
hard()
difficulty()
This is the start then after is the function with the harder game code then the easier game code. I am trying to run the easy if they request easy and vice versa but the easy () and hard() don't run the code as it isn't assigned yet. I think this is because python reads the code from top to bottom and stops when it finds an error but not sure.
I have never used this before so I apologise if things are unclear or I have done some things wrong.
I am also relatively new to python.
If anybody could help me I would greatly apprectiate it.
Python is quite smart when it comes to identifying functions inside a module. For instance you could do this:
def x():
y()
def y():
print("Y")
x()
and it would execute correctly.
You are right about the execution of a code block that happens from top to bottom, as well as the definitions of those functions will also be constructed top to button, but executed afterwards.
I see some issues in your code.
you do difficulty = input("would you like to the easy or hard version?") but at the same time you have a function called def difficulty. There is a conflict there, try to rename that variable.
you don't need to do ("easy"), it's overkill, you can compare directly to "easy".
I've written a beginner program to play a game. The main structure of the program nests various functions within an outer, parent function. I had a question about calling fparent() from within fnested().
NOTE: Sadly I cannot share the original code as this is for university and due to academic integrity policies I cannot make the code public.
The idea behind the implementation is that if a user wants to repeat the program, they should input a valid indicator, YES. This happens within a nested function. The program seeks to recognise this input and thus call fparent() once more, re-starting the program.
This is currently not working.
I wanted to know if there is a way to code this feature
Links to existing answers are most welcome as I couldn't find anything that helped me directly with this.
If you tried to call the parent function directly from nested it will give you "stack overflow" maximum depth reached.
As you stated the problem :
they should input a valid indicator, YES. This happens within a
nested function. The program seeks to recognise this input and thus
call fparent() once more, re-starting the program.
You can try something like this:
def f0():
def f1():
print("do some stuff in function f1")
def f2():
print("do some stuff in function f2")
def f3():
print("do some stuff with function f3")
user_input=str(input("Do you want to repeat the program Yes or No >> "))
map_userinput={"Yes":f0,"Level2":f2,"Level3":f3}
if user_input=="Yes":
print("ok calling the parent function from nested function")
map_userinput[user_input]()
elif user_input=="Level2":
map_userinput[user_input]()
else:
print("continue with this nested function")
f0()
I am quite new in programming scene. I was having a hard time grasping the very nature of this code.
import time
from random import randint
replies =["Yes","No","Possibly", "Ask again later", "IDK"]
def question():
print "What is your question?"
question = raw_input()
print "Thinking"
time.sleep(3)
print replies[randint(0,4)]
end()
def end():
print "Thanks for playing! Do you want to try again?"
user_reply = raw_input()
if user_reply == "yes":
question()
print "Welcome to the magic 8-ball"
question()
My questions are:
As you can see the end() function was called inside the question() function. And suppose that i keep playing the game. What happens to previous caller especially the very first question()? Is it still open? or is it closed once it called end() function.
Would that build up memories as long as i keep playing the game? I know that the memories are cleared up once the functions end, but in this code it just keeps calling a function. The only time it ends is if you close the program.
Thank you.
What happens to previous caller especially the very first question()? Is it still open?
The question() function is still "open", or at least still running, with all of its variables and other resources being used.
This is called "recursion" and is very worth of your study. Function question() is called, which calls end(), and if the player chooses to continue, this again calls question() which calls end(), etc. You get a stack of functions, alternating between question() and end(), all of which still exist and take resources. If the game continues too long, all the available resources will be consumed and the programs ends with a stack overflow error--appropriate for this site!
Each of those calls happens at the end of the calling routine, and this situation is called "tail recursion." Some compilers for a computer language can recognize this and replace the recursion with a loop, so the calling routine is indeed closed down before the new routine begins. I do not believe the standard Python interpreter does this, so the routines will build up on the computer stack.
Would that build up memories as long as i keep playing the game? Yes, that would build up items in computer memory--at least if the computer environment does not recognize the tail recursion.
I would like to use win32 in python to create 2 functions... 1. A function that checks if a certain application is running. 2. A function that checks if an application is installed...
I have tried the following to check if something is running;
def IsRunning(ProgramName):
if win32ui.FindWindow(None, ProgramName):
print("its running")
return True
else:
print("its not running!")
but the findwindow always throws an error if the program is not running before my program ever gets to the else statement and I do not know how to bypass that....
I needed to pass it like this;
def IsRunning(WindowName):
try:
if win32ui.FindWindow(None, WindowName):
print("its running")
return True
except win32ui.error:
print("its not running!")
return False
You need to put the window title exactly for it to pass the test and return True...
The next thing I want to write is a similar function that uses regular expressions to find any part of a title name...
Brilliant!!! Happy now :)
The only thing with this, is that if the Applications creator decides to change the title of the main window of the program you are trying to test for, it will no longer work... I was hoping for a much more robust way of doing it... i.e. through some kind of unique process code!
in any case this will do for the time being, but if anyone has a more definitive answer please let me know...