how to loop python code - python

I made the beginning of a basic text adventure game, and I want it to loop whenever you die, but any examples of code I see aren't working, and thorugh research i still cant find something that could work.
print("A tale of time version 0.0.1. by Tylan Merriam")
print("you awaken, the room is dark and you cannot see. the sheets on your
bed are damp, and you hear a faint dripping sound.")
ch0pg1 = input('>: ')
if ch0pg1 == 'turn on light':
print("you flip the light on, it turns out the dripping was from a leaky
pipe above you. you see a dresser(outisde of bed) a chair with something
glinting on it(outside of bed) and a window(outisde of bed)")
ch1p1 = input('>: ')
if ch1p1 == 'stand':
print('you stand up, the game isnt finished so this is all there is,
try saying stand at the first choice or anything else')
else:
print('sorry, but i have no fricking clue what that means')
elif ch0pg1 == 'stand':
print('since you cannot see, you bump your head on a brick and collapse.
as you think of your last words you realize the only thing that comes to
mind is wushtub.')
diemessage = input('>: ')
if diemessage == 'lol':
print('i agree, now shut up, your dead')
else:
print('shut it, your dead')
else:
print('I have no clue what that means,')

You can try embedding a while loop within a while loop kind of like this.
while(1):
while(1):
# some code
# also some code
diemessage = input('>: ')
if diemessage == 'lol':
print('i agree, now shut up, your dead')
chc = input("play again? (y,n): ")
if chc == "y":
break # break this while loop which just starts again
elif chc == "n":
exit() # exit the game entirely
else:
# You can set this bit to your liking.
print("thats no answer, bye")
exit()
else:
print('shut it, your dead')
chc = input("play again? (y,n): ")
if chc == "y":
break # break this while loop which just starts again
elif chc == "n":
exit() # exit the game entirely
else:
# You can set this bit to your liking.
print("thats no answer, bye")
exit()
It simply creates a while loop for the game inside of a while loop. Break breaks out of the while loop while being ran, so it just exits and starts again. If the user chooses to quit, it stops the whole program.
You would think that we could create a function to make it easier, but when I tried breaking with a function it won't break, so you are going to have to keep pasting this in as of what I know. :P

Could do:
while (true)
{
//print statements
//whenever you die:
continue;
}

Well, you first need to define what you want to loop. Make a function called game() with your included code. Then this would work:
if diemessage == "lol":
print("something")
else:
print("Shut it, your dead")
game()

Related

while loop could not break

there is NameError: name 'user' is not defined
why while loop is not ending please help to find the problem
this program is for dice roll in pyhton
I want to roll the dice with no exception but there are exception accured
rand_num=random.randint(1, 6)
game_is_on=True
while True:
try:
user=int(input("What's your choice : "))
continue
except:
print("Please Enter 1-6")
if user == rand_num:
print("\t congrats ! \n You guessed it right 🎊")
elif user != rand_num:
print("Sorry! your guess is incorrect🥺")
replay=input("Do you want to play again (Yes/No)")
if replay =='yes'.lower():
game_is_on=True
else:
print("Thanks for playing this game")
game_is_on=False```
hlep to find the problem please
For your loop to exit:
Your while loop will forever be true, but you switched a variable game_is_on that was meant to regulated the loop. Instead of the forever loop , game_is_on should be next to while,
You need to remove continue statement as that line will just go to the next iteration as long as the condition is true,
When asked about replaying, the lower part should be on the variable, instead of lowering the string itself.
Below is the code you need:
rand_num=random.randint(1, 6)
game_is_on=True
# while True:
while game_is_on:
try:
user=int(input("What's your choice : "))
# continue
except:
print("Please Enter 1-6")
if user == rand_num:
print("\t congrats ! \n You guessed it right 🎊")
elif user != rand_num:
print("Sorry! your guess is incorrect🥺")
replay=input("Do you want to play again (Yes/No)")
if replay.lower() =='yes':
game_is_on=True
else:
print("Thanks for playing this game")
game_is_on=False
Happy coding!
import random
rand_num=random.randint(1, 6)
game_is_on=True
while game_is_on:
try:
user=int(input("What's your choice : "))
except:
print("Please Enter 1-6")
if user == rand_num:
print("\t congrats ! \n You guessed it right 🎊")
elif user != rand_num:
print("Sorry! your guess is incorrect🥺")
replay=input("Do you want to play again (Yes/No)")
if replay =='yes'.lower():
game_is_on=True
else:
print("Thanks for playing this game")
game_is_on=False
Note:
In while loop you have to write 'game_is_on' as for that variable it is telling whether true or false instead you have written True therefore your loop will never end as nothing is breaking the loop
corrected code is pasted above, hope this might help you.
You can use operator break to end while loop. lower() should be used with variable.
if replay.lower() != 'yes':
print("Thanks for playing this game")
break

How can I have my input be typed out again via using while loops and if statements?

So i have this simple problem and I am not so sure what to do even after trying it for quite sometime.
combinations = ["rock","papers","scissors"]
ask = str(input("Do you want to play rock papers scissors?"))
while ask:
if ask.lower() == "yes":
print("ok")
break
elif ask.lower() == "no":
print("okay :(")
break
else:
ask = input("So is it a yes or no ?!")
break
my issue is that I am not so sure what to type such that my input user has to type either yes or no instead of typing something else. Additionally, when I tried to run the program, when I typed yes/no it jumped straight to the else statement instead of the if statement.. someone pls help :( (am just a noob programmer)
I would remove the break in the else statement so that your program keeps looping until the user inputs yes or no.
combinations = ["rock","papers","scissors"]
ask = str(input("Do you want to play rock papers scissors?"))
while ask:
if ask.lower() == "yes":
print("ok")
break
elif ask.lower() == "no":
print("okay :(")
break
else:
ask = input("So is it a yes or no ?!")

Python typewriter effect issues

string = "Your NEW name is ALBY. You have 3 minutes to get to your shelter or you get RIPPED APART by gamma radiation and A MASSIVE FIREBALL. Do you RUN, SHELTER, or WAIT?"
for char in string:
print(char, end='')
time.sleep(.05)
print("")
time.sleep(5)
answer1 = input("What do you do?")
while True:
if answer1 == "RUN":
print("")
print ("You choose to RUN. Within minutes of running you see a massive
FIREBALL behind you, say your PRAYERS and DIE.")
print("")
time.sleep(5)
print("You Died! The creator of this game can't use 'While True'
statements and therefore you must restart.")
elif answer1 == "WAIT":
print("This is certainly not YOUR BEST IDEA. You WAIT for the bomb to drop
and DIE a hot death.")
print("")
time.sleep(5)
print("")
print("You Died! The creator of this game can't use 'While True' statements and therefore you must restart.")
elif answer1 == "SHELTER":
def slowprint(s):
for c in s + '\n':
sys.stdout.write(c)
sys.stdout.flush() # defeat buffering
time.sleep(random.random() * 0.1)
slowprint('Hello, world.')
Above is the code snippet, i have the typewriter effect going for a little text adventure. When I run the code all that happens is i get a blank loop, or the first letter of the line.
[EDIT: This isn't a duplicate of a flushing issue. I didn't want to flush slowprint i just needed to redefine it.]

error with elif. says that elif is a syntax error

diamondCave = random.randint(1, 3)
goldCave = random.randint(1, 3)
while diamondCave == goldCave:
goldCave = random.randint(1, 3)
if chosenCave == str(diamondCave):
pygame.mixer.init()
pygame.mixer.music.load("test.wav")
pygame.mixer.music.play()
while pygame.mixer.music.get_busy() == True:
continue
print('full of diamonds!')
elif: chosenCave == str(goldCave):
print('full of gold!')
else:
print('hungry and gobbles you down in one bite!')
playAgain = 'yes'
while playAgain == 'yes' or playAgain == 'y':
displayIntro ()
caveNumber = chooseCave()
checkCave(caveNumber)
print('Do you want to play again? (yes or no)')
playAgain = input()
else:
pygame.mixer.init()
pygame.mixer.music.load("test.wav")
pygame.mixer.music.play()
while pygame.mixer.music.get_busy() == True:
continue
I want to make the code so that each time a chest is picked, it plays a sound. When a diamond gets picked it makes a cool sound, when gold is picked, a different sound is played, and when the chest eats you, it should make a game over sound. Every time I use the code of the sound, it says that the elif statement is invalid syntax. What did I do wrong?
The problem is that elif: is a syntax error.
The whole point of elif is that it means else if. Just like you can't write if: without a condition, you can't write elif: without a condition.
Meanwhile, the statement after the : is clearly supposed to be the condition expression, not a statement. So you almost certainly wanted this:
elif chosenCave == str(goldCave):
Remove the ":" after the elif
elif: chosenCave == str(goldCave):
Like this:
elif chosenCave == str(goldCave):

How do I use 2 loops, and if it is false, repeat the program indefinetely

Right now I am doing the tutorial "Dragon Realm" from this site http://inventwithpython.com/chapter6.html
I understand what it's all doing slightly but that is not my problem. At the end I'm wanting to add a bit of code that if the player says no, it says, as I currently have it, "too bad *!" and move back up to the beginning of the program. I've gotten it to do that, but once it goes through the second time and i get to the input of whether you want to try again whether or not you type yes or no it just ends the program. I've tried multiple combinations of while, if/else, while True, while False and I am not getting the results I am wanting. I don't understand how you just keep it to keep going? It's probably really simple but I can't figure it out.
this is the code for the program.
import random
import time
def displayIntro():
print('You are in a land full of dragons. In front of you,')
print('you see two caves. In one cave, the dragon is friendly')
print('and will share his treasure with you. The other dragon')
print('is greedy and hungry, and will eat you on sight.')
print()
def chooseCave():
cave = ''
while cave != '1' and cave != '2':
print('Which cave will you go into? (1 or 2)')
cave = input()
return cave
def checkCave(chosenCave):
print('You approach the cave...')
time.sleep(2)
print('It is dark and spooky...')
time.sleep(2)
print('A large dragon jumps out in front of you! He opens his jaws and...')
print()
time.sleep(2)
friendlyCave = random.randint(1, 2)
if chosenCave == str(friendlyCave):
print('Gives you his treasure!')
else:
print('Gobbles you down in one bite!')
playAgain = 'yes'
while playAgain == 'yes' or playAgain == 'y':
displayIntro()
caveNumber = chooseCave()
checkCave(caveNumber)
print('Do you want to play again? (yes or no)')
playAgain = input()
You could add simply,
if 'n' in playAgain:
print "too bad"
playAgain = 'yes'
At the end (inside your while loop)
By the way, these two lines can be combined:
print('Do you want to play again? (yes or no)')
playAgain = input()
as simply:
playAgain = input('Do you want to play again? (yes or no)')
Because input will display the string argument when asking for input.

Categories

Resources