Stop running function when one variable gets to zero - python

Hope you can help me. Please see the code below. What I am trying to achieve is for code to stop when "x" or "y" gets to 0. At the moment, "x" gets to 0 first, but function_b() is still run after that. I would like that if "x" gets to 0, function_b() would not run afterwards. How do I do that?
Thank you
from random import randint
x = 10
y = 10
def roll_dice():
random_dice = randint(1, 6)
return random_dice
def function_a():
global x
while x > 0:
dice = roll_dice()
if dice >= 1:
x -= 5
else:
print('Better luck next time')
if x <= 0:
break
else:
function_b()
def function_b():
global y
while y > 0:
dice = roll_dice()
if dice >= 1:
y -= 5
else:
print('Better luck next time')
if y <= 0:
break
else:
function_a()
def turns():
if x > 0:
function_a()
else:
print('good game')
if y > 0:
function_b()
else:
print('good game')
turns()

I made some adjustement on your code :
from random import randint
x = 10
y = 10
def roll_dice():
random_dice = randint(1, 6)
return random_dice
def function_a():
global x
while x > 0 and y != 0:
dice = roll_dice()
if dice >= 1:
x -= 5
else:
print('Better luck next time')
if x <= 0:
break
else:
function_b()
def function_b():
global y
while y > 0 and x !=0:
dice = roll_dice()
if dice >= 1:
y -= 5
else:
print('Better luck next time')
if y <= 0:
break
else:
function_a()
def turns():
if x > 0:
function_a()
else:
print('good game')
if y > 0:
function_b()
else:
print('good game')
turns()

Related

Python craps game: Wrong output

I'm a beginner and I can't figure out why I can't get the output I
want. It's a craps game. It's suppose to go like:
How many games do you want to play > 6 You rolled 5 + 2 = 7 You
win
What I got is something like: You rolled 1 + 6 = 7 You rolled 1 + 6 =
7 You rolled 1 + 6 = 7 You lose
import random
def rollDice():
roll_1 = random.randint(1,7)
roll_2 = random.randint(1,7)
return roll_1, roll_2
def determine_win_or_lose(dice1,dice2):
sum = dice1 + dice2
print("You rolled", dice1, "+", dice2, "=", sum )
if sum == '2' or '3' or '12':
return 0
elif sum == '7' or '11':
return 1
else:
print("Point is", sum)
determinePointValueResult(sum)
if determinePointValueResult(sum) == 1:
return 1
elif determinePointValueResult(sum) == 0:
return 0
def determinePointValueResult(sum):
point = sum
while sum != 7 and sum != point:
x, y = rollDice()
sum = x + y
if sum == point:
return 1
elif sum == '7':
return 0
print("You rolled", x, "+", y, "=", sum )
#==== MAIN =====
win = 0
lose = 0
game = int(input("How many games do you want to play > "))
for i in range(game):
x, y = rollDice()
determine_win_or_lose(x, y)
if determine_win_or_lose(x, y) == 1:
print("You win")
win = win + 1
elif determine_win_or_lose(x, y) == 0:
print("You lose")
lose = lose + 1
print("Game results: ", win, "wins and", lose, "losses")
Your issue come from the main, because you call the determine_win_or_lose function 3 times, the first one before the if (and i'm not sure why since you do nothing with it), a second time to check the condition of the if and a third time to check the condition of the elif.
Since it's this function that print the message, and you call the function 33 times each iteration of the for loop, it's normal to get the message printed 3 times.
(
Also since the determine_win_or_lose will always return 0 or 1 you don't really need an elif you can just do an if/else to achieve the same thing and simplify your code a bit.
)
So i'd suggest the following :
#==== MAIN =====
win = 0
lose = 0
game = int(input("How many games do you want to play > "))
for i in range(game):
x, y = rollDice()
result = determine_win_or_lose(x, y)
if result == 1:
print("You win")
win = win + 1
else:
print("You lose")
lose = lose + 1
print("Game results: ", win, "wins and", lose, "losses")
Obvious issues:
You call determine_win_or_lose too many times in your for loop. Change it to:
for i in range(game):
x, y = rollDice()
result = determine_win_or_lose(x, y)
if result == 1:
print("You win")
win = win + 1
elif result == 0:
print("You lose")
lose = lose + 1
Your check in determine_win_or_lose is incorrect. It should be something like:
def determine_win_or_lose(dice1,dice2):
sum = dice1 + dice2
print("You rolled", dice1, "+", dice2, "=", sum )
if sum == 2 or sum == 3 or sum == 12:
return 0
elif sum == 7 or sum == 11:
return 1
else:
print("Point is", sum)
determinePointValueResult(sum)
if determinePointValueResult(sum) == 1:
return 1
elif determinePointValueResult(sum) == 0:
return 0
In determinePointValueResult you shouldn't compare sum to a string, but an integer:
def determinePointValueResult(sum):
point = sum
while sum != 7 and sum != point:
x, y = rollDice()
sum = x + y
if sum == point:
return 1
elif sum == 7:
return 0
print("You rolled", x, "+", y, "=", sum )
It's possible that determine_win_or_lose and determinePointValueResult are returning None. You may need to change your elifs to elses or create a new else case.

Made a simple "Death roll" game. I want to try and make code cleaner and not repeat myself as i am right now with the current "roll" function

Made a simple "Death roll" game. I want to try and make code cleaner and not repeat myself as i am right now with the current "roll" function.
import random
from time import sleep
def roll():
p1_turn = True
p2_turn = False
current_max = int(input("You are player 1. Enter a number: "))
print("")
while current_max > 1:
if p1_turn:
round_max = current_max
current_max -= random.randint(0, current_max - 1)
p1_turn = False
p2_turn = True
print(f"Player 1 rolled: {current_max} (1 - {round_max})")
sleep(1)
print("")
if current_max == 1:
print("Player 2 wins!!")
elif p2_turn:
round_max = current_max
current_max -= random.randint(0, current_max - 1)
p1_turn = True
p2_turn = False
print(f"Player 2 rolled: {current_max} (1 - {round_max})")
sleep(1)
print("")
if current_max == 1:
print("Player 1 wins!!")
roll()

Python Won't Run

My python program prints the first thing I wrote, and then loads forever and never prints the second task. What do I need to change with my code?
import random
def main():
money = 100
win = 0
loss = 0
draw = 0
bet = random.randint(5, 20)
print('You are starting with $100 and each round you will bet', bet, 'dollors')
while True:
x = random.randint(1, 6)
y = random.randint(1, 6)
z = x + y
if money == 0 or money == 200:
break
if z == 7 or z == 11:
money += bet
win += 1
elif z == 2 or z == 3 or z == 12:
loss += 1
money -= bet
else:
draw += 1
print('You ended up with', money, 'dollars, and you won', win, 'rounds, lost', \
loss, 'rounds, and drew', draw, 'rounds')
main()
Looks like it will never be able to satisfy all the conditions and is caught in a infinite loop
I think you have to use correct condition in the if condition and i suggest u to use a var to run the loop and to break the loop.
import random
def main():
money = 100
win = 0
loss = 0
draw = 0
bet = random.randint(5, 20)
print('You are starting with $100 and each round you will bet', bet, 'dollors')
loop = True
while loop:
x = random.randint(1, 6)
y = random.randint(1, 6)
z = x + y
if money <= 0 or money >= 200:
loop = False
if z == 7 or z == 11:
money += bet
win += 1
elif z == 2 or z == 3 or z == 12:
loss += 1
money -= bet
else:
draw += 1
print('You ended up with', money, 'dollars, and you won', win, 'rounds, lost', \
loss, 'rounds, and drew', draw, 'rounds')

Making Mastermind in Python

I am simply wondering how I can make my game of Mastermind work, more specifically how I would go about making "finish" global, how I would call these functions so that the program works correctly, and overall tips that would help enhance my code. I would also like to know how to make it so the program doesn't 'reroll' the computer-generated number every single loop. This was just a difficult problem for me and I can't seem to understand how to close it out with the correct function calls and niche aspects such as that. Thank you.
run = True
def get_guess():
while run:
guess = input("Provide four unique numbers: ")
count = 0
if len(guess) == 4:
guessdupe = guess[0] == guess[1] or guess[0] == guess[2] or guess[0] == guess[3] or guess[1] == guess[2] or guess[1] == guess[3] or guess[2] == guess[3]
else:
guessdupe = False
try:
try:
for i in range(4):
if int(guess[i]) <= 7 and int(guess[i]) >= 1 and len(guess) == 4:
count += 1
if len(guess) != 4:
print "Your guess must consist of 4 numbers!"
if guessdupe:
count -= 1
print "You can only use each number once!"
except ValueError:
print "You can only use numbers 1-7 as guesses"
except IndexError:
print "You can only use numbers 1-7 as guesses"
if count == 4:
break
return guess
def check_values(computer_list, user_list):
final_list = [''] * 4
for i in range(4):
if user_list[i] in computer_list:
if user_list[i] == computer_list[i]:
final_list[i] = "RED"
else:
final_list[i] = "WHITE"
else:
final_list[i] = "BLACK"
random.shuffle(final_list)
print final_list
return final_list
def check_win(response_list):
if response_list[0] == "RED" and response_list[1] == "RED" and response_list[2] == "RED" and response_list[3] == "RED":
print "Congratulations! You've won the game!"
global finish
finish = True
def create_comp_list():
while run:
compList = [random.randint(1, 7), random.randint(1, 7), random.randint(1, 7), random.randint(1, 7)]
listBool = compList[0] == compList[1] or compList[0] == compList[2] or compList[0] == compList[3] or compList[1] == compList[2] or compList[1] == compList[3] or compList[2] == compList[3]
if listBool:
continue
else:
return compList
def play_game():
for i in range(5):
print create_comp_list()
print get_guess()
check_win(check_values(create_comp_list(), get_guess()))
if finish:
break
play_game()```

How do i use a variable defined already in a different function in another function?

def winOrLose():
rand = random.randint(0,1)
if rand == 1:
win = 1
return win
elif rand == 0:
lose = 0
return lose
def scores():
score = 0
if win = 1:
score += 1
elif lose:
score -= 1
I get an error when using the win and lose in the second function.
There is no need to use this variables outside this function as it returns the values. Instead use the functions return values directly:
def winOrLose():
rand = random.randint(0,1)
if rand == 1:
win = 1
return win
elif rand == 0:
lose = 0
return lose
def scores():
score = 0
if winOrLose() == 1:
score += 1
else:
score -= 1
Or even more simple without need of using variables win, lose and rand:
def winOrLose():
if random.randint(0,1) == 1:
return True
else:
return False
def scores():
score = 0
if winOrLose():
score += 1
else:
score -= 1
But there is one more thing: what do you do with your variable score in your function scores? Right now it does nothing but setting the local variable score to either 1 or -1 and forget it right at the end. Maybe you want something like this to calculate a new score from an existing value and return the new result:
def calc_score(score=0):
if winOrLose():
return score += 1
else:
return score -= 1

Categories

Resources