Sorry if this is considered spam, yet another issue I have is that this while loop runs unconditionally and I am not sure how to fix it.
Code:
while anotherNum == True:
playerNum = random.randint(1,10)
total = total + playerNum
print("")
print("Your number is ", str(playerNum) + ".")
print("You have " + str(total) + " in total.")
print("")
again = input("Roll another number? <Y or N> ")
print("")
if again == "Y":
anotherNum == True
else:
anotherNum == False
break
#game finished now
print("Computer got", pcNum)
print("You got", total)
#checking for winner
while anotherNum == False:
if (total <= 13) and (total > pcNum):
print("You,", name, "have won!")
elif (pcNum <= 13) and (pcNum > total):
print("The computer has bested you,", name + "!")
else:
if (total == pcNum) and (total <= 13):
print("Draw...")
elif (pcNum > 13) and (total <= 13):
print("You,", name + " have won!")
else:
print("Both of you have lost. Wow...")
Output:
Your number is 2.
You have 2 in total.
Roll another number? <Y or N> n
Your number is 3.
You have 3 in total.
Roll another number? <Y or N> N
Your number is 3.
You have 3 in total.
Roll another number? <Y or N> N
Your number is 9.
You have 9 in total.
Instead of going to the #game finished now comment's area, the while loop repeats the process whilst only disregarding the total = total + playerNum command.
You are not changing the valu
if again == "Y":
anotherNum == True
else:
anotherNum == False
break
You should use 1 equal sign as it is an assignment
if again == "Y":
anotherNum = True
else:
anotherNum = False
break
Your code (with minimal correction) is working just fine:
import random
total = 0
anotherNum = True
while anotherNum == True:
playerNum = random.randint(1,10)
total = total + playerNum
print("")
print("Your number is ", str(playerNum) + ".")
print("You have " + str(total) + " in total.")
print("")
again = input("Roll another number? <y or n> ")
print("")
if again == "y":
anotherNum = True
else:
anotherNum = False
break
print("You got", total)
The output that I get after running the code:
Your number is 7.
You have 7 in total.
Roll another number? <y or n> y
Your number is 9.
You have 16 in total.
Roll another number? <y or n> y
Your number is 10.
You have 26 in total.
Roll another number? <y or n> y
Your number is 2.
You have 28 in total.
Roll another number? <y or n> y
Your number is 6.
You have 34 in total.
Roll another number? <y or n> n
You got 34
Here's how I would do it.
while anotherNum:
playerNum = random.randint(1,10)
total += playerNum
print("")
print("Your number is ", str(playerNum) + ".")
print("You have " + str(total) + " in total.")
print("")
again = input("Roll another number? <Y or N> ")
print("")
anotherNum = (again == "Y")
this way you can avoid the if <blank> then true else false which caused you to make a mistake here (simple == instead of =)
Try to remove break and change == to =
import random
total = 0
anotherNum = True
while anotherNum == True:
playerNum = random.randint(1, 10)
total += playerNum
print("")
print(f"Your number is {playerNum}.")
print(f"You have {total} in total.")
print("")
again = input("Roll another number? <Y or N> ")
print("")
if again == "Y":
anotherNum = True # <- HERE
else:
anotherNum = False # <- HERE
OR without anotherNum variable:
import random
total = 0
while True:
playerNum = random.randint(1, 10)
total += playerNum
print("")
print(f"Your number is {playerNum}.")
print(f"You have {total} in total.")
print("")
again = input("Roll another number? <Y or N> ")
print("")
if again == 'N':
break
Related
I had to build a game which awards players based on their guess. The user guesses a number and the algorithm compares that to a randomly-generated 2-digit number and awards the player accordingly.
Problem: The player needs to play this game 3 times before the game ends. When I loop it 3 times with a while loop it only loops by asking the user for their guess and does not print or return the award message. When I remove the while loop and use a for loop it only runs once and prints the message.
How do I solve this looping issue and run this program thrice?
import random
jackpot = 10000
award2 = 3000
award3 = 100
noaward = 0
play = 3
turns = 1
def lottery_game():
for x in range(play):
lottery = random.randrange(10,99)
lot = list(map(int, str(lottery)))
guess = int(input("Choose a 2 digit number: "))
n_guess = list(map(int, str(guess)))
if guess == lottery:
return "You won: " + str(jackpot) + " Euros"
elif n_guess[0] == lot[0] or n_guess[1] == lot[1]:
return "You won: " + str(award2) + " Euros"
elif n_guess[0] == lot[1] or n_guess[1] == lot[0]:
return "You won: " + str(award3) + " Euros"
else:
return "I am sorry, you won: " + str(noaward) + " Euros" + " try again"
while i <= 3:
lottery_game()
i = i + 1
According to your code, you're not initialising your i variable before your while you shoud definitely do it. But for your use case, you shouldn't use a while, you should use a for loop like this:
for i in range(0,3):
This will run the code in the loop three times.
You need to
replace return with print statement:
replace while i <= 3 with for i in range(3)
Here is updated code:
import random
jackpot = 10000
award2 = 3000
award3 = 100
noaward = 0
def lottery_game():
lottery = random.randrange(10, 99)
lot = list(map(int, str(lottery)))
guess = int(input('Choose a 2 digit number: '))
n_guess = list(map(int, str(guess)))
if guess == lottery:
print(f'You won: {jackpot} Euros')
elif n_guess[0] == lot[0] or n_guess[1] == lot[1]:
print(f'You won: {award2} Euros')
elif n_guess[0] == lot[1] or n_guess[1] == lot[0]:
print(f'You won: {award3} Euros')
else:
print(f'I am sorry, you won: {noaward} Euros. Try again')
for i in range(3):
lottery_game()
Sample output:
Choose a 2 digit number: I am sorry, you won: 0 Euros. Try again
Choose a 2 digit number: You won: 100 Euros
Choose a 2 digit number: You won: 10000 Euros
you have not initialized i
Before the while statement add i=1
Hey I'm trying to add a variable for "won" or "loss", I already have a variable for players name and guesses allowed.
Any help would be kind thanks. This is the code I have so far:
import random
number = random.randint(1, 100)
player_name = input("Hello, What's your name?: ")
number_of_guesses = 0
print("Okay! "+ player_name+ " I am guessing a number between 1 and 100:")
max_guesses = random.randint(1, 6)
print("You have " + str(max_guesses) + " guesses. ")
while number_of_guesses < max_guesses:
guess = int(input())
number_of_guesses += 1
if guess < number:
print("Your guess is too low")
if guess > number:
print("Your guess is too high")
if guess == number:
break
if guess == number:
print("You guessed the number in " + str(number_of_guesses) + " tries!")
else:
print("You did not guess the number, the number was " + str(number))
f = open("statistics.txt", "a")
f.write =(player_name) (max_guesses)
f.close()
f = open("statistics.txt", "r")
print(f.read())
Maybe add befor you loop the variable won = False
And in the loop
if guess == number:
won = True
break
After the loop if the player don't find the nulber won will be false.
In the oter case it will be True
For saving
f.write( str(won) ) # convert to string
I am making a number guessing game for a project as a part of my intro to the coding class. I am trying to calculate the total earnings for the user, but I keep getting a type error and I have no idea what I am doing wrong.
print("To begin the game pay two dollars")
print("You can collect your winnings when you stop playing")
import sys
count = 0
Jackpot_wins = 0
Reversed_digits = 0
Digit_WrongPlacement = 0
Digit_RightPlacement = 0
Digit_RightPlacement_two = 0
Digit_WrongPlacement_two = 0
JackpotValue = 100
Reversed_digitsValue = 10
Digit_RightPlacementValue = 10
Digit_WrongPlacementValue = 5
Cost_Per_Play = 2
Game_start = input("Would you like to play? enter 'y' for yes and 'n' for no: ")
if Game_start == "n":
print("Thats ok, maybe next time")
sys.exit()
while Game_start == "y":
count = count + 1
Money_Spent = count * Cost_Per_Play
Player_Number = int(input("Enter a number 0-99: "))
print(Player_Number)
import random
Hidden = random.randint(0,99)
Reversed_digits = (str(Hidden)[::-1])
print(Hidden)
Jackpot = Hidden == Player_Number
PN = int(Player_Number / 10)
RN = int(Hidden / 10)
PN1 = int(Player_Number % 10)
RN1 = int(Hidden % 10)
if Jackpot:
print("Jackpot!!! You win 100 dollars!!!")
Jackpot_wins = int(Jackpot_wins + 1)
elif Player_Number == Reversed_digits:
print("Right digits, wrong order!... You win 10 dollars!")
Reversed_digits = int(Reversed_digits + 1)
elif PN == RN:
print("One digit correct, place correct. You win 10 dollars!")
Digit_RightPlacement = int(Digit_RightPlacement + 1)
elif RN1 == PN1:
print("One digit correct, place correct. You win 10 dollars!")
Digit_RightPlacement_two = int(Digit_RightPlacement_two + 1)
elif PN1 == RN:
print("One digit correct, place incorrect. You win 5 dollars!")
Digit_WrongPlacement = int(Digit_WrongPlacement + 1)
elif RN1 == PN:
print("One digit correct, place incorrect. You win 5 dollars!")
Digit_WrongPlacement_two = int(Digit_WrongPlacement_two + 1)
else:
print("Completely wrong")
Game_start = input("To continue type 'y' to end type anything: ")
JP_money = Jackpot_wins * JackpotValue
RD_money = Reversed_digits * Reversed_digitsValue
DRP_money = Digit_RightPlacement * Digit_RightPlacementValue
DRP1_money = Digit_RightPlacement_two * Digit_RightPlacementValue
DWP_money = Digit_WrongPlacement * Digit_WrongPlacementValue
DWP1_money = Digit_WrongPlacement_two * Digit_WrongPlacementValue
Winnings = JP_money + RD_money + DRP_money + DRP1_money + DWP_money + DWP1_money
Total_earnings = Winnings - Money_Spent
if Game_start != "y":
print("See you next time! You played ", count, "rounds.")
print("you spent $ ", Money_Spent)
print("Wow you won the Jackpot", Jackpot_wins, "times!")
print("Your total earnings are", Total_earnings, "Congrats!")
I expected the code to keep tally of the wins and their varying values but I am either getting a type error or a value that is unbelievable like 72727171723
Yes, I tested the code, in your Winning calculation RD_Money is returning string number,
Winnings = JP_money + RD_money + DRP_money + DRP1_money + DWP_money + DWP1_money
For resolving this you can just convert it in the calculation like this
Winnings = JP_money + int(RD_money) + DRP_money + DRP1_money + DWP_money + DWP1_money
or you can do this
RD_money = int(Reversed_digits) * Reversed_digitsValue
This will solve your problem
I'm trying to write a count function, to calculate the number of rolls it takes to hit 0. And it is returning me the random integer of the diceroll + 1, how do I get it to count the number of times the myroll variable occurs.
import random
def luckysevens():
mypot = int(input("Please enter the amount of money you want to in the pot: "))
while mypot > 0:
diceroll = random.randint(1, 6)
print(diceroll)
myroll = (diceroll + diceroll)
if myroll == 7:
mypot = mypot + 4
print("Your roll was a 7 you earned 4$", mypot)
else:
mypot = mypot - 1
print("Your roll was", myroll, "you lost 1$", mypot)
if mypot == 0:
print("Your out of money!")
sum = 0
for count in range(myroll + 1):
sum = sum + count
print(count)
luckysevens()
If you want to count how many rolls before the loop exits, simply add another counter variable. I also am assuming you're rolling a couple dice, so added different random calls for each one.
import random
mypot = int(input("Please enter the amount of money you want to in the pot: "))
num_rolls = 0
while mypot > 0:
die_1 = random.randint(1,6)
die_2 = random.randint(1,6)
myroll = die_1 + die_2
num_rolls += 1 # count rolls
if myroll == 7:
mypot = mypot + 4
print("Your roll was a 7 you earned 4$",mypot)
else:
mypot = mypot - 1
print("Your roll was",myroll,"you lost 1$",mypot)
if mypot == 0:
print("Your out of money!")
print 'Num rolls: {}'.format(num_rolls) # print rolls
I am trying to create a game where you choose how many players there will be, name those players, and then one player is chosen at random.
From there, that chosen player would pick a number in between 1 and 10 that they DON'T want to land on.
Then, the dice rolls and if they land on that number, everyone else gets to pick a dare for him/her. If it doesn't, the game just randomly picks another player and the process begins again.
The problem is though, the program doesn't get past the part where it asks you which number you don't want to land on. This is weird, as it works fine with one person.
Here is the full code, you are looking for line 23:
# Pass Or Dare
from random import randint
firsttry = True
def playerpicked(list):
listwords = len(list)
numpicked = randint(0, listwords - 1)
userpicked = list[numpicked]
return userpicked
while firsttry:
try:
playercount = int(input('How many players will there be?\n'))
except ValueError:
print("That isn't a number. Please enter a number without decimals.")
else:
firsttry = False
playernames = [input("Name of Player {}: ".format(i)) for i in range(1, playercount + 1)]
while True:
playerturn = playerpicked(playernames)
print("The Player picked is:",playerturn)
while True:
try:
darenum = int(input(playerturn + ", which number do you NOT want to land on?\n"))
except ValueError:
print("Please enter a number.")
else:
if darenum > 10 or darenum < 1:
print("Please enter a number between 1 and 10.\n")
else:
break
print("Okay. Rolling the dice...")
numpick = randint(1, 10)
print("The number chosen is " + str(numpick) + ".")
if numpick == darenum:
print("Whoops! The number you chose was the one that we landed on! Everyone agree on a dare for " + playerturn + "!\n\n")
input("Press Enter once " + playerturn + " has done a dare...\n")
else:
print(playerturn + " has escaped! Moving on to the next person.\n\n")
Here is a fast review of the algorithm, the problem was that the break you used while checking if the darenumber was between the desired range, causing to loop back again and never getting out of there.
Also, it's recommended that you check your control structure because it´s what made the problem.
Lastly, I strongly recommend an exit feature of your game because in some point in has to end. Hope it helps:
from random import randint
def playerpicked(list):
listwords = len(list)
numpicked = randint(0, listwords - 1)
userpicked = list[numpicked]
return userpicked
playercount = 0
while playercount < 1:
try:
playercount = int(input('How many players will there be?\n'))
except ValueError:
print("That isn't a number. Please enter a number without decimals.")
playernames = [input("Name of Player {}: ".format(i)) for i in range(1, playercount + 1)]
print("Press 0 while it's your turn to finish the game")
while True:
playerturn = playerpicked(playernames)
print("The Player picked is:",playerturn)
darenum = -1
while (darenum > 10 or darenum < 0):
try:
darenum = int(input(playerturn + ", which number do you NOT want to land on?\n"))
if darenum > 10 or darenum < 1:
print("Please enter a number between 1 and 10.\n")
except ValueError:
print("Please enter a number.")
if darenum == 0:
break
print("Okay. Rolling the dice...")
numpick = randint(1, 10)
print("The number chosen is " + str(numpick) + ".")
if numpick == darenum:
print("Whoops! The number you chose was the one that we landed on! Everyone agree on a dare for " + playerturn + "!\n\n")
input("Press Enter once " + playerturn + " has done a dare...\n")
else:
print(playerturn + " has escaped! Moving on to the next person.\n\n")
print("Game Over")
Your original code, with errors sinalization (read the code's comments):
# Pass Or Dare
from random import randint
firsttry = True
def playerpicked(list):
listwords = len(list)
numpicked = randint(0, listwords - 1)
userpicked = list[numpicked]
return userpicked
while firsttry:
try:
playercount = int(input('How many players will there be?\n'))
except ValueError:
print("That isn't a number. Please enter a number without decimals.")
else:
firsttry = False
playernames = [input("Name of Player {}: ".format(i)) for i in range(1, playercount + 1)]
while True:
playerturn = playerpicked(playernames)
print("The Player picked is:",playerturn)
while True:
try:
darenum = int(input(playerturn + ", which number do you NOT want to land on?\n"))
except ValueError:
print("Please enter a number.")
else: #there is no if for this else
if darenum > 10 or darenum < 1:
print("Please enter a number between 1 and 10.\n")
else:
break #this break would break the while True above
print("Okay. Rolling the dice...")
numpick = randint(1, 10)
print("The number chosen is " + str(numpick) + ".")
if numpick == darenum:
print("Whoops! The number you chose was the one that we landed on! Everyone agree on a dare for " + playerturn + "!\n\n")
input("Press Enter once " + playerturn + " has done a dare...\n")
else:
print(playerturn + " has escaped! Moving on to the next person.\n\n")
#there should be a break in here, otherwise the function would be stuck in the second while True
The fixed code, changing what I mentioned in the comments above:
# Pass Or Dare
from random import randint
firsttry = True
def playerpicked(list):
listwords = len(list)
numpicked = randint(0, listwords - 1)
userpicked = list[numpicked]
return userpicked
while firsttry:
try:
playercount = int(input('How many players will there be?\n'))
except ValueError:
print("That isn't a number. Please enter a number without decimals.")
else:
firsttry = False
playernames = [input("Name of Player {}: ".format(i)) for i in range(1, playercount + 1)]
while True:
playerturn = playerpicked(playernames)
print("The Player picked is:",playerturn)
while True:
try:
darenum = int(input(playerturn + ", which number do you NOT want to land on?\n"))
except ValueError:
print("Please enter a number.")
if darenum > 10 or darenum < 1:
print("Please enter a number between 1 and 10.\n")
else:
print("Okay. Rolling the dice...")
numpick = randint(1, 10)
print("The number chosen is " + str(numpick) + ".")
if numpick == darenum:
print("Whoops! The number you chose was the one that we landed on! Everyone agree on a dare for " + playerturn + "!\n\n")
input("Press Enter once " + playerturn + " has done a dare...\n")
else:
print(playerturn + " has escaped! Moving on to the next person.\n\n")
break