Hi all programming masters! Im working on a python guessing game and want to change the format of my print to file from "name: win 0: loss 0: guess 0", to "Name | Win or loss (not both) | number of guesses". Im not sure how to make it print the win OR loss, do i need another if statement to print to the txt file?
import random
print("Number guessing game")
name = input("Hello, please input your name: ")
win = 0
loss = 0
guesses = 0
diceRoll = random.randint(1, 6)
if diceRoll == 1:
print("You have 1 guess.")
if diceRoll == 2:
print("You have 2 guesses.")
if diceRoll == 3:
print("You have 3 guesses.")
if diceRoll == 4:
print("You have 4 guesses.")
if diceRoll == 5:
print("You have 5 guesses.")
if diceRoll == 6:
print("You have 6 guesses.")
elif diceRoll != 1 and diceRoll != 2 and diceRoll != 3 and diceRoll != 4 and diceRoll != 5 and
diceRoll != 6:
print("Invalid input!")
number = random.randint(1, 3)
chances = 0
print("Guess a number between 1 and 100:")
while chances < diceRoll:
guess = int(input())
if guess == number:
print("Congratulation YOU WON!!!")
win += 1
guesses = guesses + 1
break
elif guess < number:
print("Your guess was too low")
guesses = guesses + 1
else:
print("Your guess was too high")
guesses = guesses + 1
chances += 1
else:
print("YOU LOSE!!! The number is", number)
loss += 1
print(name)
print("win: "+str(win))
print("loss: "+str(loss))
stat = open("Statistics.txt", "a")
stat.write(name + ":" + " win: "+str(win) + " loss: " +str(loss) +" guesses: "+str(guesses)),
stat.close()
You can solve the critical part using the ternary statement, an "if-then-else" expression, like this:
result = "Win" if win == 1 else "Loss"
stat.write((name + ":" + result + " guesses: "+str(guesses))
Beyond this, I strongly recommend that you look up "Python output format", so you can improve your range of expression. You won't have to keep doing string construction for your output statements.
Related
I am having trouble finding a way to allow my Python project to accept a non-integer value and not crash. My intention is that when the user inputs a non-integer value or any value other than the ones assigned by the random sampkle, the game will prompt the function "repeatr()" which will tell them to input the value again.
I've put in the entire solution, but the most relevant sections are in bold and it's that particular section that I want to allow to prompt the repeatr() function instead of crashing
import random
user_wins = 0
user_draws = 0
user_losses = 0
rounds = 0
def closr():
quit()
def repeatr():
print("That is not a valid input. Please input a correct value.")
**def promptr():
print("Please select an input from the following options.")**
options = [5, 4, 3, 2, 1]
randomlist = random.sample(range(1, 5), 3)
randomr = randomlist
x=1
while x == 1:
user_input = int(input("Type 5/4/3/2/1 or Q to quit."))
if user_input in options:
x=2
elif user_input != options:
repeatr()
continue
elif user_input == "q":
closr()
**y=1
while rounds < 10:
promptr()
player_choice = int(input(randomlist))
npc = random.randint(1,5)
if player_choice in randomr:
print("Your opponent has drawn: ", npc)
y=2
else:
repeatr()
continue**
if npc > int(player_choice):
print("You have been defeated this round.")
user_losses = user_losses + 1
print("The score is:" , user_wins , ":" , user_losses)
rounds = rounds + 1
elif npc < player_choice:
print ("You have won this round.")
user_wins = user_wins + 1
print ("The score is:" , user_wins , ":" , user_losses)
rounds = rounds + 1
elif npc == player_choice:
print ("You have drawn this round.")
user_draws = user_draws + 1
print ("The score is:" , user_wins , ":" , user_losses)
rounds = rounds + 1
rounds = 10
if user_losses < user_wins:
print("You have won the game!")
elif user_losses > user_wins:
print("You have lost this game. Better luck next time!")
elif user_losses == user_wins:
print("The game has ended in a draw.")
print("the number of wins you had was:" , user_wins)
print("the number of draws you had was:" , user_draws)
print("the number of losses you had was:" , user_losses)
print("The final score was (Player vs CPU):" , user_wins, ":" , user_losses)
u=1
while u == 1:
resu=input("Press Q to quit the game.")
if resu=="q":
closr()
I hope the question makes sense.
Heres the copy of my code :) this game is part of my personal activity.
so after purchasing a clue (from: def game_hints) i want to return to def Game_process.
import random
SCORE = 0
ROUNDS = 1
def player_stats():
print(f"SCORE: {SCORE} | ROUNDS: {ROUNDS}")
def game_hints(USER_GUESS, Mystery_NUM):
print("Would you like purchase a hint for 5 points? [1/2]: ")
USER_HINT = int(input())
global SCORE
if USER_HINT == 1:
SCORE= SCORE - 5
if USER_GUESS > Mystery_NUM and Mystery_NUM % 2 == 0:
print("Mystery Num is even and try a smaller guess")
elif USER_GUESS > Mystery_NUM and Mystery_NUM % 2 == 1:
print("Mystery Num is odd and try a smaller guess")
elif USER_GUESS < Mystery_NUM and Mystery_NUM % 2 == 0:
print("Secret Num is even and try a larger guess")
elif USER_GUESS < Mystery_NUM and Mystery_NUM % 2 == 1:
print("Mystery Num is odd and try a larger guess")
def Game_Process():
global ROUNDS
while True:
if ROUNDS <= 10:
Mystery_NUM = random.randrange(10)
print(Mystery_NUM) #remove before final product
print("Guess the num [1-10]: ")
USER_GUESS = int(input())
if USER_GUESS == Mystery_NUM:
print("\nGood Job! +5 Coins!")
global SCORE
SCORE = SCORE + 10
ROUNDS += 1
player_stats()
else:
print("Wrong! Try Again")
game_hints(USER_GUESS, Mystery_NUM)
else:
print("Game Over!")
Game()
def Game():
user_opt = input("\"Welcome to Guess Game\" \nPress [Y] to Play or [N] to Exit: ").lower()
if user_opt == "n":
print("Good bye!")
exit()
elif user_opt == "y":
Game_Process()
else:
print("Invalid Input! [1/2]")
Game()
Game()
As shown below, this is the fuction for the hints. I was able to call this function but the only problem is that the after this fuction is done, it changes the Myster_Num.
def game_hints(USER_GUESS, Mystery_NUM):
print("Would you like purchase a hint for 5 points? [1/2]: ")
USER_HINT = int(input())
global SCORE
if USER_HINT == 1:
SCORE= SCORE - 5
if USER_GUESS > Mystery_NUM and Mystery_NUM % 2 == 0:
print("Secret Num is even and try a smaller guess")
elif USER_GUESS > Mystery_NUM and Mystery_NUM % 2 == 1:
print("Secret Num is odd and try a smaller guess")
elif USER_GUESS < Mystery_NUM and Mystery_NUM % 2 == 0:
print("Secret Num is even and try a larger guess")
elif USER_GUESS < Mystery_NUM and Mystery_NUM % 2 == 1:
print("Mystery Num is odd and try a larger guess")
First, you must remove the else statement in the game_hints function because it restarts a full GameProcess and therefore indeed recompute a mysterious number.
Then, when you exit game_hints and come back to GameProcess, you must not come back to the big loop because it will indeed recompute a mysterious number. The solution is to have an inner loop inside each round that you exit only if the player guessed the correct value using the break keyword.
def Game_Process():
SCORE = 0
ROUNDS = 1
while True:
if ROUNDS <= 10:
Mystery_NUM = random.randrange(10)
print(Mystery_NUM) # remove before final product
while True:
print("Guess the num [1-10]: ")
USER_GUESS = int(input())
if USER_GUESS == Mystery_NUM:
print("\nGood Job! +5 Coins!")
SCORE = SCORE + 10
ROUNDS += 1
player_stats()
break
else:
print("Wrong! Try Again")
game_hints(USER_GUESS, Mystery_NUM)
else:
print("Game Over!")
Game()
I am trying to write a program to play 100 games of Craps and print out the overall results. I have an infinite loop at the end of my code.
Does anyone see the problem?
I assume my 2nd function could be calling diceRoll again for secondRoll. Trying that now...
Specs:
The player must roll two six-side dice and add the total of both
dice.
The player will win on the first roll if they get a total of 7 or 11
The player will lose on the first roll if they get a total of 2, 3,
or 12
If they get any other result (4, 5, 6, 8, 9, 10), they must roll
again until they either match their first roll (a win) or get a
result of 7 (a loss)
Use at least two functions in your program
from random import randrange as rd
winTuple = 7, 11
lossTuple = 2, 3, 12
wins = 0
losses = 0
x = 1
def diceRoll (number, type = 6):
result = 0
for i in range(number):
result += rd(1, type +1)
return result
while x < 101:
firstRoll = diceRoll(2)
if firstRoll in winTuple:
wins += 1
elif firstRoll in lossTuple:
losses += 1
else:
secondRoll = diceRoll(2)
while secondRoll != 7 or secondRoll != firstRoll:
if secondRoll == 7:
wins += 1
elif secondRoll == firstRoll:
wins += 1
else:
secondRoll = diceRoll(2)
x += 1
print("wins: ", wins)
print("losses: ", losses)
Looks like you need to eliminate your inner loop. First, the loop conditions are in direct conflict with your conditional statements, so the loop never exits. Second, why would you want a loop here? Even if you fixed it, all it would do is keep rolling the second dice until a win is scored.
while x < 101:
firstRoll = diceRoll(2)
if firstRoll in winTuple:
wins += 1
elif firstRoll in lossTuple:
losses += 1
else:
secondRoll = diceRoll(2)
if secondRoll == 7 or secondRoll == firstRoll:
wins += 1
x += 1
In response to your comment, this is how you create your second loop. You make an infinite loop with while True and break out of it when the conditions are met.
while x < 101:
firstRoll = diceRoll(2)
if firstRoll in winTuple:
wins += 1
elif firstRoll in lossTuple:
losses += 1
else:
while True:
secondRoll = diceRoll(2)
if secondRoll == 7:
losses += 1
break
elif secondRoll == firstRoll:
wins += 1
break
x += 1
If your firstRoll != 7 (let's say firstRoll = 8) then your script cannot exit the second nested loop because either secondRoll != 7 or secondRoll = 7 and therefore firstRoll != secondRoll (7 != 8)
I am not sure how your program goes through 100 games of craps, here is an example of a program I wrote quick that goes through 100 games. Games being times you either hit or don't hit the point.
Clearly you need to understand how craps works to make something like this, so I am assuming you do. The program you were trying to write, even though you were stuck in the loop, was not actually playing a full game of craps.
You can choose the amount of games you want and the only thing it stores is if you won or lost.
You can add other statistics if you would like, for example points hit and which points they were etc.,
I added text to, also, make it user friendly if this is for a school project.
There are many different ways to do this, I used a main while loop and created two functions for whether the button is on or off.
You could obviously condense this, or write a class instead but I simply put this together quick to give you an idea and see how it goes through every loop and statement.
I am still a novice, so I apologize to anyone else reading, I know the below is not the most efficient/does not perfectly follow PEP8 especially the long if statement in the main loop.
This does perform what you wanted and feel free to change the number of games. Enjoy!
import random
wins = 0
losses = 0
gamenum = 0
#Used a list to pull the dice numbers from but not mandatory
dicenum = [2,3,4,5,6,7,8,9,10,11,12]
#Function when point is off
def roll_off():
#Random roll from list
roll = random.choice(dicenum)
if roll == 2:
print("2 craps")
elif roll == 3:
print("3 craps")
elif roll == 4:
print("Point is 4")
return(4)
elif roll == 5:
print("Point is 5")
return(5)
elif roll == 6:
print("Point is 6")
return(6)
elif roll == 7:
print("Winner 7")
elif roll == 8:
print("Point is 8")
return(8)
elif roll == 9:
print("Point is 9")
return(9)
elif roll == 10:
print("Point is 10")
return(10)
elif roll == 11:
print("Yo 11")
elif roll == 12:
print("12 craps")
#Function when point is on
def roll_on(x):
#Random roll from list
roll = random.choice(dicenum)
if roll == 2:
print("2 craps")
elif roll == 3:
print("3 craps")
elif roll == 4:
print("You rolled a 4")
elif roll == 5:
print("You rolled a 5")
elif roll == 6:
print("You rolled a 6")
elif roll == 7:
print("7 out")
elif roll == 8:
print("You rolled a 8")
elif roll == 9:
print("You rolled a 9")
elif roll == 10:
print("You rolled a 10")
elif roll == 11:
print("Yo 11")
elif roll == 12:
print("12 craps")
#Check if you hit the point
if x == 4 and roll == 4:
print("You win!")
return (True)
elif x == 5 and roll == 5:
print("You win!")
return (True)
elif x == 6 and roll == 6:
print("You win!")
return (True)
elif x == 7 and roll == 7:
print("You win!")
return (True)
elif x == 8 and roll == 8:
print("You win!")
return (True)
elif x == 9 and roll == 9:
print("You win!")
return (True)
elif x == 10 and roll == 10:
print("You win!")
return (True)
#Check if you 7'ed out
if roll == 7:
print("You lose!")
return (False)
#Main game, change the amount of games you want to play
while gamenum < 100:
diceresult = roll_off()
#If statement to check the point
if diceresult == 4 or diceresult == 5 or diceresult == 6 or diceresult == 8 or diceresult == 9 or diceresult == 10:
active = True
print("The point is on!")
while active == True:
curentstate = roll_on(diceresult)
if curentstate == False:
gamenum += 1
losses += 1
print("------------")
print("Games:", gamenum)
print("Losses:", losses)
print("Wins:", wins)
print("------------")
break
elif curentstate == True:
gamenum += 1
wins += 1
print("------------")
print("Games:", gamenum)
print("Losses:", losses)
print("Wins:", wins)
print("------------")
break
It is a Snake Water Gun Game in python
But My score is not counting
What is the problem
import random
Importing Random Module
chance = 1
human_point = 0
computer_point = 0
print("s for snake , w for water , g for gun ; you can use both uppercase or lowercase characters")
while (chance <= 10):
lst=["s","w","g"]
computer_choice=random.choice(lst)
human_point = 0
computer_point = 0
usr = input("Snake, Water & Gun : ")
usr = usr.lower()
if usr == computer_choice:
print("Tie\nNobody get points")
elif usr == "s" and computer_choice=="w":
print("You Win!")
human_point = human_point + 1
print(f"You Choosed {usr} Computer Choosed {computer_choice} ")
elif usr == "s" and computer_choice=="g":
print("You Loose")
computer_point = computer_point + 1
print(f"You Choosed {usr} Computer Choosed {computer_choice} ")
elif usr == "w" and computer_choice=="g":
print("You Win!")
human_point = human_point + 1
print(f"You Choosed {usr} Computer Choosed {computer_choice} ")
elif usr == "w" and computer_choice=="s":
print("You Loose")
computer_point = computer_point + 1
print(f"You Choosed {usr} Computer Choosed {computer_choice} ")
elif usr == "g" and computer_choice=="s":
print("You Win!")
human_point = human_point + 1
print(f"You Choosed {usr} Computer Choosed {computer_choice} ")
elif usr == "g" and computer_choice=="w":
print("You Loose")
computer_point = computer_point + 1
print(f"You Choosed {usr} Computer Choosed {computer_choice} ")
else:
print("Invalid Input")
continue
if attempts>10:
print("Game Over!")
print("No. of guesses left: {}".format(10 - chance))
chance = chance + 1
if computer_point < human_point:
print("All Over You Win! And Computer Loose")
print(f"Your score: {human_point} \nComputer's score: {computer_point}")
elif computer_point > human_point:
print("All Over Computer Win! And You Loose")
print(f"Your score: {human_point} \nComputer's score: {computer_point}")
else:
print("It Was A Tie")
print(10 - chance, "no. of guesses left")
chance = chance + 1
But if computer wins the computer score = 1 and my score = 0 and if I win then my score = 1 and computer score = 0
Why it is not counting score
Please Suggest me the answer What I am doing wrong
Please Help
You set the score of both you and your computer to 0 at the beginning of your while loop. This would mean that for every iteration, your scores will be 0 so when you do a command such as: computer_point = computer_point + 1 or player_point = player_point + 1, those statements will always evaluate to 0 + 1, hence why it doesn't actually "update"
you repeated human_point = 0, computer_point = 0 code under while.
you should probably erase that part
human_point = 0
computer_point = 0
print("s for snake , w for water , g for gun ; you can use both uppercase or lowercase characters")
while (chance <= 10):
lst=["s","w","g"]
computer_choice=random.choice(lst)
human_point = 0 <- erase this part
computer_point = 0 <- erase this part
Here's the full code you'll need. I removed chance = chance +1 repeating twice and updated the logic to only display the final result if chance = 10. Finally, I moved the human_point = 0 and computer_point = 0 to above the while loop so you don't constantly reset the score.
import random
chance = 1
human_point = 0
computer_point = 0
print("s for snake , w for water , g for gun ; you can use both uppercase or lowercase characters")
while (chance <= 10):
lst=["s","w","g"]
computer_choice=random.choice(lst)
usr = input("Snake, Water & Gun : ")
usr = usr.lower()
if usr == computer_choice:
print("Tie\nNobody get points")
elif usr == "s" and computer_choice=="w":
print("You Win!")
human_point = human_point + 1
print(f"You Choosed {usr} Computer Choosed {computer_choice} ")
elif usr == "s" and computer_choice=="g":
print("You Loose")
computer_point = computer_point + 1
print(f"You Choosed {usr} Computer Choosed {computer_choice} ")
elif usr == "w" and computer_choice=="g":
print("You Win!")
human_point = human_point + 1
print(f"You Choosed {usr} Computer Choosed {computer_choice} ")
elif usr == "w" and computer_choice=="s":
print("You Loose")
computer_point = computer_point + 1
print(f"You Choosed {usr} Computer Choosed {computer_choice} ")
elif usr == "g" and computer_choice=="s":
print("You Win!")
human_point = human_point + 1
print(f"You Choosed {usr} Computer Choosed {computer_choice} ")
elif usr == "g" and computer_choice=="w":
print("You Loose")
computer_point = computer_point + 1
print(f"You Choosed {usr} Computer Choosed {computer_choice} ")
else:
print("Invalid Input")
continue
if attempts>10:
print("Game Over!")
print("No. of guesses left: {}".format(10 - chance))
chance = chance + 1
if chance == 10 and computer_point < human_point:
print("All Over You Win! And Computer Loose")
print(f"Your score: {human_point} \nComputer's score: {computer_point}")
elif chance == 10 and computer_point > human_point:
print("All Over Computer Win! And You Loose")
print(f"Your score: {human_point} \nComputer's score: {computer_point}")
elif chance == 10 and computer_point == human_point:
print("It Was A Tie")
print(10 - chance, "no. of guesses left")
Code:
import random
score = 0
score2 = 0
guess = 0 #Defining Variables
quiz = 0
lives = 3
print('''Would you like to play a 'Guess the number' or a '3 round quiz'?
For Guess the number enter '1', for 3 round quiz enter '2' ''')
game = input()
if game == ("1"):
guess = guess + 1
print("Ok, time to start") #Asking what game you want to play
elif game == ("2"):
quiz = quiz + 1
else:
print("Please answer with 'Guess the number game' or a '3 round quiz'")
if quiz == 1:
print("Would you like to play 'Easy' or 'Hard'?")
difi = input()
if difi == ("Easy"):
print("Ok, let's go!") #Choosing difficulty
score = score + 1
elif difi == ("Hard"):
print("Ok,let's go")
score2 = score2 + 1
else:
print("Please answer with 'Easy' or 'Hard'")
if score == 1:
num1 = (random.randint(1, 50))
num2 = (random.randint(1, 50))
print("First question")
print("What is ",num1,"+",num2) # Question 1 easy
ans1 = input()
ans1 = int(ans1)
if ans1 == num1+num2:
print("Well done")
score = score + 1
else:
print("Unlucky, it was ",num1+num2)
if score == 2:
num3 = (random.randint(1, 10))
num4 = (random.randint(1, 10))
print("Next question")
print("What is ",num3,"*",num4) # Question 2 easy
ans2 = input()
ans2 = int(ans2)
if ans2 == num3*num4:
print("Congratualtions, on to the last question")
score = score + 1
else:
print("Unlucky, it was ",num3*num4)
if score == 3:
num5 = (random.randint(1, 5))
num6 = (random.randint(1, 2))
print("What is ",num5,"**(To the power of)",num6) # Question 3 easy
ans3 = input()
ans3 = int(ans3)
if ans3 == num5**num6:
print("Congratualtions, you beat the game on easy")
print("Now try hard!")
score = score + 1
else:
print("Unlucky, it was ",num5**num6)
if score == 4:
print("Would you like to try hard?")
hard2 = input()
else:
print("Ok, come back later") # If you beat easy you can choose to play hard here
if hard2 == ("Yes"):
print("This is the hard game, good luck!")
score2 = score2 + 1
elif hard2 == ("No"):
print("Ok, see you soon")
else:
print("Please answer with 'Yes' or 'No'")
if score2 == 1:
num12 = (random.randint(1, 500))
num22 = (random.randint(1, 500))
print("First question")
print("What is ",num12,"+",num22) # Question 1 hard
ans12 = input()
ans12 = int(ans12)
if ans12 == num12+num22:
print("Well done")
score2 = score2 + 1
else:
print("Unlucky, it was ",num1+num2) #2s in front of all hard variables so it differentiates the variables #From Easy and Hard
if score2 == 2:
num32 = (random.randint(1, 25))
num42 = (random.randint(1, 25))
print("Next question")
print("What is ",num32,"*",num42) # Question 2 hard
ans22 = input()
ans22 = int(ans22)
if ans22 == num32*num42:
print("Congratulations, on to the last question")
score2 = score2 + 1
else:
print("Unlucky, it was ",num32*num42)
if score2 == 3:
num52 = (random.randint(1, 15))
num62 = (random.randint(1, 3))
print("What is ",num52,"**(To the power of)",num62) # Question 3 hard
ans32 = input()
ans32 = int(ans32)
if ans32 == num52**num62:
print("Congratualtions, you beat the game on hard")
else:
print("Unlucky, it was ",num52**num62)
if guess == 1:
print("Time to play") #Guess the number game
guess = guess + 1
if guess == 2:
print("Pick a number between 1 an 10")
comp_num = (random.randint(1,10))
user_guess1 = input()
user_guess1 = int(user_guess1)
if user_guess1 == comp_num:
print("Well done, you beat the game on your first turn!")
else:
print("Unlucky you still have 2 more goes")
lives = lives - 1
if lives == 2:
print("Guess again")
user_guess2 = input()
user_guess2 = int(user_guess2)
if user_guess2 == comp_num:
print("Congrats, you beat it on your second guess!")
lives = lives - 1
if lives == 1:
print("Guess again")
user_guess3 = input()
user_guess3 = int(user_guess3)
if user_guess3 == comp_num:
print("Congrats, you beat it on your last life!")
lives = lives - 1
else:
print("Unlucky, care to try again")
if lives == 0:
retry = input()
if retry == ("Yes"):
lives = lives + 3
elif retry == ("No"):
print("Ok, come back soon")
else:
print("Please answer with 'Yes' or 'No'")
Error:
Traceback (most recent call last):
File "C:\Users\Boys\Desktop\3 Round Quiz.py", line 24, in <module>
if difi == ("Easy"):
NameError: name 'difi' is not defined
The error above comes up when I enter '1' to play the game 'Guess the number' it comes up with that, even though the variable difi is for the quiz. I'm not sure why this happens so any help will be appreciated!
Thanks
difi is only ever bound if quiz is 1:
if quiz == 1:
print("Would you like to play 'Easy' or 'Hard'?")
difi = input()
You don't set difi otherwise, and the name is not defined in that case.
quiz starts at 0, and isn't incremented unless you pick '2':
elif game == ("2"):
quiz = quiz + 1
If you pick '1', on the other hand, quiz remains at 0, difi is not set, and your code breaks.
The control flow is reaching the if difi == ("Easy"): line before difi is defined because quiz is still 0 at the top. I suspect you intended the if difi == ("Easy"): and associated parts of the code to be indented more so they appear inside the if quiz == 1: block.