直接貼例子:
IF 循環:
#!/usr/bin/python
# Filename: if.py
number = 23
guess = int(raw_input('Enter an integer : '))
if guess == number:
print 'Congratulations, you guessed it.' # New block
starts here
print "(but you do not win any prizes!)" # New block ends
here
elif guess < number:
print 'No, it is a little higher than that' # Another
block
# You can do whatever you want in a block ...
else:
print 'No, it is a little lower than that'
# you must have guess > number to reach
print 'Done'
# This last statement is always executed, after the if
statement is executed
WHILE 循環:
# Filename: while.py
running = True
while running:
print 'Congratulations, you guessed it.'
running = False # this causes the while loop to
stop
print 'No, it is a little higher than that'
print 'The while loop is over.'
# Do anything else you want to do here
FOR 循環:
# Filename: for.py
for i in range(1, 5):
print i
print 'The for loop is over'
很遺憾Python中沒有switch-case 循環;