#!/usr/bin/python
i = 5
print i
i = i + 1
print i
s1 = '''This is a multi-line string.\
This is the second line.'''
s2 = '''This is a multi-line string.
This is the second line.'''
print s1
print s2
#!/usr/bin/python
# Filename:expression.py
length = 5
breadth = 2
area = length * breadth
print 'Area is', area
print 'Perimeter is', 2 * (length + breadth)
使用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 blockstarts here
print "(but you do not win any prizes!)"
elif guess < number:
print 'No, it is a little higher than that.'
#Another block
else:
print 'No, it is a little lower than that'
print 'Done'
# This last statement is always executed, after the ifstatement is executed
使用while语句
#!/usr/bin/python
# Filename: while.py
number = 23
running = True
while running:
guess = int(raw_input('Enter an integer : '))
if guess == number:
print 'Congratulations, you guessed it.'
running = False # this causes the while loop tostop
elif guess < number:
print 'No, it is a little higher than that.'
else:
print 'No, it is a little lower than that.'
else:
print 'The while loop is over.'
# Do anything else you want to do here
print 'Done'
#!/usr/bin/python
# Filename: while.py
number = 23
running = True
while running:
guess = int(raw_input('Enter an integer : '))
if guess == number:
print 'Congratulations, you guessed it.'
break #直接跳出while,下面的print 'The while loop is over.'不执行
elif guess < number:
print 'No, it is a little higher than that.'
else:
print 'No, it is a little lower than that.'
#当while循环条件变为False的时候,else块才被执行
else:
print 'The while loop is over.'
# Do anything else you want to do here
print 'Done'
记住,你可以在while循环中使用一个else从句。
for循环
for..in是另外一个循环语句,它在一序列的对象上 递归 即逐一使用队列中的每个项目
#!/usr/bin/python
# Filename: for.py
for i in range(1, 5):
print i
else:
print 'The for loop is over.'
默认地,range的步长为1
如果我们为range提供第三个数,那么它将成为步长。例如,range(1,5,2)给出[1,3]。记住,range 向上 延伸到第二个数,即它不包含第二个数。
记住,else部分是可选的。如果包含else,它总是在for循环结束后执行一次,除非遇到break语句。
记住,for..in循环对于任何序列都适用。这里我们使用的是一个由内建range函数生成的数的列表,但是广义说来我们可以使用任何种类的由任何对象组成的序列!
如果你想要写for (int i = 0; i < 5; i++),那么用Python,你写成for i in range(0,5)。
阅读(1147) | 评论(0) | 转发(0) |