Python case: using if statement to implement a guessing game

Time:2019-9-6

Mission requirements:

In the console prompt input stone, scissors, cloth, press the return key, and then give the game results.

Analysis:

We know that in the rules of the game, stones can cut scissors, scissors can cut cloth, and Books can cut stones. But this is not a very direct representation in the computer, so we use it separately.0、1、2They represent the stone scissors in the game.

So how can the computer punch? That should be used.pythonA modulerandomA Methodrandom.randint()If a random integer is generated in the range of 0-2, it will be displayed by the computer.

random.randint()The usage is as follows:

# First import the module
import random
# When invoked, two integer numbers are passed in and any integer number from 1 to 2 is returned.
a = random.randint(1,2)
# Print out 1 or 2
print(a)


# Or, B might be any number in 1-10 (including 1 and 10)
b = random.randint(1,10)
print(b)

# In this case, we only need any number in 0-2, so
computer = random.randint(0,2)

If the player punches, he can enter any number of 0-2 from the keyboard and save it in a variable, then useifSentences can be compared to get the result.

Code implementation:

import random

# If you get user input from keyboard, you can only enter 0-2 digits, otherwise the result will be incorrect, and there will be upgrades in the future.
Person = input ('Please enter: stone (0), scissors (1), cloth (2):')
# Input returns a string type, randInt (0, 2) returns an int type, which requires mandatory conversion of person to an int type, so that the type is consistent before comparison can be made.
person = int(person)
computer = random.randint(0, 2)

# In order to display information more friendly
if person == 0:
    Print ('Player: Stone')
elif person == 1:
    Print ('player: scissors')
else:
    Print ('player: cloth')
if computer == 0:
    Print ('Computer: Stone')
elif computer == 1:
    Print ('computer: scissors')
else:
    Print ('computer: cloth')

# If you punch, it's a draw.
if person == computer:
    Print ('You're awesome! It was a draw with me! )

# Player: Stone Computer: Scissors
# Player: Scissors Computer: Cloth
# Player: Cloth Computer: Stone in these three cases the player wins

elif person == 0 and computer == 1 or person == 1 and computer == 2 or person == 2 and computer == 0:
    Print ('Congratulations, you won! )
# In other cases, players lose.
else:
    Print ('What a pity you lost! )

 

Operating schematic diagram:

Recommended Today

Server Core Knowledge

Catalog 1. Computer: a tool to assist human brain 2. Composition of computer hardware 3. power supply 4.CPU 5. memory 6. Classification of computer use 7. Introduction to common Internet servers 8. Server classification 1. Computer: a tool to assist human brain Nowadays people touch computers almost all the time! Whether it’s a desktop computer, […]