Python: player input using for loops? - python

I am trying to make a guessing game in python 3 using jupyter notebook whereby two people take turns to guess a number between 1 and 10. What I don't want is that the answer is immediately given like this:
from random import randint
rand_num = randint(1,10)
players = ['player_1', 'player_2']
for player in players:
player_input = int(input('What is your guess {}? '.format(player)))
if player_input == rand_num:
print('You won!')
else:
print('You lost!')
print('The random number was: {}'.format(rand_num))
Instead I want everyone to guess and then the answer is given so that everyone has a fair chance at guessing the number. I tried the following here but this doesn't seem to work because I think the player_input doesn't account for every single player. So when one player got the number right, python prints that every player got the number right.
from random import randint
rand_num = randint(1,10)
players = ['player_1', 'player_2']
for player in players:
player_input = int(input('What is your guess {}? '.format(player)))
for player in players:
if player_input == rand_num:
print('You won {}!'.format(player))
else:
print('You lost {}!'.format(player))
print('The random number was: {}'.format(rand_num))
How can I make this work using lists and for loops?

Loops are probably not suitable for what you want to achieve, you better go with simple case selection by storing the answers of both players:
from random import randint
rand_num = randint(1,10)
players = ['player_1', 'player_2']
player_inputs = []
for player in players:
player_input = int(input('What is your guess {}? '.format(player)))
player_inputs.append(player_input)
if rand_num in player_inputs:
if player_inputs[0] == player_inputs[1]:
print('You both won!')
elif player_inputs[0] == rand_num:
print('You won {}!'.format(players[0]))
print('You lost {}!'.format(players[1]))
elif player_inputs[1] == rand_num:
print('You won {}!'.format(players[1]))
print('You lost {}!'.format(players[0]))
else:
print('You both lost')
print('The random number was: {}'.format(rand_num))

Related

I tried adding a simple play again feature to my guessing game

I tried to add a do you want to play again feature to my guessing game and it stopped working :( pls help. Im very new to python so i bet i have done many oblivious mistakes :S
import random
n = random.randint(1, 100)
play_game = input("Do you want to play ? Y/N :")
play_game = play_game.upper()
print("play_game")
while play_game == 'Y':
guess = int(input("Guess a number between 1 och 100: "))
while n != "gissning":
if guess < n:
print("You guessed to low")
guess = int(input("Guess a number between 1 och 100: "))
elif guess > n:
print ("You guessed to high")
guess = int(input("Guess a number between 1 och 100: "))
else:
print("Gratz you guessed it")
break
while play_game == 'Y':
# your game
play_game = input("Do you want to play again? Y/N :").upper()
Actually there are a few little problems in your code, but with a bit of logic you can figure it out.
First, you don't want three separated while loops, since when you quit one you'll never reach it again unless you restart your code. You actually want nested loops. The outer one will verify if the user wants to play again, while the inner one will keep asking guesses until it matches the random number.
And second, you want to compare n, the random number, to guess, the user's input. In your code you're comparing n != "gissning", which will never be true since n is a number and "gissning", a string.
With that in mind you can change your code a little bit and have something like:
import random
print("play_game")
play_game = input("Do you want to play ? Y/N :").upper()
highscore = 0
while play_game == 'Y':
n = random.randint(1, 100)
guess = int(input("Guess a number between 1 och 100: "))
score = 1
while n != guess:
if guess < n:
print("You guessed to low")
elif guess > n:
print("You guessed to high")
guess = int(input("Guess a number between 1 och 100: "))
score += 1
else:
print("Gratz you guessed it")
highscore = score if score < highscore or highscore == 0 else highscore
print('Your score this turn was', score)
print('Your highscore is', highscore)
play_game = input("Do you want to play again? Y/N :").upper()
Hope this helps you out. Good luck in your Python journey! Let us know if you have any further questions.
The next input prompt should be inside the outer-while loop. You also need to print the "Gratz you guessed it" along with the prompt and outside the inner-while loop when it's already n == guess.
import random
play_game = input("Do you want to play ? Y/N :")
play_game = play_game.upper()
while play_game == 'Y':
print("play_game")
n = random.randint(1, 100)
guess = int(input("Guess a number between 1 och 100: "))
while n != guess:
if guess < n:
print("You guessed to low")
guess = int(input("Guess a number between 1 och 100: "))
elif guess > n:
print ("You guessed to high")
guess = int(input("Guess a number between 1 och 100: "))
print("Gratz you guessed it")
play_game = input("Do you want to play ? Y/N :")
play_game = play_game.upper()

Dice rolling game in python

I am completely new to coding and trying to write somewhat of a dice rolling program/game.
I want the program to ask how many dice the user wants to roll, and how many times they can "retry" to roll the dice per one game. After the user has rolled all of their tries the program jumps back to the first question.
So this is what i´ve got so far:
import random
def roll(dice):
i = 0
while i < dice:
roll_result = random.randint(1, 6)
i += 1
print("You got:", roll_result)
def main():
rolling = True
while rolling:
answer = input("To throw the dice press Y if you want to stop press any key")
if answer.lower() == "Y" or answer.lower() == "y":
number_of_die = int(input("How many dice do you want to throw? "))
roll(number_of_die)
else:
print("Thank you for playing!")
break
main()
This works but i am not sure though where to begin to make the program ask for how many tries one player gets per game so that if they are unhappy with the result they can roll again.
Been trying for a while to figure it out so appreciate any tips!
Here's a simpler approach-
from random import randint
def roll(n):
for i in range(n):
print(f"You got {randint(1, 6)}")
def main():
tries = int(input("Enter the number of tries each player gets: "))
dice = int(input("How many dice do you want to roll? "))
for j in range(tries):
roll(dice)
roll_again = input("Enter 'y' to roll again or anything else to quit: ")
if roll_again.lower() != 'y':
break
main()

Two Player Number Guessing Game - Python

I am trying to write a game where Player One picks a number and Player Two has 5 Guesses to guess it. If he manages to do so, he wins, if not, he losses and Player One wins.
So I have the code, but if for example Player one picks the number '3' and Player Two enters the number '3' on any of his goes, it still says Player One wins.
>>>
Player One enter you chosen number: 3
Player Two have a guess: 3
Player One wins.
>>>
This happens also:
>>>
Player One enter you chosen number: 5
Player Two wins.
Also, player two can have as many turns as he likes, but it should only be 5. If he passes that amount, Player One automatically wins. Here is my code: (I don't know here I went wrong.)
def Game():
Guess = 0
NumberOfGuesses = 0
NumberToGuess = int(input("Player One enter you chosen number: "))
while NumberToGuess < 1 or NumberToGuess > 10:
NumberToGuess = int(input("Not a valid choice, please enter another number: "))
while Guess != NumberToGuess and NumberOfGuesses < 5:
Guess = int(input("Player Two have a guess: "))
NumberOfGuesses = NumberOfGuesses + 1
if Guess == NumberToGuess:
print("Player One wins.")
else:
print("Player Two wins.")
Game()
Your if statement is the wrong way around.
Instead of
if Guess == NumberToGuess:
print("Player One wins.")
else:
print("Player Two wins.")
it should be
if Guess == NumberToGuess:
print("Player Two wins.")
else:
print("Player One wins.")
because player 2 wins if he guesses the number that player 1 has chosen (NumberToGuess).
I cannot reconstruct your second problem where player 2 wins immediately of player 1 enters 5. It works fine for me.
The logic is wrong. If the input is not equal to NumberToGuess then you cannot print Player Two wins.
You must then loop. Then outside the loop check if player one was successful.
while Guess != NumberToGuess and NumberOfGuesses < 5:
Guess = int(input("Player Two have a guess: "))
NumberOfGuesses = NumberOfGuesses + 1
if Guess == NumberToGuess:
print("Player Two wins.")
if Guess != NumberToGuess:
print("Player One wins.")
"""This game generates random number, then players try to guess the number generated"""
import random
#generate number directly
num = random.randrange(1,5)
#initialize global variables
player1 = "Human"
player2 = "Alien"
player = ""
player1PlayCount = 0
player2PlayCount = 0
maxPlayTimes = 3
#game logic
def Game():
global player1, player2, player, player1PlayCount, player2PlayCount, maxPlayTimes, num
"""enter and assign names to players"""
player1Name = input('Player1 Enter Your Name: ')
player2Name = input('Player2 Enter Your Name: ')
player1 = player1Name
player2 = player2Name
player = player1
print(player1, 'turn')
while ((player1PlayCount and player2PlayCount) != maxPlayTimes):
guessNum = int(input("Guess Number: "))
if guessNum == num:
print(player, "won")
exit()
elif player == player1:
player1PlayCount +=1
player = player2
print(player2, 'turn')
elif player == player2:
player2PlayCount +=1
player = player1
print(player1, 'turn')
else:
print("Both ", player1, " and ", player2, " lose")
exit()
Game()

Adding scoring system to a number guessing game including play again

I have my game working fine now but I still want to take it further. I want to have a point scoring system included. I want the player to score 5 points if they have 1 live left when they win, 10 if they have 2 and 15 if they have all 3. But I don't want the score to be reset if they play again I just want it to say when the quit the game you have scored " " points. I have tried to do this in many different ways but I can seem to get it work it resets the score every time press y on the play again. I've included my base game code below please try and help. Any other recomendations for this game are very welcome.
**My apologies I don't know if I made this clear enough before. I don't want the score to be stored after the programs closed just until the player presses n when asked to play again **
#imports required modules
import random
#correct number variable created
num = 0
#generates number at random
comp_num = random.randint(1,10)
print('I\'m thinking of a number guess what it is...\n')
#main game code
def main():
#generates number at random
comp_num = random.randint(1,10)
#set num as a global variable
global num
#lives created
lives = 3
while lives >= 1:
#player guesses
guess = int(input('Guess: '))
if comp_num == guess:
#if correct says well done
print('\nWell Done! You guessed Correctly!\n')
break
elif comp_num >= guess:
#if guess is too low tells player
#one live taken for incorrect guess
lives = lives -1
print('\nToo low!\n')
#player is told how many lives they have left
print('You guessed incorrectly. You have',lives,'live(s) remaining.\n')
if lives == 0:
#if player guesses incorrectly they get told the correct awnser
print('The number I was thinking of was...',comp_num,'!\n')
elif comp_num <= guess:
#if guess is too high tells player
#one live taken for incorrect guess
lives = lives -1
print('\nToo high!\n')
#player is told how many lives they have left
print('You guessed incorrectly. You have',lives,'live(s) remaining.\n')
if lives == 0:
#if player guesses incorrectly they get told the correct awnser
print('The number I was thinking of was...',comp_num,'!\n')
def end():
#asks player if they want to play again
play_again = input('Would you like to play again?[Y/N] ')
while play_again.lower() == 'y':
#if they do game resets and plays again
if play_again.lower() == 'y':
comp_num = random.randint(1,10)
print('\nI\'m thinking of a number guess what it is...\n')
main()
play_again = input('Would you like to play again?[Y/N] ')
if play_again.lower() == 'n':
break
if play_again.lower() == 'n':
#if they don't game ends
input('Ok, Press enter to exit')
exit()
#calls main section of game
main()
#calls end of game to give option of playing again and reseting game
end()
Use this pattern:
def game(): # Play a single game.
lives = 3
...
return 5 * lives # Return the score of the game.
def ask_again():
print 'Play again?'
answer = ...
return answer == 'y' # Return True iff the user wants to play again.
def main():
score = game()
while ask_again():
score += game()
print score
main()
You should use global variable for storing the amount of scored points.
So I added code for adding points and printing the message:
#imports required modules
import random
#correct number variable created
num = 0
score = 0
#generates number at random
comp_num = random.randint(1,10)
print('I\'m thinking of a number guess what it is...\n')
#main game code
def main():
#generates number at random
comp_num = random.randint(1,10)
#set num as a global variable
global num
global score
#lives created
lives = 3
while lives >= 1:
#player guesses
guess = int(input('Guess: '))
if comp_num == guess:
#if correct says well done
print('\nWell Done! You guessed Correctly!\n')
# add score
if lives == 3:
score += 15
elif lives == 2:
score += 10
elif lives == 1:
score += 5
break
elif comp_num >= guess:
#if guess is too low tells player
#one live taken for incorrect guess
lives -= 1
print('\nToo low!\n')
#player is told how many lives they have left
print('You guessed incorrectly. You have',lives,'live(s) remaining.\n')
if lives == 0:
#if player guesses incorrectly they get told the correct awnser
print('The number I was thinking of was...',comp_num,'!\n')
elif comp_num <= guess:
#if guess is too high tells player
#one live taken for incorrect guess
lives -= 1
print('\nToo high!\n')
#player is told how many lives they have left
print('You guessed incorrectly. You have',lives,'live(s) remaining.\n')
if lives == 0:
#if player guesses incorrectly they get told the correct awnser
print('The number I was thinking of was...',comp_num,'!\n')
def end():
global score
#asks player if they want to play again
play_again = input('Would you like to play again?[Y/N] ')
while play_again.lower() == 'y':
#if they do game resets and plays again
if play_again.lower() == 'y':
comp_num = random.randint(1,10)
print('\nI\'m thinking of a number guess what it is...\n')
main()
play_again = input('Would you like to play again?[Y/N] ')
if play_again.lower() == 'n':
break
if play_again.lower() == 'n':
#if they don't game ends
print("You scored " + str(score) + " amazing points!")
input('Ok, Press enter to exit')
exit()
#calls main section of game
main()
#calls end of game to give option of playing again and reseting game
end()

Python Guessing Game Correct answer being printed even when player gets answer right

So I have recently started programming python and I have one issue with this code. When the player gets the answer incorrect after using all their lives it should print the answer which it does but only the first time the layer plays i they play again they don't get told the correct answer if the get it wrong. It also does this when the player gets the answer correct. Plus the number the computer chooses stays the same when you use the play again function. Please try and help me but bear in mind my understanding cane be very limited in some aspects of python. I've included lots of comments to help others understand whats going on. I have included my code and what I get in the shell.
Code:
#imports required modules
import random
from time import sleep
#correct number variable created
num = 0
#generates number at random
comp_num = random.randint(1,10)
print('I\'m thinking of a number guess what it is...\n')
#main game code
def main():
#lives created
lives = 3
#correct number variable reset
num = 0
while lives >= 1:
#player guesses
guess = int(input('Guess: '))
if comp_num == guess:
#if correct says well done
input('\nWell Done! You guessed Correctly!\n')
#player doesn't get told what the number is if there right
num = num +1
break
elif comp_num >= guess:
#if guess is too low tells player
#one live taken for incorrect guess
lives = lives -1
print('\nToo low!\n')
#player is told how many lives they have left
print('You guessed incorrectly. You have',lives,'live(s) remaining.\n')
elif comp_num <= guess:
#if guess is too high tells player
#one live taken for incorrect guess
lives = lives -1
print('\nToo high!\n')
#player is told how many lives they have left
print('You guessed incorrectly. You have',lives,'live(s) remaining.\n')
def end():
#asks player if they want to play again
play_again = input('Would you like to play again?[Y/N] ')
while play_again.lower() == 'y':
#if they do game resets and plays again
if play_again.lower() == 'y':
comp_num = random.randint(1,10)
print('\nI\'m thinking of a number guess what it is...\n')
main()
play_again = input('Would you like to play again?[Y/N] ')
if play_again.lower() == 'n':
break
if play_again.lower() == 'n':
#if they don't game ends
input('\nOk, Press enter to exit')
exit()
main()
if num != 1:
#if player guesses incorrectly they get told the correct awnser
print('The number I was thinking of was...',comp_num,'!\n')
end()
SHELL:
I'm thinking of a number guess what it is...
Guess: 5
Well Done! You guessed Correctly!
The number I was thinking of was... 5 !
Would you like to play again?[Y/N] y
I'm thinking of a number guess what it is...
Guess: 5
Well Done! You guessed Correctly!
Would you like to play again?[Y/N] y
I'm thinking of a number guess what it is...
Guess: 5
Well Done! You guessed Correctly!
Would you like to play again?[Y/N] y
I'm thinking of a number guess what it is...
Guess: 5
Well Done! You guessed Correctly!
The problem with your function is that you have a global variable named num, but your main function also has a local variable named num. The num += 1 line inside main only changes the local variable. But the if num != 1 at the end checks the global variable.
To fix this, add a global statement:
def main():
global num
# the rest of your code
Why does this work?
In Python, any time you write an assignment statement (like num = 0 or num += 1) in a function, that creates a local variable—unless you've explicitly told it not to, with a global statement.* So, adding that global num means that now, there is no local variable num, so num += 1 affects the global instead.
This is explained in more detail in the tutorial section on Defining Functions.
* Or a nonlocal statement, but you don't want to learn about that yet.
However, there's a better way to fix this. Instead of using a global variable, you can return the value in the local variable. Like this:
def main():
# your existing code
return num
# your other functions
score = main()
if score != 1:
#if player guesses incorrectly they get told the correct awnser
print('The number I was thinking of was...',comp_num,'!\n')
Ok so my friend looked at my code and we solved it together. We have fixed both the number staying the same and being told the correct answer by doing this.
#imports required modules
import random
#correct number variable created
num = 0
#generates number at random
comp_num = random.randint(1,10)
print('I\'m thinking of a number guess what it is...\n')
#main game code
def main():
#generates number at random
comp_num = random.randint(1,10)
#set num as a global variable
global num
#lives created
lives = 3
while lives >= 1:
#player guesses
guess = int(input('Guess: '))
if comp_num == guess:
#if correct says well done
print('\nWell Done! You guessed Correctly!\n')
break
elif comp_num >= guess:
#if guess is too low tells player
#one live taken for incorrect guess
lives = lives -1
print('\nToo low!\n')
#player is told how many lives they have left
print('You guessed incorrectly. You have',lives,'live(s) remaining.\n')
if lives == 0:
#if player guesses incorrectly they get told the correct awnser
print('The number I was thinking of was...',comp_num,'!\n')
elif comp_num <= guess:
#if guess is too high tells player
#one live taken for incorrect guess
lives = lives -1
print('\nToo high!\n')
#player is told how many lives they have left
print('You guessed incorrectly. You have',lives,'live(s) remaining.\n')
if lives == 0:
#if player guesses incorrectly they get told the correct awnser
print('The number I was thinking of was...',comp_num,'!\n')
def end():
#asks player if they want to play again
play_again = input('Would you like to play again?[Y/N] ')
while play_again.lower() == 'y':
#if they do game resets and plays again
if play_again.lower() == 'y':
comp_num = random.randint(1,10)
print('\nI\'m thinking of a number guess what it is...\n')
main()
play_again = input('Would you like to play again?[Y/N] ')
if play_again.lower() == 'n':
break
if play_again.lower() == 'n':
#if they don't game ends
input('Ok, Press enter to exit')
exit()
#calls main section of game
main()
#calls end of game to give option of playing again and reseting game
end()
I would like to thank everyone that helped out as with out I still wouldn't be able to see the problem within my code let alone fix it. For this reason I will me marking #abarnert 's answer as the accepted answer as he found the bug.
You can try this code. I did it as a school assignment
import random
print "Welcome to guess my number!"
number = random.randint(1,100)
count = 1
while count <= 5:
guess = int(raw_input("Guess an integer between 1 and 100 (inclusive): "))
if guess == number:
print "Correct! You won in",count,"guesses!"
break
if guess > number:
print "Lower!"
else:
print "Higher!"
count += 1
if count == 6:
print "Man, you really suck at this game. The number was", number

Categories

Resources