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
Related
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
So I have been playing around with schedule and finally got it to work. I was too excited to relized that there came ANOTHER problem haha. However the issue is now that it doesn't end whenever the main is finished and I can't really find the solution. I know the issue sits on the row Time.sleep(1) because whenever I keyboardInterrput then there comes a error saying Time.sleep(1) was the "Issue" and I can't really find a soulution to end it.
Im using a schedule from a github : Github schedule
while True:
UserInput = input('To run Schedule task - Press y\nTo run directly - Press n\n')
if(UserInput == 'y' or UserInput == 'Y'):
print(Fore.RESET + space)
TimeUser = input('What time to start script? Format - HH:MM\n')
schedule.every().day.at(TimeUser).do(main)
wipe()
print('Schedule starts at: ''' + TimeUser + ' - Waiting for time...')
idle = int(round(schedule.idle_seconds()))
while True:
schedule.run_pending()
time.sleep(1)
idle = int(round(schedule.idle_seconds()))
if(idle < 6.0) and (idle >= 0.0):
print('Starting in: ' + str(idle))
elif(UserInput == 'n' or UserInput == 'N'):
main()
print("Wrong input - Try again")
You could use the for keyword. The for statement can define your iterations and the halting conditions. Or using the range() function to iterate over your numerical sequence.
Being used to traditional if-then-else statements, the break statement will break you out of your while loop. It needs to be with your innermost for or while loop. Your else clause needs to belong to your for loop and not part of the if statement. And the continue statement will move your loop forward.
There are examples here: https://docs.python.org/3/tutorial/controlflow.html
You code is encapsulated in while loops with true as the argument. Either you did this by mistake or this is poor structure. This is the problem.
If you don't want to remove the while loops then atleast add a break somewhere.
If you need help structuring your code, go to Code Review.
I would like to get user input while printing to the screen. I researched this a lot. but didn't find anything. I'm not very advanced with class programming in Python, so I didn't understand the other examples on stackoverflow.
Example:
import time
def user_input():
while True:
raw_input("say smth: ")
def output():
while True:
time.sleep(3)
print "hi"
input()
output()
I want the prompt to stay, even if the output is printing "hi". I already tried an example, but the input prompt disappears even if it is in a while loop.
First, let's go over your code
import time
def user_input():
while True:
raw_input("say smth: ")
def output():
while True:
time.sleep(3)
print "hi"
input()
output()
You are calling input() which is not actually your function name. It's user_input(). Also, once user_input() is called, output() will never be called because the while True condition in user_input() is always True, meaning it never exits outside the function.
Also, if you want to do something with multithreading, but you don't understand classes in Python, you should probably do a tutorial related to classes.
Take a look at this other StackOverflow Post on a multithreaded program.
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)