Python教程(五)--if、if else以及注意事项

转载请标明出处:
原文发布于:浅尝辄止,未尝不可的博客
https://blog.csdn.net/qq_31019565

Python教程(五)–if、if else以及注意事项

if 语句

用例子简明扼要的说明用法

###gvim  example_5_1
##age = input("please input your age:")
age = 19
###如果年龄大于18岁,打印 can come in,pritn前面为4个空格。
if age>18:
    print("can come in!") 

如果想使用 input 函数,需要稍微更改一下代码,如下所示:

###gvim : example_5_2
###之前已经讲过input函数。 需要将age的字符串类型转换为int类型。
age = input("please input your age:")
age_num = int(age)
###如果年龄大于18岁,打印 can come in,pritn前面为4个空格。
if age_num>18:
    print("can come in!") 

if else语句

###gvim : example_5_3
age = input("please input your age:")
age_num = int(age)
###如果年龄大于18岁,打印 can come in,pritn前面为4个空格。
if age_num>18:
    print("can come in!") 
elseprint("can not come in !")

关于if语句条件满足后,执行多句语句的格式

###gvim : example_5_4
age = input("please input your age:")
age_num = int(age)
if age_num>18:
    print("can come in!-1") 
    print("can come in!-2")
    print("can come in!-3")
    print("can come in!-4")
    print("can come in!-5")
elseprint("can not come in!-6")
    print("can not come in!-7")
    print("can not come in!-8")
print("can not come in!-9")
print("can not come in!-10")
print("can not come in!-11")
  1. 如上所示代码,else 代码能够影响的范围只有语句6-8。最后三行代码不受if else 语句的影响,是独立的部分。如果需要else语句影响到最后三行代码,则需要将最后三行代码加4个空格,与6-8对齐。
  2. if else 后需要各自加 冒号 (:),并且if 和else需要对齐。

猜你喜欢

转载自blog.csdn.net/qq_31019565/article/details/86488242