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')
Related
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()
I need to create a program that will input a money amount in the form of a floating point number. The program will then calculate which dollars and coins to make this amount. Coins will be preferred in the least number of coins. If any of the values is zero, I need to not output the value. IE: if the change is 26 cents you only need to tell the user they will receive 1 quarter and 1 penny. No more, no less.
Below is what I have so far, the only thing I cant figure out is to make the program not output the zero values
# calculate amount of change needed
dollar = 100
quarter = 25
dime = 10
nickel = 5
penny = 1
def main():
calc = True
while calc:
lst = []
mon = ['dollars', 'quaters', 'dimes', 'nickels', 'pennys']
doll = 0
quart = 0
dimes = 0
nick = 0
pen = 0
total = int(float(input('Enter amount of change: '))*100)
amount = total
while amount - dollar >= 0:
amount -= dollar
doll += 1
while amount - quarter >= 0:
amount -= quarter
quart += 1
while amount - dime >= 0:
amount -= dime
dimes += 1
while amount - nickel >= 0:
amount -= nickel
nick += 1
while amount - penny >= 0:
amount -= penny
pen += 1
lst.append(doll)
lst.append(quart)
lst.append(dimes)
lst.append(nick)
lst.append(pen)
print('\nThe change owed is: ')
print(" ")
for i, e in zip(lst, mon):
print(i, e)
calc = input("\nPress 'Y' to try again or any other key to exit: ")
if calc != 'y' and calc != 'Y':
calc = False
if __name__ == "__main__":
main()
else:
pass
I ended up solving it
if doll >= 1:
lst.append(doll)
mon.append("dollars")
if quart >= 1:
lst.append(quart)
mon.append("quarters")
if dimes >= 1:
lst.append(dimes)
mon.append("dimes")
if nick >= 1:
lst.append("nickles")
if pen >= 1:
lst.append(pen)
mon.append("pennies")
this seems to have worked
I am trying to create a Coin Flip Game this is what I have came up with so far:
import random
def headsOrTails(number_of_flips):
number_of_flips = int(input("How many times do you want to flip the coin: "))
heards_count = 0
tails_count = 0
for i in range(number_of_flips):
rand = random.randint(1, 2)
if rand == 1:
heards_count += 1
print(f"It is Heads.\n Heads {heards_count}")
elif rand == 2:
tails_count += 1
print(f"It is Tails.\n Tails {tails_count}")
print(heards_count)
print(tails_count)
headsOrTails(1)
I want to tell the user that they are very lucky if they get heard or tail 6 times in a role. And I was wondering if anyone can help me do that.
An if statement like this should work:
if heards_count == 6:
print('You are very lucky!')
heards_count can only equal 6 if you pass in six to the function headsOrTails(). Get rid of the line
if rand == 1 and rand == 1 and rand == 1 and rand == 1:
rand will be reset on each iteration of the loop so it does not check if rand has been equal to 1 four times. Hope this helps!
Here is what I would do. I would use the heads_count and the tails_count as a heads/tails in a row count. If you get a heads, reset the tails count. If you get a tails, reset the heads count.
import random
def headsOrTails():
number_of_flips = int(input("How many times do you want to flip the coin: "))
heads_count = 0
tails_count = 0
for i in range(number_of_flips):
rand = random.randint(1, 2)
if rand == 1:
tails_count = 0
heads_count += 1
print(f"It is Heads.\n Heads in a row {heads_count}")
elif rand == 2:
heads_count = 0
tails_count += 1
print(f"It is Tails.\n Tails in a row {tails_count}")
if heads_count == 6 or tails_count == 6:
print("You are very lucky")
headsOrTails()
import random
def headsOrTails(n):
heads_count = 0
tails_count = 0
heads_inarow = 0
tails_inarow = 0
for i in range(n):
rand = random.randint(1, 2)
if rand == 1:
tails_inarow = 0
heads_inarow += 1
heads_count += 1
print(f"It is Heads.\n Heads in a row {heads_inarow}")
elif rand == 2:
heads_inarow = 0
tails_inarow += 1
tails_count += 1
print(f"It is Tails.\n Tails in a row {tails_inarow}")
if heads_inarow == 6 or tails_inarow == 6:
print("You are very lucky")
print(heards_count)
print(tails_count)
number_of_flips = int(input("How many times do you want to flip the coin: "))
headsOrTails(number_of_flips)
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.
I'm a beginner, and I wanted to know if there was a simpler way of write this out in Python. I'm assuming some type of dictionary, but I do not understand how to write it out.
I was on a cruise a couple of days ago, and I play craps. I wanted to know if the odds are somewhat correct. So, I wrote this, but I know there is a simpler way.
import random
dice2 = 0
dice3 = 0
dice4 = 0
dice5 = 0
dice6 = 0
dice7 = 0
dice8 = 0
dice9 = 0
dice10 = 0
dice11 = 0
dice12 = 0
for i in range(100000):
dice1 = random.randint(1,6)
dice2 = random.randint(1,6)
number = dice1 + dice2
#print(dice1)
if number == 2:
dice2 +=1
elif number == 3:
dice3 += 1
elif number == 4:
dice4 += 1
elif number == 5:
dice5 += 1
elif number == 6:
dice6 += 1
elif number == 7:
dice7 += 1
elif number == 8:
dice8 += 1
elif number == 9:
dice9 += 1
elif number == 10:
dice10 += 1
elif number == 11:
dice11 += 1
elif number == 12:
dice12 += 1
total = dice2+dice3+dice4+dice5+dice6+dice7+dice8+dice9+dice10+dice11+dice12
At the end of this, it just prints out the percentage of hits on numbers from 2-12.
I'd use Counter, as that's what it was made for:
from random import randint
from collections import Counter
counts = Counter(randint(1, 6) + randint(1, 6) for i in range(100000))
total = sum(counts.values())
number_of_tens = counts[10]
from random import randint
dice = [0]*11
for i in range(100000):
dice[randint(1,6)+randint(1,6)-2] += 1
total = sum(dice) #it is 100000, of course
for i, v in enumerate(dice, 2):
print('{0}: {1}%'.format(i, v*100.0/total))
import random
def roll(n=6):
return random.randint(1, n)
dice = dict.fromkeys(range(2, 13), 0)
for i in range(100000):
number = roll() + roll()
dice[number] += 1
total = float(sum(dice.values()))
for k,v in dice.items():
print "{}, {:.2%}".format(k, v/total)