dimanche 11 août 2019

Else and elif trouble decision

Imagine i have the following problem.Write a program to play the following simple game. The player starts with $100. On each turn a coin is flipped and the player has to guess heads or tails. The player wins $9 for each correct guess and loses $10 for each incorrect guess. The game ends either when the player runs out of money or gets to $200.

I have already solved the problem by using a while loop and some if and else statements. I will post the code. When i use if and else my program prints p1_points and p2_points.

import random

coin = ['h','t']


def cpu_guess():
    return random.choice(coin)


def player1_guess():
    return input('Digit your choice player 1\n')


def player2_guess():
    return input('Digit your choice player 2\n')


def guessing_game():
    p1_points = 100 #each player starts with 100$
    p2_points = 100 #each player starts with 100$
    while (0 < p1_points <= 200) or (0 < p2_points < 200):
        cpu_choice = cpu_guess()
        print(cpu_choice)
        player1_choice = player2_guess()
        player2_choice = player2_guess()
        if player1_choice == cpu_choice:
            p1_points += 45
            print(p1_points)
        else:
            p1_points = p1_points - 45
            print(p1_points)
        if player2_choice == cpu_choice:
            p2_points += 45
            print(p2_points)
        else:
            p2_points = p2_points - 45
            print(p2_points)
    if p1_points > p2_points:
        print('Player 1 won the game (',p1_points,'-',p2_points,')')
    elif p2_points > p1_points:
        print('Player 2 won the game (', p2_points, '-', p1_points, ')')
    else:
        print('Even game (',p1_points,'-',p2_points,')')
    return p1_points,p2_points


print(guessing_game())

However imagine i want to put the following code.

 if player1_choice == cpu_choice:
            p1_points += 45
            print(p1_points)
        elif player_choice != cpu_choice
            p1_points = p1_points - 45
            print(p1_points)
        elif player2_choice == cpu_choice:
            p2_points += 45
            print(p2_points)
        else:
            p2_points = p2_points - 45
            print(p2_points)

In this situation why are only the player 1 points printed and not the player 2 points aswell?

Aucun commentaire:

Enregistrer un commentaire