Skip to content
Advertisement

Can’t Make Code Detect whose turn it is in Python IDLE

My friend and I are trying to code the “21” game into Python, where you play against a random thingy and you take in turns adding numbers (from 1-4) to a score and if its 21 or above when its your turn, you lose. but we can’t figure out how to make it detect who’s turn it was when it reaches 21

Here’s my code so far:

import random
import time
carryOn = True
counter = 0

print("First to 21 or above LOSESn n") 

while carryOn == True:
    user = input("Please enter any number from 1 – 4")
    print("You Chose " + user)

    counter = counter + int(user)
    print("The new Total is " + str(counter) + "n")

    user == 0

    time.sleep(3)

    computer = random.randint(1,4)
    print("The Computer Rolled a " + str(computer))

    counter = counter + int(computer)
    print("The new Total is " + str(counter) + "n")
if counter == 21:
    carryOn == False

Advertisement

Answer

First your code does not detect when the score is 21, because if statement is not inside while loop and because you are comparing carryOn with False, but not setting it to False. Also if statement should check if counter is more or equal than 21, because you can jump over it (for example score was 20 and then 24).

And you need to check counter after each turn, not after every two turns, because game might end after user’s turn. To end loop in the middle you can use break or continue. I prefer continue, so it ends up like this

import random
import time
carryOn = True
counter = 0

print("First to 21 or above LOOSESn n") 

while carryOn:

    user = input("Please enter any number from 1 – 4")
    print("You Chose " + user)

    counter = counter + int(user)
    print("The new Total is " + str(counter) + "n")


    if counter >= 21:
        print('User lost')
        carryOn = False 
        continue

    computer = random.randint(1,4)
    print("The Computer Rolled a " + str(computer))

    counter = counter + int(computer)
    print("The new Total is " + str(counter) + "n")

    if counter >= 21:
        print('Computer lost')
        carryOn = False

Advertisement