Mylo Bishop
Mylo Bishop

Reputation: 15

How do I set a variable to a random integer in Python 3?

I'm relatively new to coding and am now trying to build a rock paper scissors game in Python 3. Here is my code at the moment `

answer = input("To play: type in Rock (r), Paper (p) or Scissors (s)").lower()

if answer == "rock" or answer == "r":
    answer = 1
    print ("You chose Rock!")

elif answer == "paper" or answer == "p":
    answer = 2
    print ("You chose Paper!")

elif answer == "scissors" or answer == "s":
    answer = 3
    print ("You chose Scissors!")

else:
    print ("You didn't pick an option... Make sure you spell it right!")
    rps()

computer = lambda: random.randint(1, 3)
if computer == 1:
    string_computer = "Rock"
elif computer == 2:
    string_computer = "Paper"
elif computer == 3:
    string_computer = "Scissors"
else:
    print ("There must had been a glitch")
    rps()

if answer == computer:
    print(("The computer chose"), string_computer,("so it\'s a draw!"))
elif answer == 1 and computer == 2:
    print(("The computer chose"), string_computer,("so unfortuantely you lost."))
    rps()
elif answer == 1 and computer == 3:
    print(("The computer chose"), string_computer,("so you won! Congratulations!"))
    rps()
elif answer == 2 and computer == 1:
    print(("The computer chose"), string_computer,("so you won! Congratulations!"))
    rps()
elif answer == 2 and computer == 3:
    print(("The computer chose"), string_computer,("so unfortuantely you lost."))
    rps()
elif answer == 3 and computer == 1:
    print(("The computer chose"), string_computer,("so unfortuantely you lost."))
    rps()
else:
    print(("The computer chose"), string_computer,("so you won! Congratulations!"))
    rps()

`

And when I try to run the code, all syntaxes are correct but it comes up with "There must had been a glitch" which I added in to see if it wasnt chosing a number between 1 and 3. How do I fix it so it picks a number between 1 and 3 ?

Upvotes: 1

Views: 523

Answers (1)

Mason Caiby
Mason Caiby

Reputation: 1934

import random

computer = random.randint(1,3)

there's no need for a lambda function here.

including the lambda function set computer to a function that will generate a random number between 1 and 3:

>>> computer = lambda: random.randint(1, 3)
>>> computer
<function <lambda> at 0x000001F4DD2738C8>

if you then call computer() you will get a random number between 1 and 3:

>>> computer()
2
>>> computer()
2
>>> computer()
1

for your functionality, getting rid of the lambda: is the best fix. If you are tempted to add parenthesis in the if computer... statements, you might end up in the glitch statement because you'll be generating a new random int for each computer() call.

Upvotes: 1

Related Questions