職案人

求職・歴史・仏教などについて掲載するつもりだが、自分の思いつきが多いブログだよ。適当に付き合って下さい。

プログラムの6大要素

2017年11月15日 | Python
プログラムの6大要素

【環境条件】
OS:Windows 10
Python 3.6.1

【6大要素】
1.計算機能

2.変数
>>> a = 1
>>> b = 2
>>> c = "abc"
>>> username = "山田太郎"
>>> a
1
>>> username
'山田太郎'
>>> a+b
3
>>>

3.繰り返し
・for構文
「example04-03-01.py」ファイルを書く
プログラム1
# coding:utf-8
for a in [1,2,3,4,5]:
print(a)←必ずインデント
或いは
プログラム2
# coding:utf-8
for a in range(1,5+1):
print(a)

実行.表示
Python 3.6.1 shell
=========== RESTART: C:\python_sample\Chapter4\example04-03-01.py ===========
1
2
3
4
5
>>>

・while構文
「example04-04-01.py 」のリスト
# coding:utf-8
total = 0
a = 1
while total <= 50:
total = total + a
a = a + 1
print(total)
実行
=========== RESTART: C:\python_sample\Chapter4\example04-04-01.py ===========
55
>>>

4.条件分
・if構文
example04-05-01.py のリスト
# coding:utf-8

for a in range(1, 10+1):
if a <= 5:
print("小さいです")
else:
print("大きいです")

・実行
=========== RESTART: C:\python_sample\Chapter4\example04-05-01.py ===========
小さいです
小さいです
小さいです
小さいです
小さいです
大きいです
大きいです
大きいです
大きいです
大きいです
>>>

5.関数
・example04-06-01.pyのリスト
# coding:utf-8

def tashizan(a, b):←関数の定義
total = 0
for i in range(a, b + 1):
total = total + i
return total←戻り値

c = tashizan(1, 5)←関数を呼び出す
print(c)←関数を表示
・実行
=========== RESTART: C:\python_sample\Chapter4\example04-06-01.py ===========
15
>>>
example04-06-02.py のリスト
# coding:utf-8
#変数のスコープ
a = "abc"←グローバル変数

def test():
a = "def"←ローカル変数
print(a)
return

test()
print(a)
・実行
=========== RESTART: C:\python_sample\Chapter4\example04-06-02.py ===========
def
abc
>>>
example04-06-02.py のリスト
# coding:utf-8
#グローバル宣言

a = "abc"

def test():
global a
a = "def"
print(a)
return

test()
print(a)
・実行
=========== RESTART: C:\python_sample\Chapter4\example04-06-02.py ===========
def
def
>>>

6.モジュール(外部機能)
カレンダー.py のリスト

構文→import モジュール名
#カレンダー
import calendar
print(calendar.month(2017,11))

構文→import モジュール名 as 別名
#カレンダー
import calendar as c
print(c.month(2017,11))

================ RESTART: C:/python_sample/Chapter4/カレンダー.py ================
November 2017
Mo Tu We Th Fr Sa Su
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30

>>>
コメント
  • X
  • Facebookでシェアする
  • はてなブックマークに追加する
  • LINEでシェアする