LoginSignup
0
3

More than 5 years have passed since last update.

【初学者向け】Python 基礎2 ブロックとfor文if文

Last updated at Posted at 2018-03-21

これまで

・インストール方法
・Pythonプログラムの作成&実行
・【初学者向け】Python 基礎1 関数定義と呼び出し

初学者向けのためのご参考。
間違いやもっと良い方法などありましたらご指摘頂けると嬉しいです。

▽環境
Python 3.6.4

ブロックについて

PythonではJavaなどで書く{}はインデントで表す。
他の言語ではインデントはあくまで人間が理解し易いようにする為であるが、Pythonでは意味がある事に注意。

main.java
public static void main(String[] args){
    System.out.println("考える前に");
}
main.py
def main():
    print('行動')

インデントとはタブ?空白4文字?2文字?
空白が全くないと「IndentationError: expected an indented block」エラーが発生するが1文字でも空白があるとPGM上は動作するようだ。

Pythonのコーディング規約PEP8では空白4文字を推奨している。

for文

for1
for i in 'する!':
    print(i)
結果
す
る
!
for2
for i in range(5):
    sys.stdout.write('i=%s ' %(i))
結果
i=0 i=1 i=2 i=3 i=4

range関数についてはここが詳しい
【Python入門】range関数で繰り返し処理をする方法とは?

if文

if1
for i in range(10):
    if (i == 1) or (i == 3):
        i = 0
    elif (i == 2):
        i = 9
    elif (i == 6):
        break # 直近のループを抜ける
              # continue で次のループへ
    else:
        i = '*'
    sys.stdout.write('i=%s ' % i)
結果
i=* i=0 i=9 i=0 i=*
論理演算子 意味
and かつ
or または
not 真偽値反転
0
3
2

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
0
3