LoginSignup
5
11

More than 5 years have passed since last update.

Python基礎

Last updated at Posted at 2017-10-10

モジュール

pythonではモジュールをimportすることでその機能をプログラム上使うことができます。

sample.py
import math
print(math.cos(0))

表示

print関数を使うことによってコンソール上に文字を表示することできます。
また、end引数を使うことによってデフォルトでは改行してしまうところを自由に設定することができます。

sample.py
print("HelloWorld")
print("Hello",end=" ")
print("World")

OutPut

HelloWorld
Hello World

コメント

「#コメント」または「"""コメント"""」とすることでコード内にコメントを書くことができます。

sample.py
"""コサイン値を表示するプログラム"""
import math #mathをインポート
print(math.cos(1))

変数

 変数名(値を入れる箱名)を決めてあげることでコードを綺麗にすることができます。

sample.py
"""コサイン値を表示するプログラム"""
import math #mathをインポート
x = math.cos(1)
print(x)

データ型

 プログラミング言語はデータの型を定義することで扱い方を変えることができます。

sample.py
"""コサイン値を表示するプログラム"""
import math #mathをインポート
x = math.cos(1)
print(x)

"""型を定義するプログラム"""
print(type(x))
intx = int(x)#小数点切り捨て
strx = str(x)#文字として定義
floatx = float(x)#浮動小数点型

print(intx)
print(strx)
print(floatx)

リスト

 複数のデータを格納、扱う時はリストを作成します。

sample.py
"""コサイン値を表示するプログラム"""
import math #mathをインポート
x = math.cos(1)
print(x)

"""型を定義するプログラム"""
print(type(x))
intx = int(x)#小数点切り捨て
strx = str(x)#文字として定義
floatx = float(x)#浮動小数点型

print(intx)
print(strx)
print(floatx)

"""リストに格納するプログラム"""
cos_list = [intx,strx]
cos_list.append(floatx)

print(cos_list)

スライスを使った部分リストの取得

スライスとは要素と要素の間にある壁をイメージするとわかりやすいです。

 0   1   2   3   4   5
 | A | B | C | D | E |
slice1 = cos_list[1:2]    
slice2 = cos_list[1:-1]   
slice3 = cos_list[1:]     
slice4 = cos_list[:2]     
slice5 = cos_list[:]      

制御構文

インデント

for文プログラムに注目してください。print文の前にスペースがあります。このスペースがインデント(字下げ)です。pythonではインデントを使うことで、コードの一行前の処理内でコードを実行します。

ほとんどの場合インデントの前コードの最後に「:」をつけます。

if文

「if」を記述後に条件式を記述し、その条件がTrueであれば条件配下の処理が実行される仕組みとなります。

if_sample.py
value = 2

if value == 1:
    print ('valueの値は1です')
elif value == 2:
    print ('valueの値は2です')
elif value == 3:
    print ('valueの値は3です')
else:
    print ('該当する値はありません')

条件の組み合わせには「and」「or」などを用います。

if_sample2.py
value_1 = 'python'
value_2 = 'izm'

if value_1 == 'Python':
    print(" ")
elif value_1 == 'python' and value_2 == 'izm':
    print("2番目の条件式がTrue")
elif value_1 == "IZM" or value_2 == "PYTHON":
    print("3番目の条件式がTrue")

for文

繰り返す動作を実装する際に使います。

sample.py
"""コサインの値を複数表示するプログラム"""
for x in range(0,10):#0~9の値を順場にxに入れる処理()
    print(math.cos(x))#前コードの処理を反映したコサイン値

Untitled Diagram (2).jpg

関数

defをつかうことで関数を定義することができます。def 関数名():で定義されます。
関数名は任意です。

sample.py
"""コサインの値を複数表示する関数のプログラム"""
def cos():#cos関数
    for x in range(0,10):#0~9の値を順場にxに入れる処理
        print(math.cos(x))#前コードの処理を反映したコサイン値

コード全文

sample.py
"""コサイン値を表示するプログラム"""
import math #mathをインポート
x = math.cos(1)#コサイン値をxに代入
print(x)

"""型を定義するプログラム"""
print(type(x))
intx = int(x)#小数点切り捨て
strx = str(x)#文字として定義
floatx = float(x)#浮動小数点型

print(intx)
print(strx)
print(floatx)

"""コサインの値を複数表示する関数のプログラム"""
def cos():#cos関数
    for x in range(0,10):#0~9の値を順場にxに入れる処理
        print(math.cos(x))#前コードの処理を反映したコサイン値
cos()

お疲れ様でした。

演習問題

問題1:forを2つ使い、九九を表示してください。
SampleOutput

1 2 3 4 5 6 7 8 9 
2 4 6 8 10 12 14 16 18 
3 6 9 12 15 18 21 24 27 
4 8 12 16 20 24 28 32 36 
5 10 15 20 25 30 35 40 45 
6 12 18 24 30 36 42 48 54 
7 14 21 28 35 42 49 56 63 
8 16 24 32 40 48 56 64 72 
9 18 27 36 45 54 63 72 81

問題2: 1から100までの数をプリントするプログラムを書いてください。ただし3の倍数のときは数の代わりに「Fizz」と、5の倍数のときは「Buzz」とプリントし、3と5両方の倍数の場合には「FizzBuzz」とプリントしてください。
(FizzBuzz問題)

SampleOutput

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz
Fizz
22
23
Fizz
Buzz
26
Fizz
28
29
FizzBuzz
31
32
Fizz
34
Buzz
Fizz
37
38
Fizz
Buzz
41
Fizz
43
44
FizzBuzz
46
47
Fizz
49
Buzz
Fizz
52
53
Fizz
Buzz
56
Fizz
58
59
FizzBuzz
61
62
Fizz
64
Buzz
Fizz
67
68
Fizz
Buzz
71
Fizz
73
74
FizzBuzz
76
77
Fizz
79
Buzz
Fizz
82
83
Fizz
Buzz
86
Fizz
88
89
FizzBuzz
91
92
Fizz
94
Buzz
Fizz
97
98
Fizz
Buzz

問題3: 以下のプログラムを完成完成させよ。

calendar.py
X1 calendar
calendar = calendar.Calendar()
X2 = []
X3 year X4 range(int(2016),int(2017)+1): #ヒント繰り返し文
X3 month x4 range(1,13):
X3 week X4 calendar.monthdayscalendar(year,month):
X3 day X4 week:
X5 day != 0:  #条件分岐
X2.X6("%d-%02d-%02d" %(year,month,day))
X7(date)

このプログラムはリスト「date」に2016年から2017年の日付データを格納し、表示するプログラムです。「x1~7」にはある単語が入ります。また、このコードはインデントを考慮していません。各自で字下げしなければなりません。

サンプルプログラム

1.Answer

9x9.py
for x in range(1,10):
        for y in range(1,10):
                print(x*y,end=" ")
        print("")

2.Answer

fizzbuzz.py
for i in range(1,101):
        if i%3 == 0 and i%5 == 0:
                print("FizzBuzz")
        elif i%3 == 0:
                print("Fizz")
        elif i%5 == 0:
                print("Buzz")
        else:
                print(i)

3.Answer

calendar.py
import calendar
calendar = calendar.Calendar()
date = []
for year in range(int(2016),int(2017)+1):
       for month in range(1,13):
               for week in calendar.monthdayscalendar(year,month):
                       for day in week:
                                if day != 0:
                                       date.append("%d-%02d-%02d" %(year,month,day))
print(date)

寄付していただければ幸いです!
仮想通貨
BTC 18c58m54Lf5AKFqSqhEDU548heoTcUJZk
ETH 0x291d860d920c68fb5387d8949a138ee95c8d3f03
ZEC t1KtTRKy9w1Sv5zqi3MYnxZ3zugo54G4gXn
REP 0x291d860d920c68fb5387d8949a138ee95c8d3f03

5
11
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
5
11