I wrote a program for math game which calculates score based on right answers. It will ask the user twice for the answer of a given question, if its correct it will add 10. However the score is not adding properly and I can't figure out why.
import random
def game():
l = ['*','+']
score = 0
for _ in range(2):
x = random.randint(1,5)
y = random.randint(1,5)
z = int(input("Enter the val of {} {} {} \n".format(x, random.choice(l), y)))
if random.choice(l) == '*':
o = x * y
elif random.choice(l) == '+':
o = x + y
if z == o:
score = score + 10
print(score)
return("Your score is {}".format(score))
game()
You need to remember your choice. Every time you call random.choice(l) it picks a new one:
import random
def game():
l = ['*','+']
score = 0
for _ in range(2):
choice = random.choice(l)
x = random.randint(1, 5)
y = random.randint(1, 5)
z = int(input("Enter the val of {} {} {} \n".format(x, choice, y)))
if choice == '*': # Here you chose something random
o = x * y
elif choice == '+': # and here you chose something random
o = x + y
if z == o:
score = score + 10
print(score)
return("Your score is {}".format(score))
print(game())
Also, a couple recommendations:
1) I would recommend using f-strings, it reads nicer:
z = int(input(f"Enter the val of {x} {choice} {y} \n".))
2) Use more meaningful variable names instead of x, y, z, and o.
Lastly an advanced tip. If you want to make this game more generic you can use the operator module. Then you can easily add more operations.
import random
import operator
def game():
operators = {
'*': operator.mul,
'+': operator.add,
'-': operator.sub,
}
score = 0
for _ in range(2):
choice = random.choice(list(operators.keys()))
x = random.randint(1, 5)
y = random.randint(1, 5)
user_answer = int(input(f"Enter the val of {x} {choice} {y} \n"))
actual_answer = operators[choice](x, y)
if user_answer == actual_answer:
score = score + 10
return("Your score is {}".format(score))
print(game())
Related
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 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 am currently learning python and decided to create a basic game HiLo. I've managed to code the basics but now I'd like to take it further and get the answers as a key press. At first I created a list with available answers as "h, l, etc." but now I'd the user to press UP ARROW KEY for high and DOWN ARROW KEY for low and check the answer is correct.
I've tried with msvcrt, keyboard and pyautogui modules but I could not seem to make it work.
import random
import pygame
from msvcrt import getch
name = input("Please enter your name: ")
print("Welcome {}".format(str(name)))
print(
"Okay {}. We will now play a game called high or low. In order to play this game you have to be 18 or older".format(
str(name)))
age = int(input("Please enter your age: "))
print(age)
if age < 18:
print("You are not old enough the play.")
exit
else:
print("OK! You are {}. You can play".format(str(age)))
x = random.randint(1, 9)
y = random.randint(1, 9)
print("Your first number is {}.".format(str(x)))
counter = 0
truecounter = 0
falsecounter = 0
while counter <= 10:
print("Press UP for high and DOWN for low.")
getch()
if and y > x: #If UP Arrow is pressed and Y is greater than X
truecounter += 1
print("Your answer is correct!. The other number was " + str(y))
x = random.randint(1, 9)
y = random.randint(1, 9)
print("Let's see if you can do it again. The number is")
print(x)
elif and y < x: #If DOWN Arrow is pressed and Y is smaller than X
truecounter += 1
print("Your answer is correct!. The other number was " + str(y))
x = random.randint(1, 9)
y = random.randint(1, 9)
print("Let's see if you can do it again. The number is")
print(x)
elif and y > x: #If DOWN ARROW is pressed and Y is greater than X
falsecounter += 1
print("Ooops! You guessed wrong. The number was " + str(y))
x = random.randint(1, 9)
y = random.randint(1, 9)
print("Let's see if you can do it again. The number is")
print(x)
elif and y < x: #If UP ARROW is pressend and Y is smaller than X
falsecounter += 1
print("Ooops! You guessed wrong. The number was " + str(y))
x = random.randint(1, 9)
y = random.randint(1, 9)
print("Let's see if you can do it again. The number is")
print(x)
counter += 1
print("Congrats! You got " + str(truecounter) + " out of 10!")
I expect that according to input of the user ( UP or DOWN arrow key) the code will check the numbers and add a point to true or false counter.
Here this works.
What are the problem with the keyboard libary?
import random
import keyboard
name = input("Please enter your name: ")
print("Welcome {}".format(str(name)))
print(
"Okay {}. We will now play a game called high or low. In order to play this game you have to be 18 or older".format(
str(name)))
age = int(input("Please enter your age: "))
print(age)
if age < 18:
print("You are not old enough the play.")
exit
else:
print("OK! You are {}. You can play".format(str(age)))
x = random.randint(1, 9)
y = random.randint(1, 9)
print("Your first number is {}.".format(str(x)))
counter = 0
truecounter = 0
falsecounter = 0
def check(key):
global UP_PRESS,DOWN_PRESS,run
if key.__dict__["event_type"] == "down":
DOWN_PRESS = True
run = True
elif key.__dict__["event_type"] == "up":
UP_PRESS = True
run = True
else:
raise KeyError("Not the right Key")
while counter <= 10:
print("Press UP for high and DOWN for low.")
UP_PRESS = False
DOWN_PRESS = False
run = False
while not run:
keyboard.unhook_all()
try:
event = keyboard.hook(check)
except:
print("ERROR: Press Arrow Up or Arrow Down")
print("\n")
if UP_PRESS and y > x: #If UP Arrow is pressed and Y is greater than X
truecounter += 1
print("Your answer is correct!. The other number was " + str(y))
x = random.randint(1, 9)
y = random.randint(1, 9)
print("Let's see if you can do it again. The number is")
print(x)
elif DOWN_PRESS and y < x: #If DOWN Arrow is pressed and Y is smaller than X
truecounter += 1
print("Your answer is correct!. The other number was " + str(y))
x = random.randint(1, 9)
y = random.randint(1, 9)
print("Let's see if you can do it again. The number is")
print(x)
else:
falsecounter += 1
print("Ooops! You guessed wrong. The number was " + str(y))
x = random.randint(1, 9)
y = random.randint(1, 9)
print("Let's see if you can do it again. The number is")
print(x)
counter += 1
print("Congrats! You got " + str(truecounter) + " out of 10!")
I'm having trouble because I'm asking the user to input 6 numbers into a list and then total and average it depending on input from user. It's my HWK. Please help.
x = 0
list = []
while x < 6:
user = int(input("Enter a number"))
list.append(user)
x = x + 1
numb = input("Do you want a total or average of numbers?")
numb1 = numb.lower
if numb1 == "total":
Here is my answer:
def numberTest():
global x, y, z
L1 = []
x = 0
y = 6
z = 1
while(x < 6):
try:
user = int(input("Enter {0} more number(s)".format(y)))
print("Your entered the number {0}".format(user))
x += 1
y -= 1
L1.append(user)
except ValueError:
print("That isn't a number please try again.")
while(z > 0):
numb = input("Type \"total\" for the total and \"average\"").lower()
if(numb == "total"):
a = sum(L1)
print("Your total is {0}".format(a))
z = 0
elif(numb == "average"):
b = sum(L1)/ len(L1)
print("Your average is {0}".format(round(b)))
z = 0
else:
print("Please try typing either \"total\" or \"average\".")
numberTest()
I tried this a couple of times and I know it works. If you are confused about parts of the code, I will add comments and answer further questions.
I have made a simple guessing color game.
The aim of the game is to try and guess the color that has been entered by game master.
I was wondering how to loop it, so that you were allowed a number of guesses, to guess what the game master entered.
Any help would be greatly appreciated
print"THIS IS GUESSING GAME""\n"
print"WELCOME""\n"
rsplay = "Q"
print"Game master, enter the colour that you want:"
colour1 = raw_input("")
colour2 = raw_input("")
colour3 = raw_input("")
colour4 = raw_input("")
print"colour set!""\n"
num_guess = raw_input("Set the number of guess:")
print ("\n" * 50)
playername = raw_input("Enter Your Name: ")
print "Hello" ,playername, "!" "\n" "You have<",num_guess, ">guesses to `enter the colors correctly in the order as" "\n" "how it being entered. Let's play."`
trial = 0
x = 0
y = 0
print"Enter guess number" ,trial, ":"
guess1 = raw_input("")
guess2 = raw_input("")
guess3 = raw_input("")
guess4 = raw_input("")
while trial < num_guess:
trial = trial + 1
if (guess1 == colour1):
x = x + 1
else :
if (guess2 == colour2):
x = x + 1
else :
if (guess3 == colour3):
x = x + 1
else :
if (guess4 == colour4):
x = x + 1
else:
if (guess1 == colour2):
y = y + 1
else :
if (guess1 == colour3):
y = y + 1
else :
if (guess1 == colour4):
y = y + 1
else :
if (guess2 == colour1):
y = y + 1
else :
if (guess2 == colour3):
y = y + 1
else :
if (guess2 == colour4):
y = y + 1
else :
if (guess3 == colour1):
y = y + 1
else :
if (guess3 == colour2):
y = y + 1
else :
if (guess3 == colour4):
y = y + 1
else :
if (guess4 == colour1):
y = y + 1
else :
if (guess4 == colour2):
y = y + 1
else :
if (guess4 == colour3):
y = y + 1
else:
print "You have" ,x, "CORRECT and" ,y, "MISSED" "\n"
print "You've won! Well done",playername,"! You Did it in",trial,"guesses." "\n"
print "Do You want to play again ?",rsplay,"\n"
if(rsplay == "Q"):
print "Bye..."
else :
if (rsplay == "P"):
print "Play Again"
You set:
num_guess = raw_input("Set the number of guess:")
Then you can do:
while num_guess > 0:
guess = raw_input("")
# game logic goes here
num_guess = num_guess - 1
Then the user will have exactly num_guess guesses, and you can keep count of how many correct guesses the user has made by setting count = 0 before the while, and incrementing (count = count + 1) it each time the user guesses correctly. In this case the number of wrong guesses will surely be the total number of guesses minus the correct ones (count).
As an added bonus, all your if statements will be much shorter since you won't have 4 variables for 4 guesses.