How would I put an if statement inside a function? - python

I am very very new to Python and before this I only used extremely simple "programming" languages with labels and gotos. I am trying to make this code work in Sikuli:
http://i.imgur.com/gbtdMZF.png
Basically I want it to loop the if statement until any of the images is found, and if one of them is found, it executes the right function and starts looping again until it detects a new command.
I have been looking for tutorials and documentation, but I'm really lost. I think my mind is too busy trying to go from a goto/label to an organized programming language.
If someone could give me an example, I would appreciate it a lot!

In Python indentation matters, your code should look like this:
def function():
if condition1:
reaction1()
elif condition2:
reaction2()
else:
deafult_reaction()
I recommend reading the chapter about indentation in Dive Into Python as well as PEP 0008.

x = input( "please enter the variable")
print(" the Variable entered is " + x)
myfloat = int(x)
def compare (num):
if num%2 == 0:
print(" entered variable is even")
else:
print("entered variable is odd")
compare(myfloat)

Related

Asking for user input in print function - Python 2.7

Sorry if this seems like a bit of a dumb question but I’m a bit confused about a Python 2 exercise I am trying to complete.
The exercise asks to write a code that will find the factorial of a number.
I have written a function that does this but I am confused about the pre set print function that has asks for user input as I’ve only seen this done as a separate thing. Could anyone help me figure out how to make this work please as the exercise asks for the print function to not be deleted.
Thank you in advance!
def FirstFactorial(num):
# code goes here
fact = 1
while num > 0:
fact *= num
num -= 1
return fact
x = raw_input("enter a number: ")
result = FirstFactorial(x)
# keep this function call here
print FirstFactorial(raw_input())
You have to print result not print FirstFactorial(raw_input())
The way it is set up now the program will work for the first input, but it will never print it out so you never see result.
Then it will look for a second input from your second call to raw_input(), but the user will not be notified that the program wants a second input. The second output of FirstFactorial() will be correctly printed.

Issue with running input and if/else code in a single code

Please don't hate me if something like this has been asked, I couldn't find a similar problem.
I'm learning python, and I'm trying to get a small piece of code to work in IDLE shell 3.9.7 like this
>>> mark=int(input("enter mark"))
if mark>=90:
print("excellent")
elif mark<90 and mark>=75:
print("good")
elif mark<75 and mark>=40:
print("average")
else:
print("fail")
with the idea that you enter the mark, then it prints one of the statements without having to run the input code then the if/elif/else statements afterwards (I want to have all this code, press enter and then get the desired input/output without running the if/else statements separately.) However, when I run the code, I enter the mark and nothing happens. I've tried different indentation and putting the input bit at the end, but it just asks for the mark and then nothing happens. I'm not sure what I'm doing wrong, as the app that I'm using to learn has it parsed exactly like this. Appreciate any help.
Try this it should work just had to put it in a for loop
while True:
mark=int(input("enter mark: "))
if mark>=90:
print("excellent")
elif mark<90 and mark>=75:
print("good")
elif mark<75 and mark>=40:
print("average")
else:
print("fail")
(I want to have all this code, press enter and then get the desired input/output without running the if/else statements separately
Probably you want a function, like this:
def foo(mark: str) -> None:
if mark>=90:
print("excellent")
elif mark<90 and mark>=75:
print("good")
elif mark<75 and mark>=40:
print("average")
else:
print("fail")
that you can call this way in the shell:
>>> foo(int(input("Enter your mark: ")))
10
fail

Python Function requesting input doesn't execute if statement - no error shown

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

Python - Nested if statement - else go back to original if statement

I am a total noob. I am trying to loop back to the original raw_input when inside the second if statement. i want to loop the nested if statement with an option to go back to the original raw_input. hope this makes sense. Thanks
import os
os.system("clear")
start= raw_input("SUP?\n\n1: Repo\n2: Installed\n...")
if int(start)== 1:
os.system("clear")
while True:
repo= raw_input("\n1: Search repo\n2: Install\n3: Back\n...")
if int(repo)== 1:
os.system("clear")
search= raw_input("What are you trying to search?\n")
os.system("apt-cache search " + search)
if int(repo)== 2:
os.system("clear")
inst= raw_input("What would you like to install?\n")
os.system("sudo apt-get install " + inst)
else???
if int(start)==2:
os.system("clear")
ins=raw_input("\n1: Search Installed\n2: Delete installed\n...")
Put all your code inside a function and call the function again.
Now since you are new to python, function helps in breaking up your code into functional parts. Read more about them here and here
A function calling itself is called Recursion. This is an important concept and will come handy. You can read about recursion here.
def myFunc():
start=raw_input("blah blah...")
'''Your conditions and statements'''
if #condition:
#loop back to raw_input()
myFunc()
else:
#your statements

Manipulating a global variable in a function in python

Okay so ill apologize in advance if this question has previously been answered but I've looked thoroughly and cant seem to find anything that works. Im making a very simple game where you pretty much just have to guess a number between 1 and 1000 and if its incorrect the computer guesses a number either 1 above or below your guess. here is a function I've made to determine if the guess was too low
def numLow(userInput, low, high):
while userInput < num:
print ("The guess of {0} is low".format(userInput))
compGuess = (userInput + 1)
print ("My guess is {0}".format(compGuess))
low = (userInput + 1)
if compGuess < num:
print("The guess of {0} is low".format(compGuess))
userInput = int(input("Enter a value between {0} and
{1}:".format(low, high)))
else:
print("The guess of {0} is correct!".format(compGuess))
print("I WON!!!")
showTermination()
return (userInput, low)
now my issue is that i want to change the global variables userInput, low and high in the function. ive tried inserting
global userInput
global high
global low
before the function but it doesnt seem to work and if i put the globals inside the function i get "name 'userInput' is parameter and global". now im guessing the while loop is causing the problem but i cant seem to troubleshoot it. Im totally new to coding so i apologize if im breaking any coding rules or anything. Thanks for the help.
userInput for example is an input parameter to your function. The error message says exactly what the problem is here. You wanna use a global variable called userInput and you have an input parameter called userInput which are two different things for python. When userInput should be global then just define it somewhere globally like userInput = None and then instead of reaching it into the function as parameter just write in the function global userInput and python will know you are referencing to the globally instantiated variable. Both at the same time does not work.
Use globals() like this:
globals()['userInput'] = ...

Categories

Resources