LoginSignup
1
1

More than 5 years have passed since last update.

Python基礎学習

Last updated at Posted at 2015-09-12

print文,四則演算,list,tuple

とりあえず恒例の(?)"Helo world"から

print()
x="Helo world"
print x

Python2とPython3は何か違うらしく,Python3では括弧をつける必要があるようだ.

print()
x="Helo world"
print(x)
四則演算
x = 3 + 1
print(x)

y = 8 - 3
print(y)

i = x * y
print(i)

j = i / 2
print(j)
実行結果
4
5
20
10.0

リスト型はシーケンス型の一つ.複数の要素から構成され,要素が順に並んでいるもの.
listは配列のようなものなのかな?

list
list_a = ['aaa', 'bbb', 'ccc', 'ddd']
list_b = ['1', '3', '4', '2']
print(list_a)
print(list_b)

print(list_a[2])
print(list_b[1])
実行結果
['aaa', 'bbb', 'ccc', 'ddd']
['1', '3', '4', '2']
ccc
3

タプル型もシーケンス型の一つで,リスト型との違いは要素の書き換えができないこと.

tuple
tuple_a = ('aaa', 'bbb', 'ccc', 'ddd')
tuple_b = ('1', '3', '4', '2')
print(tuple_a)
print(tuple_b)

print(tuple_a[2])
print(tuple_b[1])
実行結果
['aaa', 'bbb', 'ccc', 'ddd']
['1', '3', '4', '2']
ccc
3

条件分岐 if文

if文
#input():キーボードからの入力を受け付ける.入力は文字型.
#int():()内を整数型にする.

x = int(input("入力:"))
if x == 0:
  print("false!")
elif x == 1:
  print("true!")
else:
  print("nill")
実行結果
入力1
true!

入力0
false!

入力5
nill

繰り返し文 for文,while文

for文
list_a = ["taro", "tomo", "msds", "kumi"]
for i in list_a:
  print(i)
実行結果
taro
tomo
msds
kumi
while文
i = 0
while i < 10:
  print(i)
  i += 1 
実行結果
0
1
2
3
4
5
6
7
8
9

関数の定義

関数
#funcは関数名
#defの中のxは引数
#return xは返り値
def func(x):
  x += 5
  return x

x = func(2)
print(x)
実行結果
7

モジュールの使い方

モジュールは関数や変数をひとまとめにしたもの.
必要な関数を使うには,その関数が所属しているモジュールをimportする必要がある.
試しに,時間を扱うモジュールである”time”を使ってみる.

関数の使い方
import time
print(time.asctime())
実行結果
Thu Sep 10 00:31:51 2015
1
1
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
1
1