先看一个例子:
def clinic():
print "You've just entered the clinic!"
print "Do you take the door on the left or the right?"
answer = raw_input("Type left or right and hit 'Enter'.").lower()
if answer == "left" or answer == "l":
print "This is the Verbal Abuse Room, you heap of parrot droppings!"
elif answer == "right" or answer == "r":
print "Of course this is the Argument Room, I've told you that already!"
else:
print "You didn't pick left or right! Try again."
clinic()
clinic()
运行结果是:
You've just entered the clinic!
Do you take the door on the left or the right?
Type left or right and hit 'Enter'. r
You didn't pick left or right! Try again.
You've just entered the clinic!
Do you take the door on the left or the right?
Type left or right and hit 'Enter'. right
Of course this is the Argument Room, I've told you that already!
先不解释,继续下去。下面是Python中的if_else语句:
if expression1:
expr1_true_suite #四个空格
elif expression2:
expr2_true_suite #四个空格
elif expressionN:
exprN_true_suite #四个空格
else:
none_of_the_above_suite #四个空格
而如果if语句嵌套的话:
if EXPRESSION:
#line one
#line two
#line three
简单小例,这个例子需要注意,函数的声明需要‘:’,同时空四格,if之后又空四格。
def using_control_once():
if 1<2:
return "Success #1"
def using_control_again():
if 2<3:
return "Success #2"
print using_control_once()
print using_control_again()
注意下面这个例子中raw_input函数的使用和int函数的使用,raw_input函数接受的字符,而in将这个字符数字转换为整型
first_number = 23
second_number = int(raw_input("Input the second_number: "))
if first_number==second_number:
print "first_number==second_number"
elif first_number<second_number:
print "first_number<second_number"
else:
print "first_number>second_number"
另外的一个有关函数和if_elif_else的例子:
def greater_less_equal_5(answer):
if answer>5:
return 1
elif answer<5:
return -1
else:
return 0
print greater_less_equal_5(4)
print greater_less_equal_5(5)
print greater_less_equal_5(6)