SlideShare a Scribd company logo
1 of 43
Python講座第三回
前回をさらっとおさらい
おさらいはだいじです
誠に残念ですが、肖像権の都合上、このページは削除致しました。
♪フリージア/熱唱:Nわかさん
bool型(boolean型)の話
真偽値を取る型
取れる値は
真(True)か偽(False)
のどちらかのみ!!
数学の命題みたいなもの
bool型(boolean型)の話
例えば…
aとbの値は等しいか??
aよりbが大きいか??
「はい」か「いいえ」で答えられる質問に対する答えを格納する
「はい」 → True(真)
「いいえ」 → False(偽)
bool値を返す比較演算子
日本語 プログラム
aとbの値は等しいか? a == b
aとbの値は等しくないか? a != b
aよりbが大きいか? a < b
aはb以下か? a <= b
aよりbが小さいか? a > b
aはb以上か? a >= b
a = 10
b = 20
flag = a == b # flagにはFalseが格納される
flag = a != b # flagにはTrueが格納される
flag = a < b # flagにはTrueが格納される
flag = a > b # flagにはFalseが格納される
条件文
if [条件①]:
# 条件①を満たすときに実行するプログラム
elif [条件②]:
# 条件②を満たすときに実行するプログラム
# ifは一つまでだが、elifは何個作ってもOK
else:
# ここまでの条件を満たさなかったときに実行
必
須
任
意
【再掲】条件文
if [真偽値①]:
# 真偽値①がTrueのときに実行するプログラム
elif [真偽値②]:
# 真偽値②がTrueのときに実行するプログラム
# ifは一つまでだが、elifは何個作ってもOK
else:
# ここまでの条件を満たさなかったときに実行
必
須
任
意
リスト
データをまとめて扱えるもの
変数を繋げ、関連させたもの
イメージとしては区切られた箱のようなもの
赤羽根くんの点数
score[0] = 50
武内くんの点数
score[2] = 90
坂上くんの点数
score[1] = 200
0から始まる!!
リストを広げる・狭める
[リスト名].append([追加する変数])
リストの一番最後に新たに値を追加する
箱を追加するイメージ
score2[0] = 1 score2[1] = 4
score2 = [1, 4]
score2.append(5)
score2[2] = 5
リストを広げる・狭める
[リスト名].pop([削除する変数(省略可)])
リストの値を削除し、返す(省略した場合は
最後の値)
変数を空にするのではなく、箱ごと削除する
イメージ
score2[0] = 1 score2[1] = 4
score2 = [1, 4]
score2.pop(1)
リストを広げる・狭める
[リスト名].pop([削除する変数])
score2 = [1, 4]
score2.pop()
# 省略すると最後の要素が削除
p_name = [“Akabane”, “Sakagami”, “Takeuchi”]
p = pl_name.pop(1)
# p_nameから”Sakagami”が削除され、pに代入される
# このとき、p_name = [“Akabane”,”Takeuchi”]
辞書
リストではインデックスに0,1,2,3,…を使わないといけない!
もっと何が収納されてるか分かりやすく!!
[辞書名] = {[要素のインデックス]:[要素], [要素のインデッ
クス]:[要素], … , [要素のインデックス]:[要素]}
基本的にはリストと似ているが、要素のインデックスも指定し
ないといけない(あたりまえ)
反復構造とは
ある条件を満たすなど、指定するブロック
を実行し続けるようなもの
どの言語でも大きく「FOR」と「WHILE」が
ある
FOR
for [変数] in [リスト]:
# 実行するプログラム
リストの中身を順に実行していくもの!(Python
では)
他言語ではこれはforeachなどという名前である
ことが多い
FORを使うときに便利な関数
range([整数値1~3個]):リストを作る関数
forと相性がとてもよい
1個のとき:0以上、与えた値未満の全ての整数を順
に1つずつ含むリストを返す
2個のとき:1値目の値以上、2値目の値未満の全て
の整数を順に1つずつ含むリストを返す
3個のとき:1値目の値以上、2値目の値未満の全て
の整数を3値目の値おきに、順に1つず
つ含むリストを返す
反復構造
ぐーーーーーーーるぐる
まわるまわるよじだいはまわる
(WHILE編)
練習問題
適当な数値のリストを与えたときに、そのリ
ストの最大値と最小値とそのインデックスを
返すプログラムを作成してください
lis = [1, 4, 100] # このリストが何であっても成り立つように
l_num = len(lis) # len([リスト名])でリストの要素の数を返す(今回は3)
~~
forを含むプログラムを書く
~~
print(“最大値:lis[{}]={}, 最小値:lis[{}]={}”.format(…))
# 最大値:lis[2]=100, 最小値:lis[0]=1 というような出力をさせる
lis = [1, 4, 100]
l_num = len(lis)
maximum = minimum = lis[0] #とりあえず最初の値を代入しておく
maxIdx = minIdx = 0
for x in range(l_num):
if maximum < lis[x]: # xにはインデックスが入ることに注意
maximum = lis[x]
maxIdx = x
if minimum > lis[x]:
minimum = lis[x]
minIdx = x
print(“最大値:lis[{}]={}, 最小値:lis[{}]={}”.format(maxIdx,maximum,
minIdx,minimum))
WHILE
while [条件式or真偽値]:
# 実行するプログラム
条件式or真偽値がTrue(真)である限り、
実行するプログラムを繰り返す
x = 10
while x > 0:
print(x)
x -= 1
出力
10
9
8
7
6
5
4
3
2
1
練習問題
有名なプログラムの練習の一つ、FizzBuzz(1~100)
をForやWhileを使っていくつか作ってみましょう
★FizzBuzzとは
3の倍数のときにFizz
5の倍数のときにBuzz
どちらも満たすときはFizzBuzz
どちらでもない場合はその数字
を言う言葉遊びゲームです
for x in range(100):
if x % 15 == 0:
print(“FizzBuzz”)
elif x % 3 == 0:
print(“Fizz”)
elif x % 5 == 0:
print(“Buzz”)
else:
print(x)
FizzBuzz①
FORを使ってみた-1
for x in range(100):
msg = “”
if x % 3 == 0:
msg = msg + “Fizz”
if x % 5 == 0:
msg = msg + “Buzz”
if msg == “”:
msg = str(x)
print(msg)
FizzBuzz②
FORを使ってみた-2
x = 1
while x <= 100:
if x % 15 == 0:
print(“FizzBuzz”)
elif x % 3 == 0:
print(“Fizz”)
elif x % 5 == 0:
print(“Buzz”)
else:
print(x)
x += 1
FizzBuzz③
WHILEを使ってみた
break,continue
FOR文/WHILE文から無理やり抜け出すbreak
一つしか抜け出せないので、入れ子になってい
る場合は工夫が必要
FOR文/WHILE文の途中で実行をやめ、それらの
最初に戻るのがcontinue
i = 10
total = 1
while True:
if i <= 0:
break
elif i % 2 == 1:
continue
total *= i
total -= 1
break!!!
continue!!!!!!!!
練習問題
繰り返しを用いて常に入力を待ち、qが入力されたら繰り返
しを終了、それ以外が入力されたら好きな有名人の名前か
なんかをprintするプログラムを作ってください。
Console
入力 > a
K3
入力 > qwf
K3
入力 > q
( 終了 )
while True:
p = input()
if p == “q”:
break
print(“K3”)
p = input()
while p != “q”:
print(“K3”)
p = input()
関数
数学でやった気がする
数学の関数を思い出してみる
関数f(x)=x2
3
2
-2
9
4
4
ある値(今回はx)を決めると、値が一つに決まる
関数とは
関数:func(x)
print(x * x)
3
2
-2
変数の値(今回はx)のみを変えて、同じプログラムを実行する
場合によっては値を戻すこともある(数学の関数のイメージ)
9
4
4
関数とは
よく使う似たプログラム(変数のみ違う等)を1
箇所にまとめて、書くコードの量を減らすことが
出来る
そのプログラムに間違いがあったときも1箇所直
すだけでOK
予め用意された関数(printなど)は組み込み関
数と言う
関数
def [関数名](引数(複数ある場合カンマで区切る)):
# 実行するプログラム
return [返す値] # 戻す値があるときのみ
とりあえず分かりにくいので
プログラムを見よう!
def func(x):
print(x * x)
func(3)
# 9を出力
func(2)
# 4を出力
func(-2)
# 4を出力
def func(x, y): # 値を2個取る場合はカンマで区切る
print(x + y)
func(3, 5)
# 3+5で8を出力
func(12, 2)
# 12+2で14を出力
func(-10, -2)
# -10+(-2)で-12を出力
def absolute(value):
if value < 0:
return -1 * value
return value
x = absolute(-20)
# -20の絶対値20が返り、xに代入される
y = absolute(0.9)
# 0.9の絶対値0.9が返り、yに代入される
z = absolute(-50.2)
# -50.2の絶対値50.2が返り、zに代入される
Scrapbox => absolute.py
練習問題
階乗を返す関数を作ろう
def fact(i): # iの階乗を求める関数
# 処理を書く
return [iの階乗の答え]
print(fact(10)) # ちゃんと合ってるか試してみる
Scrapbox => fact.py
def fact(i):
result = i # resultにiを代入
while i > 1:
# iを1つずつ減らしながらresultにiを掛けていく
i -= 1
result *= i
return result
# ちゃんと値を返す
print(fact(10))
演習問題
毒まんじゅう
複数人でやるゲーム
それぞれが順番に1~3個値を言う
30を言ってしまった人が負け
1,2,3
4,5
6
7,8,9
10,11
12
19,20,21
22,23
24,25
26
27,28,29
30…(負け)
一部略
演習問題
毒まんじゅう
人数:2人固定 or キー入力で指定できる
値の増やし方:1~3の値を入力 or 各自工夫
負けになる数:30固定 or キー入力で指定できる
or ランダム(randomモジュールをimport)
最後の数を言ったら勝ちというゲーム
ができるようにしても良い

More Related Content

Featured

How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Applitools
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at WorkGetSmarter
 
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...DevGAMM Conference
 
Barbie - Brand Strategy Presentation
Barbie - Brand Strategy PresentationBarbie - Brand Strategy Presentation
Barbie - Brand Strategy PresentationErica Santiago
 
Good Stuff Happens in 1:1 Meetings: Why you need them and how to do them well
Good Stuff Happens in 1:1 Meetings: Why you need them and how to do them wellGood Stuff Happens in 1:1 Meetings: Why you need them and how to do them well
Good Stuff Happens in 1:1 Meetings: Why you need them and how to do them wellSaba Software
 
Introduction to C Programming Language
Introduction to C Programming LanguageIntroduction to C Programming Language
Introduction to C Programming LanguageSimplilearn
 

Featured (20)

How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work
 
ChatGPT webinar slides
ChatGPT webinar slidesChatGPT webinar slides
ChatGPT webinar slides
 
More than Just Lines on a Map: Best Practices for U.S Bike Routes
More than Just Lines on a Map: Best Practices for U.S Bike RoutesMore than Just Lines on a Map: Best Practices for U.S Bike Routes
More than Just Lines on a Map: Best Practices for U.S Bike Routes
 
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
 
Barbie - Brand Strategy Presentation
Barbie - Brand Strategy PresentationBarbie - Brand Strategy Presentation
Barbie - Brand Strategy Presentation
 
Good Stuff Happens in 1:1 Meetings: Why you need them and how to do them well
Good Stuff Happens in 1:1 Meetings: Why you need them and how to do them wellGood Stuff Happens in 1:1 Meetings: Why you need them and how to do them well
Good Stuff Happens in 1:1 Meetings: Why you need them and how to do them well
 
Introduction to C Programming Language
Introduction to C Programming LanguageIntroduction to C Programming Language
Introduction to C Programming Language
 

K3Python講座2018 - 第3回資料 完全版