LoginSignup
2

More than 5 years have passed since last update.

はじめてのpython② pythonの特徴を調べつつコードを書いてみる

Last updated at Posted at 2013-07-10

背景

「さわった事が無い言語でWebシステムを作ろう」というテーマの社内勉強会に参加する事になり、
pythonの調査を担当する事になったので、調べた内容をまとめてみる第二弾。前半は主にwikipediaからの抜粋。

pythonとは

  • オープンソースのオブジェクト指向スクリプト言語
  • 2013/7/8時点の最新バージョンは3.3.2
  • 公式サイト http://www.python.org/

pythonの特徴

記法

  • 文法の制約が強く、プログラムのスタイルがその書き手にかかわらずほぼ同じになる
  • ブロック構造にインデントを用いる
  • 一行80文字(あくまで推奨)

データ型

  • データは動的に型付けされる。値自身が型を持っており、変数はすべて値への参照である
  • リスト = 配列っぽい感じ
  • タプル = 値の変更が出来ない配列っぽい。マップのキーとしても利用出来る

オブジェクト指向

  • Pythonでは扱えるデータの全てがオブジェクトである

比べてみよう

前にRubyで書いた長女の算数問題Scriptをpythonで書きなおしてみた。書いてみた感想は以下。
(大したことやってないので、大した感想ではないですが・・・。随時書き足します。)

  • ifやwhileにendがないのは個人的には見づらいなぁ(慣れ?)
  • まぁしかしそんな書きづらさは無い感じ
  • ただやっぱりRubyのほうが好き
keisan.rb
#!/usr/bin/env ruby
# -*- encoding: utf-8 -*-

question_num = 10
score = 0
i = 0

while i < question_num do
  val1 = rand(10)
  val2 = rand(10)

  print "(#{i + 1}) "
  case rand(2)
  when 0
    print "#{val1} + #{val2} = "
    correct_ans = val1 + val2
  when 1
    if val1 >= val2
      print "#{val1} - #{val2} = "
      correct_ans = val1 - val2
    else
      print "#{val2} - #{val1} = "
      correct_ans = val2 - val1
    end
  end

  ans = gets.to_i

  if correct_ans == ans
    p "せいかいは#{correct_ans}"
    p "やったね!!"
    score += 1
  else
    p "せいかいは#{correct_ans}"
    p "ざんねん!!"
  end
  i = i + 1
end

p "あなたのてんすうは #{((score.to_f / question_num.to_f) * 100).to_i} てん!!"

keisan.py
#!/usr/bin/env python
# -*- encoding: utf-8 -*-

import random

question_num = 10
score = 0
i = 0

while i < question_num:
  val1 = random.randint(0,9)
  val2 = random.randint(0,9)
  operator_flg = random.randint(0,1)

  print("(" + str(i + 1) + ") ", end=&#39;&#39;)

  if operator_flg == 0:
     formula = str(val1) + " + " + str(val2) + " = "
     correct_ans = val1 + val2
  elif operator_flg == 1:
    if val1 >= val2:
      formula = str(val1) + " - " + str(val2) + " = "
      correct_ans = val1 - val2
    else:
      formula = str(val2) + " - " + str(val1) + " = "
      correct_ans = val2 - val1

  ans = input(formula)

  if correct_ans == int(ans):
    print("せいかいは " + str(correct_ans))
    print("やったね!!")
    score += 1
  else:
    print("せいかいは " + str(correct_ans))
    print("ざんねん!!")

  i += 1

print("あなたのてんすうは " + str(int(float(score) / float(question_num) * 100)) + "てん!!")

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
2