LoginSignup

This article is a Private article. Only a writer and users who know the URL can access it.
Please change open range to public in publish setting if you want to share this article with other users.

More than 3 years have passed since last update.

Python練習問題4 回答編

Posted at
import random

d = {"a": "グー", "b": "チョキ", "c": "パー"}

pc_dic = {"a":{"a":"引き分け","b":"あなたの勝ち","c":"あなたの負け"},
          "b":{"b":"引き分け","c":"あなたの勝ち","a":"あなたの負け"},
          "c":{"c":"引き分け","a":"あなたの勝ち","b":"あなたの負け"},
}

user_choice = ""
while True:

    print("じゃーんけーん")
    print("a=グー b=チョキ c=パー aかbかcを入力")
    user = input('>>>  ')
    user = user.lower()
    try:
        user_choice = d[user]
        break
    except:
        continue

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

result = pc_dic[pc][user]

print("ユーザーが選んだのは%s"%d[user])
print("PCが選んだのは%s"%d[pc])
print(result)
  • a b cに対しじゃんけんの手を取得する辞書を作成する
  • pc の手が決まった時に返す答えの辞書を作成する
  • ユーザに入力を求める
  • PCの手をランダムに取得する
  • ユーザーとPCの手を表示する
  • じゃんけんの結果を表示する
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up