2
1

More than 3 years have passed since last update.

Pythonの超基本文法カンニング用プログラム_フロー制御文ver

Last updated at Posted at 2020-07-01

仕事でプログラミングをしないが趣味でpythonを始めた私自身のためのチートシート。初学者の方は「思い出す」作業にどうぞお使いください。

超基本文法について理解しているものの、python独特の書き方をすぐ忘れるのでカンニング用プログラム。

確認環境:Python3.7.6

フロー制御① if文

01_if.py
#末尾の:忘れがち。
print('あなたの名前を入力してください。Alice,usagi,etc...')
name = input()
if name =='Alice':
  print('やぁ、Alice.')
elif name == 'usagi':
  print('どうも白うさぎさん')
else:
  print('初めまして、' + name  + '.')
出力例(Aliceと入力すると)
あなたの名前を入力してくださいAlice,usagi,etc...
Alice
やぁAlice.

フロー制御② whileループ

02_while.py
#無限ループになったらCtrl+C
spam = 0
while spam < 5:
  print('Hello,world.')
  spam = spam +1
出力結果
Hello,world.
Hello,world.
Hello,world.
Hello,world.
Hello,world.
03_while_break.py
#breakはループを抜ける処理
while True:
  print('あなたの名前を入力してください。')
  name = input()
  if name == 'あなたの名前':
    break
print('どうも!')
出力例(「あなたの名前」と入力すればループが終わる。)
あなたの名前を入力してください
alice
あなたの名前を入力してください
Aceli
あなたの名前を入力してください
Alice
あなたの名前を入力してください
あなたの名前                  
どうも
04_while_continue.py
#continueはループの最初に戻る処理。
while True:
  print('Alice,あなたは何歳?')
  age = input()
  if age != '15':
    continue
  print('そう、あなたは15歳。ここはどこ?')
  world = input()
  if world == '不思議の国':
    break
print('そう、ここは不思議の国。')
出力例(「15」「不思議の国」と入力すればループが終わる。)
Alice,あなたは何歳
15
そうあなたは15歳ここはどこ
日本
Alice,あなたは何歳
14
Alice,あなたは何歳
15
そうあなたは15歳ここはどこ
不思議の国
そうここは不思議の国

フロー制御③ forループとrange()

05_for_range.py
#回数を指定してループ
#rangeの数字は0からスタート。
print('うらめしやー')
for i in range(6):
  print('お皿が、' + str(i) + '枚、、、')
print('キャーーーーー!')
出力結果
うらめしやー
お皿が0、、、
お皿が1、、、
お皿が2、、、
お皿が3、、、
お皿が4、、、
お皿が5、、、
キャーーーーー
06_for_range_from_to.py
#開始値と終了値をrangeに指定
print('うらめしやー')
for i in range(1,8):
  print('お皿が、' + str(i) + '枚、、、')
print('どわーーーーーーーーー!')
出力結果
うらめしやー
お皿が1、、、
お皿が2、、、
お皿が3、、、
お皿が4、、、
お皿が5、、、
お皿が6、、、
お皿が7、、、
どわーーーーーーーーー
07_for_range_from_to_step.py
#開始値と終了値と増加値をrangeに指定
print('うらめしやー')
for i in range(1,15,3):
  print('お皿が、' + str(i) + '枚、、、')
print('めんどくさいので3枚ずつ数えてみましたわ。ウフフ')
出力結果
うらめしやー
お皿が1、、、
お皿が4、、、
お皿が7、、、
お皿が10、、、
お皿が13、、、
めんどくさいので3枚ずつ数えてみましたわウフフ

フロー制御④ sys.exit()

08_exit.py
#import sysが必要
import sys

while True:
  print('終了するにはexitと入力してください')
  response = input()
  if response == 'exit':
    sys.exit()
  print(response + 'と入力されました。')
出力結果
終了するにはexitと入力してください
a
aと入力されました
終了するにはexitと入力してください
i
iと入力されました
終了するにはexitと入力してください
exit
2
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
2
1