[GO] Rock-paper-scissors poi in Python for beginners (answers and explanations)

This article is for Django Girls Japan Python beginners, This is a study session material for "Let's make a rock-paper-scissors game with Python". In addition, since the author is also a beginner, we apologize for any problems. Namer environment: Windows 10 python3.5 In addition, this article is a page of answers and explanations to the problems in the article of Janken Poi in Python.

Answer code

The problem page is here

# !/usr/bin/env python
# -*- coding: utf-8 -*-

import random

dic = {"a": "Goo", "b": "Choki", "c": "Par"}

print("Janken")
print("a=Goo b=Choki c=Enter par a, b, or c")
user = input('>>>  ')
user = user.lower()

try:
    user_choice = dic[user]

    choice_list = ["a", "b", "c"]
    pc = dic[random.choice(choice_list)]

    draw = 'DRAW'
    win = 'You Win!!'
    lose = 'You lose!!'

    if user_choice == pc:
        judge = draw
    else:
        if user_choice == "Goo":
            if pc == "Choki":
                judge = win
            else:
                judge = lose

        elif user_choice == "Choki":
            if pc == "Par":
                judge = win
            else:
                judge = lose

        else:
            if pc == "Goo":
                judge = win
            else:
                judge = lose

    print("You chose%s" % user_choice)
    print("The computer chose%s" % pc)
    print("Result is%s" % judge)
except:
    print("Please enter a, b or c.")

Commentary

Creating a dictionary

dic = """Question 1: Please make a dictionary where 1 is Goo 2 and Choki 3 is Par."""

dic.JPG Ask the user to enter a, b, or c. Since the key of the dictionary is a, b, or c, the keys are a, b, and c, and the value is set. Create a dictionary with goo, choki, and par.

input()

input.JPG

The print statement is a statement that prints the contents described in ().

user = input('>>> ') Program execution is interrupted at the line where input () is written, and waits for keyboard input. This time, there is a two-line print statement before input (), so it will be interrupted with the print statement and the >>> specified in () of input () displayed.

The input () function stores the contents input from the keyboard in the variable (user this time).

In addition, this time, kindly to the user ... so that you can enter uppercase letters, user = Converting characters entered with user.lower () to lowercase.

Exception handling

If the content entered by the user is not a, b, or c, there is no key in the dictionary. An error will occur and the program will be interrupted.

3.JPG

This spoils the fun (?) Game.

There are various ways to avoid this, but this time we will use exception handling.

try.JPG

Getting dictionary value using variables

user_choice = """Question 2: Is it goo using dic from the number entered by the user?
Get the choki or par letters"""

The method of acquiring the value of the dictionary is the dictionary name [key]. This time I will use dic.JPG Therefore, the dictionary name is dic. The key is user because it is the information received by input ().

Therefore, in order to obtain the value of Goo, Choki, or Par from the information selected by the user,

user_choice = dic[user]

It is described as.

Distinguish goo, choki, and par from the hands of a computer

pc = """Question 3: Using the imported random, let the PC choose a number,
And get the string of goo, choki or par"""

6.JPG

There are other ways to choose a computer hand, using the random module, This time, since the list is prepared in python first, use random.choice ().

One element is randomly extracted from the choice_list with random.choice (choice_list). The extracted element is used for the key of the dictionary created earlier.

Therefore ... From the hand selected by the computer by setting dic [random.choice (choice_list)] You can get value.

Conditional branch with if statement

"""Question 4: Compare the user's hand with the PC's hand to get the result.
The result is to create a variable called judge and do one of the above draw win lose
Please put it in a variable."""

if.JPG Arrows of the same color are the conditions. (I'm sorry. It's a little difficult to understand .. I'll update it if I can make it easier to understand ...) python I will make this judgment first, and then I will win or lose, so I will make a detailed judgment below else:.

String concatenation

Concatenation using% s% d

9.JPG

This time, I'm using a slightly older type of string concatenation method. Even now, it is described as an example on various sites. I still use it a lot (because it's easy ... ^^;), so I'll explain it.

"What you chose%s" % user_choice

There is a description of% s in the character string enclosed in "" (''is OK). Specify the character you want to embed in this% s part (this time, the character string in the user_choice variable). To specify, simply enclose it in "", enter%, and then enter the character you want to embed.

So what if you want to embed multiple characters?

a = "women"
b = 40

"A %s does not become interesting until she is over %d" % (a, b)

→A women does not become interesting until she is over 40 *% d embeds int value

It is OK if you pass% s and% d in the specified order, after the% after the character string (listed in the order of embedding, separated by commas).

** By the way, the English translation of ↑ is "Women become interesting only after 40." (It doesn't matter, but lol)

Other connection methods

Concatenation using operators

You can also use operators for strings. Actually ...

"You chose" + user_choice

Even if you just say, there is no problem with this content.

You can also use * (multiplication) for the character string. For example, if the variable of user_choice is "Goo"

user_choice * 3

Then

"Goo Goo Goo"

It will be.

Concatenation using format

Well ... In some cases, you may want to embed the same string in several places.

"My name is {0}.  Hallo {0}!! My Name is {1}".format("Taro", "Hanako")

→ "My name is Taro. Hallo Taro!! My Name is Hanako"

The number in {} indicates the room number of the tuple after formatting. If you use% s, the inside of () is the same as ("Taro", "Taro", "Hanako"). It is necessary to list more than one, but if you use format, as above, This is convenient because you don't have to write "Taro" twice.

If there are many places you want to embed and it is difficult to manage by room number, etc. It is also possible to specify by keyword.

"My name is {name1}.  Hallo {name1}!! My Name is {name2}".format(name1= "Taro", name2 =  "Hanako")

→ "My name is Taro. Hallo Taro!! My Name is Hanako"

There are various other ways to specify format, but I would like to introduce it separately.

bonus. I tried to make 3 games

・ In this case, you cannot count in the game ・ When the total number of wins between the user and the computer reaches 3, the one who wins 2 or more wins.

# -*- coding: utf-8 -*-
# !/usr/bin/env python

import random

dic = {"a": "Goo", "b": "Choki", "c": "Par"}

draw = 'DRAW'
win = 'You Win!!'
lose = 'You lose!!'

user_co = 0
pc_co = 0

judge = win

i = 1
while (user_co + pc_co) < 3:
    if judge == win or judge == lose:
        print(u"Janken")
    else:
        print(u"Aikode")
    print(u"a=Goo b=Choki c=Enter par a, b, or c")
    user = input('>>>  ')

    user_choice = user.lower()
    try:
        user_choice = dic[user]
    except:
        print("Please enter a, b or c.")
        continue

    pc = dic[str(random.choice("abc"))]

    if user_choice == pc:
        judge = draw
    else:
        if user_choice == "Goo":
            if pc == "":
                judge = win
            else:
                judge = lose

        elif user_choice == "Choki":
            if pc == "Par":
                judge = win
            else:
                judge = lose

        else:
            if pc == u"Goo":
                judge = win
            else:
                judge = lose
    if judge == win:
        user_co += 1
    elif judge == lose:
        pc_co += 1

    print(u"You chose%s" % user_choice)
    print(u"The computer chose%s" % pc)
    print(u"%The result of the dth race is%s" % (i, judge))
    print(u"")

    i += 1

if user_co >= pc_co:
    print(u"%d win%You win with d losses" % (user_co, pc_co))
else:
    print(u"%d win%You lose with d loss" % (user_co, pc_co))


↑ The 3rd game is also made according to my rules ... I think it will be a good practice to arrange and make various rules by yourself.

Recommended Posts

Rock-paper-scissors poi in Python for beginners (answers and explanations)
Run unittests in Python (for beginners)
I tried to refer to the fun rock-paper-scissors poi for beginners with Python
Causal reasoning and causal search with Python (for beginners)
Try to calculate RPN in Python (for beginners)
[Introduction for beginners] Working with MySQL in Python
Basic story of inheritance in Python (for beginners)
python textbook for beginners
OpenCV for Python beginners
[For beginners] How to use say command in python!
Preferences for playing Wave in Python PyAudio and PortAudio
Problems and countermeasures for Otsu's binarization overflow in Python
[Introduction for beginners] Reading and writing Python CSV files
[For beginners] Learn basic Python grammar for free in 5 hours!
Python # How to check type and type for super beginners
Recursively search for files and directories in Python and output
Learning flow for Python beginners
Search for strings in Python
Techniques for sorting in Python
Python3 environment construction (for beginners)
Python #function 2 for super beginners
Stack and Queue in Python
Basic Python grammar for beginners
100 Pandas knocks for Python beginners
Python for super beginners Python #functions 1
Unittest and CI in Python
Python #list for super beginners
~ Tips for beginners to Python ③ ~
About "for _ in range ():" in python
List method argument information for classes and modules in Python
[For beginners] Summary of standard input in Python (with explanation)
How to learn TensorFlow for liberal arts and Python beginners
Tips for coding short and easy to read in Python
Useful tricks related to list and for statements in Python
Problems and solutions when asked for MySQL db in Python 3
[Python] Accessing and cropping image pixels using OpenCV (for beginners)
Check for memory leaks in Python
MIDI packages in Python midi and pretty_midi
Difference between list () and [] in Python
Check for external commands in python
Difference between == and is in python
View photos in Python and html
Python Exercise for Beginners # 2 [for Statement / While Statement]
Sorting algorithm and implementation in Python
Python for super beginners Python # dictionary type 1 for super beginners
Manipulate files and folders in Python
About dtypes in Python and Cython
Assignments and changes in Python objects
Python #index for super beginners, slices
Check and move directories in Python
[For beginners] How to register a library created in Python in PyPI
Ciphertext in Python: IND-CCA2 and RSA-OAEP
<For beginners> python library <For machine learning>
Hashing data in R and Python
Python #len function for super beginners
Function synthesis and application in Python
Create a CGH for branching a laser in Python (laser and SLM required)
Export and output files in Python
Beginners use Python for web scraping (1)
Reverse Hiragana and Katakana in Python2.7
Reading and writing text in Python