Conditionls&Control Flow

先看一个例子:

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值