Python 3, Calling a Function Properly - python

I'm quite new to Python, kind of new to programming and I'm having trouble creating a proper "loop".
def gameLoop():
print('1')
if ageInt == 2:
gamePlay = '{}'.format(input("Would you like to play a game?\n"))
else:
sys.exit(0)
time.sleep(1)
if any([gamePlay == 'yes', gamePlay == 'sure']):
print('you are playing a game')
elif gamePlay == 'maybe':
gamePlay = '{}'.format(input("C'mon, let,'s play...\n"))
time.sleep(1)
gameLoop()
I realize a lot of this code may be sloppy, but I'm trying to call gameLoop, so if they answer "maybe" it returns to gameLoop. Why doesn't the last line of the code return to the first line?
Edit to include full code:
import time
import sys
name = input('What is your name?\n')
print('Hello, %s!' % name)
age = int (input('how old are you?\n'))
print('Your age is: %s' % age, ' and your name is: %s' % name)
ageInt = int (1)
def gameLoop():
print('gameloopworks')
if ageInt == 2:
gamePlay = '{}'.format(input("Would you like to play a game?\n"))
else:sys.exit(0)
time.sleep(1)
if any([gamePlay == 'yes', gamePlay == 'sure']):
print('you are playing a game')
elif gamePlay == 'maybe':
gamePlay = '{}'.format(input("C'mon, let,'s play...\n"))
time.sleep(1)
print('elif works')
gameLoop()
if age < 18:
print(name, 'sorry you\'re too young')
ageInt = 1
else:
print(name, 'you are totally blankable')
ageInt = 2
gameLoop()

Your code works. A recursive call gameLoop() is in progress. Or I
didn't understand the question.
What is your name?
Vladmir
Hello, Vladmir!
how old are you?
45
Your age is: 45 and your name is: Vladmir
Vladmir you are totally blankable
gameloopworks
Would you like to play a game?
maybe
C'mon, let,'s play...
OK
elif works
gameloopworks
Would you like to play a game?
maybe
C'mon, let,'s play...
OK
elif works
gameloopworks
Would you like to play a game?
maybe
C'mon, let,'s play...
ys
elif works
gameloopworks
Would you like to play a game?
yes
you are playing a game
Process finished with exit code 0

You are doing recursion instead of a loop; you are basically calling the same function each time, but the values of each call will not persist into the next because of variable scoping (a little more advanced than what you want right now, but just in case).
Try using a while loop and that should work much better for your purpose.
keep_playing = True
while keep_playing:
if <condition to stop>:
keep_playing = False
else:
# keep game

I think your code should be this
def gameLoop():
while True:
if ageInt == 2:
gamePlay = '{}'.format(input("Would you like to play a game?\n"))
else:
sys.exit(0)
if any([gamePlay == 'yes', gamePlay == 'sure']):
print('you are playing a game')
elif gamePlay == 'maybe':
gamePlay = '{}'.format(input("C'mon, let,'s play...\n"))
if __name__ == '__main__':
gameLoop()

Related

Error when trying to call a function from another function in Python

I'm building a text-based game where you have the options to fight or run. It has a random element to it so you cannot just memorize the answers to gain a victory. My problem is I put the random.randint into a function so it could be "rolled" everytime it's called so I can adjust the percentage of success/failure (live/die) per question. I have it written where it works but the randomness is included in each question. I want to seperate that so I don't have to write it out each time.
import random
def q_1_1():
option = [0,9]
chance = random.randint(0,9)
if chance <= 6:
print('You won the fight')
else:
print('You lost the fight')
quit()
def q_1_2():
option = [0,9]
chance = random.randint(0,9)
if chance <= 6:
print('You got away')
else:
print('You were captured')
quit()
def user_input1():
ui = input('fight or run? ').lower()
if ui == 'fight':
q_1_1()
user_input1_2()
if ui == 'run':
q_1_2()
user_input2()
user_input1()
user_input2 just goes to next question and so on, but say after the first fight, the villain drops a piece of armor. I want to be able to adjust the percentage, which means I have to create 2 new functions for random and 2 new question functions. So I decided to clean it up and try to put the random in its own function so I can call it after each question.
import random
def roll():
option = [0,9]
chance = random.randint(0,9)
def win_f():
print('You won the fight')
def win_r():
print('You got away')
def lose_f():
print('You lost the fight')
quit()
def lose_r():
print('You were captured')
quit()
def user_input1():
ui = input('Fight or Run? ').lower()
if ui == 'fight':
roll()
if roll <= 6:
win_f()
user_input1_2()
else:
lose_f()
if ui == 'run':
roll()
if roll <= 6:
win_r()
user_input2()
else:
lose_r()
user_input1()
Now this code is cleaner and will be easier to use, but for some reason I'm drawing a blank when trying to call the roll function.
"TypeError: '<=' not supported between instances of 'function' and 'int'"
is the error. How can I do this? I need to be able to re-roll the number every time the function is called. I cannot just have it roll once at startup.
import random
def roll_0():
options = [0,9]
chance = random.randint(0,9)
return chance
def win_f_50_50():
if roll_0() <= 4:
print('You won the fight!')
start_game()
else:
print('You lost the fight!')
quit()
def win_r_50_50():
if roll_0() <= 4:
print('You got away!')
start_game()
else:
print('You were captured!')
quit()
def start_game():
start = input('You must choose to "Fight" or "Run" ').lower()
if start == 'fight':
win_f_50_50()
if start == 'run':
win_r_50_50()
start_game()
Ok so i got it to work. you were right! and you even told me to use the return value and i still didnt get it. lol duh..i knew it was something simple i was missing thank you so much!!

Python is ignoring fleeing_attempted variable

I am making a fighting system for a text-based game I am working on, and one option is to flee.
however, I want to make it so that you can only attempt to flee once. I made it so that after 1 failed attempt, the variable fleeing_attempted is set from false to true. However, python is ignoring this and letting me attempt to flee as many times as I want.
edit: I made fixes, but the result hasn't changed. here are the modifications.
fleeing_attempted = False #the first time the variable is defined
def battle():
print("What will you do?")
print("1. attack")
print("2. flee")
action = input()
if action == "1":
print("test")
elif action == "2":
fleeing = randint(1, 100)
if fleeing in range(1, 50):
print("You got away!")
elif fleeing in range(51,100):
callable(fleeing_attempted)
print("The enemy caught up!")
battle()
elif action == 2 and fleeing_attempted:
print("You already tried that!")
battle()
Take a look at the following two lines of code:
fleeing_attempted = False
if fleeing_attempted == True:
There is no chance for fleeing_attempted to ever be True at that if statement, since it is being set to False on the line above.
Without seeing the rest of your code, it is hard to tell where the fleeing_attempted=False should go but it should probably be somewhere in initialization.
elif action == "2":
fleeing = randint(1, 100)
fleeing_attempted = False < --- Your problem is here.
if fleeing_attempted == True:
You set it to False before you do the if check, so it will never be True.
You can also do:
if fleeing_attempted:
to test if it's true.
You can also clean up your code with and
elif action == "2" and fleeing_attempted :
# rest of code
Cleaned Code:
def have_battle():
action = input("What will you do?")
print("1. Attack")
print("2.Flee")
if action == "1":
print("You choose to attack")
elif action == "2":
# do your random check
fleeing = random.randint(0, 100)
print("fleeing variable: {0}", fleeing)
if fleeing in range (1,50):
print("You choose to flee")
You had some major problems, but I cleaned up some it and you should be able to work off it.

how to loop python code

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()

Python - How to pass a variable from one method to another in Python?

I've looked around for a question like this. I've seen similar questions, but nothing that really helped me out. I'm trying to pass the choice variable from the method rollDice() to the method main(). This is what I've got so far:
import random
import os
import sys
def startGame():
answer = input('Do you want to play Super Dice Roll?\nEnter 1 for Yes\nEnter 2 for No\n'
os.system('cls')
if (answer == '1'):
rollDice()
elif(answer == '2'):
print('Thank you for playing!')
else:
print('That isn/t a valid selection.')
StartGame()
def rollDice():
start = input('Press Enter to roll dice.')
os.system('cls')
dice = sum(random.randint(1,6) for x in range (2))
print('you rolled ',dice,'\n')
choice = input('Do you want to play again?\nEnter 1 for Yes\nEnter 2 for No.\n)
return choice
def main():
startGame()
while (choice == '1'):
startGame()
print('Thank you for playing')
print('!~!~!~!~WELCOME TO SUPER DICE ROLL~!~!~!~!~\n')
main()
I know that I may have other things in here that are redundant or I may have to fix, but I'm just working on this one issue right now. I'm not sure how to pass the choice variable into the main() method. I've tried putting choice == rollDice() in the main() method but that didn't work. I do mostly SQL work, but wanted to start learning Python and I found a website that has 5 beginner tasks but virtually no instructions. This is task one.
You need to put the return value of the function into a variable to be able to evaluate it (I also corrected a few bugs in your code, mainly typos):
import random
import os
def startGame():
answer = input('Do you want to play Super Dice Roll?\nEnter 1 for Yes\nEnter 2 for No\n')
os.system('cls')
while answer == '1':
answer = rollDice()
if answer == '2':
print('Thank you for playing!')
else:
print('That isn/t a valid selection.')
startGame()
def rollDice():
input('Press Enter to roll dice.')
os.system('cls')
dice = sum(random.randint(1,6) for x in range (2))
print('you rolled ', dice, '\n')
choice = input('Do you want to play again?\nEnter 1 for Yes\nEnter 2 for No.\n')
return choice
def main():
print('!~!~!~!~WELCOME TO SUPER DICE ROLL~!~!~!~!~\n')
startGame()
print('Thank you for playing')
main()

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):

Categories

Resources