Latest web development tutorials

whileループのPython

Pythonプログラミングループ文がプログラムを実行するために使用されている間、つまり、特定の条件下で、ループは、特定の手順は、プロセスを処理するために、同じ作業を繰り返す必要が実行されます。 基本的な形式は次のとおりです。

while 判断条件:
    执行语句……

文が単一のステートメントまたはブロックすることができます実行します。 条件を分析する任意の式、任意の非ゼロとすることができ、非空(ヌル)の値が両方とも真です。

とき判定条件偽偽、ループは終了します。

次のように執行するためのフローチャートです。

python_while_loop

例:

#!/usr/bin/python

count = 0
while (count < 9):
   print 'The count is:', count
   count = count + 1

print "Good bye!"

実行中のインスタンス>>

上記のコードは出力が実行されます。

The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!

while文は、2つの重要なコマンドは、サイクルをスキップする破る、引き続きこのサイクルをスキップし続けていた場合、ブレークは「条件を決定」に加えて、ループを終了するために使用されてもでなければならないループを表す定数値とすることができます次のように確立は、使用されています。

# continue 和 break 用法

i = 1
while i < 10:   
    i += 1
    if i%2 > 0:     # 非双数时跳过输出
        continue
    print i         # 输出双数2、4、6、8、10

i = 1
while 1:            # 循环条件为1必定成立
    print i         # 输出1~10
    i += 1
    if i > 10:     # 当i大于10时跳出循环
        break
 


無限ループ

条件文が常に真である場合、無限ループが例以下、それを実行します:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

var = 1
while var == 1 :  # 该条件永远为true,循环将无限执行下去
   num = raw_input("Enter a number  :")
   print "You entered: ", num

print "Good bye!"

上記の出力の例:

Enter a number  :20
You entered:  20
Enter a number  :29
You entered:  29
Enter a number  :3
You entered:  3
Enter a number between :Traceback (most recent call last):
  File "test.py", line 5, in <module>
    num = raw_input("Enter a number :")
KeyboardInterrupt

注:上記の無限ループは、あなたはサイクルを中断するために、Ctrl + Cを使用することができます。



リサイクルelseステートメント

Pythonでは、のために...他の一方で文と普通の差がないために、elseステートメントは、(すなわちのために外にブレークによって中断されていない)の実行終了の通常サイクルの場合に実行されるので、平均表現...それ以外は同じです。

#!/usr/bin/python

count = 0
while count < 5:
   print count, " is  less than 5"
   count = count + 1
else:
   print count, " is not less than 5"

上の例の出力は、次のとおりです。

0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5


シンプルなステートメントグループ

あなたが唯一の1文である場合、以下のようにあなたは、同じ行に文を書くことができますが構文は、whileループ、if文に似ています。

#!/usr/bin/python

flag = 1

while (flag): print 'Given flag is really true!'

print "Good bye!"

注:上記の無限ループは、あなたはサイクルを中断するために、Ctrl + Cを使用することができます。