A Python game in which both a user and a computer randomly chooses a number from 1 – 10 and if the numbers are the same, the user wins else, he loses

Question:

Write a game in Python so that a user will randomly choose a number from 0 to 10 and the computer will also do same. If the numbers are equal, you win else you lose.

This is what I wrote. When I run, nothing happens. Can anyone rewrite the full game for me?

import random
class Game():
    def __init__(self, computer_choice, user_choice):
        self.computer_choice = computer_choice
        self.user_choice = user_choice

    def computer(self):
        self.computer_choice = random.randint(range(1,10))

    def user(self):
        self.user_choice= int(input("Enter a random number from 1 to 10: "))  

    def decision(self): 
        if self.user_choice == int(range(1,10)): 
         
            if self.computer_choice == self.user_choice:
                print("You won!")
            else:
                print("You lost!")    
        else:
            print("You entered an invalid option")

def main():
    
    if __name__ == "__main__":
        main()
Asked By: Sa.m.ue

||

Answers:

It is hard to know for sure since we can’t see what is in main, but the problem could very well be this line:

if self.user_choice == int(range(1,10)):

You are attempting to compare the user’s choice, an integer between 1 and 10, with a range of integers, a range object. Under the best of circumstances that would not work. In this case, you casting the range to an int should result in a TypeError exception. Instead, you could write:

if self.user_choice in range(1, 11):

or better yet:

if 1 <= self.user_choice <= 10:
Answered By: rhurwitz

Note: Main problem is fixed in rhurwitz’s answer, but there is an addition:

You are entering an infinite loop in the main function: I’d also recommend doing:

def main():
    if __name__ == "__main__":
       game = Game(0, 0)
       game.computer()
       game.user()
       game.decision()

In all:

import random
class Game():
    def __init__(self):
        self.computer_choice = random.randint(1,10)
        self.user_choice = int(input("Enter a random number from 1 to 10: "))

    def decision(self): 
        if self.user_choice in list(range(11)): 
         
            if self.computer_choice == self.user_choice:
                print("You won!")
            else:
                print("You lost!")    
        else:
            print("You entered an invalid option")

def main():
    game = Game()
    game.decision()

main()
Answered By: UndoneStudios
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.