Beginning Python From Novice to Professional (5) - 条件与循环

条件与循环

条件执行:

name = raw_input('What is your name? ')
if name.endswith('Gumby'):
	print 'Hello, Mr.Gumby'
What is your name? Gumby
Hello, Mr.Gumby
name = raw_input('What is your name? ')
if name.endswith('Gumby'):
	print 'Hello, Mr.Gumby'
else:
	print 'Hello, stranger'
多个条件:

num = input('Enter a number: ')
if num > 0:
	print 'The number is positive'
elif num < 0:
	print 'The number is negative'
else:
	print 'The number is zero'
Enter a number: 5
The number is positive
Enter a number: -1
The number is negative
Enter a number: 0
The number is zero
while循环:

x = 1
while x<=100:
	print x
	x+=1
for循环:

numbers = [0,1,2,3,4,5,6,7,8,9]
for number in numbers:
	print number
0
1
2
3
4
5
6
7
8
9
循环中的else:

for n in range(99,81,-1):
	root = sqrt(n)
	if root == int(root):
		print n
		break
else:                                #只在没有调用break时执行
	print "Didn't find it!"

你可能感兴趣的:(python)