LoginSignup
9
3

More than 3 years have passed since last update.

Pythonでおみくじ作った。

Last updated at Posted at 2019-12-02

はじめに

アドベントカレンダーが空いていたのでPythonに関するちょっとしたことを書こうと思います。
いつもはFlaskを使ってWebアプリを作っているのですが、フレームワークに頼っているせいかPythonそのものの理解が浅いと感じました。そこで、Pythonの練習をしようとまず、おみくじを作りました。
(現在Flaskのアドベントカレンダーがガラ空きです。少しでもFlaskを知っている方はぜひ参加してください!)

環境

Ubuntu18.04LTS
Python3.6.9
vim

コード

今回はこんな感じのおみくじを作りました。

kuji.py
from random import choice


play = input('playと入力したらおみくじを引けます。: ')

while True:
    if play == 'play':
        break

    print('もう一度入力してください。')
    play = input('playと入力したらおみくじを引けます。: ')

while True:
    KUJI = ['大吉', '中吉', '小吉', '末吉', '凶', '大凶']
    print(choice(KUJI))
    continue_ = input('もう一度引きますか?[y/n]: ')
    while True:
        if continue_ != 'y':
            if continue_ != 'n':
                input('yまたはnを入力してください。: ')
            else:
                break
        else:
            break

    if continue_ == 'y':
        pass
    else:
        break

print('終了しました。')

普通のおみくじだとつまらないので少し工夫してみました。
本当におみくじだけなら2行で終わります。こんな感じで。

from random import choice
print(choice(['大吉', '中吉', '小吉', '末吉', '凶', '大凶']))

追記

コメントのアドバイスを参考にしてもう少し工夫しました。

kuji2.py
from random import choices #choice → choices


play = input('playと入力したらおみくじを引けます。: ')

while True:
    if play == 'play':
        break

    print('もう一度入力してください。')
    play = input('playと入力したらおみくじを引けます。: ')

while True:
    KUJI = ['大吉', '中吉', '小吉', '末吉', '凶', '大凶']
    print(choices(KUJI, weights=[1, 5, 10, 10, 5, 1])[0]) # ここを変えました。
    continue_ = input('もう一度引きますか?[y/n]: ')
    while True:
        if continue_ == 'y' or continue_ == 'n': # ここらへんのコードも整えました。
            break
        else:
            continue_ = input('yまたはnを入力してください。: ')

    if continue_ == 'n':
        break

print('終了しました。')

以上です。

9
3
2

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
9
3