Python day04——流程控制

版权声明:本文为小嘉丶学长原创文章,未经博主允许不得转载。 https://blog.csdn.net/fj_Author/article/details/79088983

1、简单输入和输出

在讲解流程控制之前,我们先了解一下两个知识点,input()与print()

1、input()和raw_input()

input([prompt]) -> string
raw_input([prompt]) ->string

上述两个函数,都有一个同样的可选参数prompt。[]表示参数,prompt为提示字符串。如果你指定了该参数将会输出到标准输出,并且不带空行。该函数将会从用户的输入中读取一行,并且转换为字符串(不带有换行符)。

注:

1、Python3.x之中使用input()作为用户输入函数,Python2.x之中使用raw_input()函数作为输入函数

2、不管是input(),还是raw_input(),其返回值都是str类型(字符串)

3、Python2.x之中虽然也是有input()函数,但是我们不建议在Python2.x使用。

input([prompt]) -> value 
raw_input([prompt]) -> string

通过help()内建函数来查看帮助,我们可以发现,raw_input()返回值是string,而input()的返回值是value,这个value的含义就是值的类型。也就是说,如果你输入的类型是整型,那么他就是整型,如果你输入的浮点型,那么他就是浮点型。

在输入字符串的时候却和raw_input()输入的情况不一样。raw_input()输入字符串不需要加引号,而input输入的时候需要加引号。

如果字符串输入的时候不加引号会抛出一个NameError错误,例如:

NameError: name 'a' is not defined

这里我就不过多的讲述这个问题,

2、print()

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

参数一:*objects,该参数为可变参数,也就是说可以是多个;

参数二:sep='',该参数为默认参数,默认值' ',表示分割符,可变参数的分割符;

参数三:end='\n',该参数为默认参数,默认值\n,表示结束符,输出的结尾追加该字符串,也就是说print()默认会打印一个换行

参数四:file=sys.stdout,该参数为默认参数,默认值为sys.stdout,该参数表示要输出的位置,默认为标准输出

参数五:flush=Fasle,该参数为默认参数,默认值为False,表示是否强制刷新缓冲区;

注:

1、在Python2.x之中 print是关键字而不是函数,但在Python3.x之中,print是函数,而不是关键字。

函数必须要加括号,而关键字则不同,可加括号,可不加括号。

在Python2.x之中,用help(print)来查看帮助会抛出一个SyntaxError的错误

2、在Python2.x之中,print语句,如果输出结尾加, 则表示不输出换行,如果不加逗号,则默认就有换行

print_stmt ::=  "print" ([expression ("," expression)* [","]]  | ">>" expression [("," expression)+ [","]])

print 如果改变输出对象可以使用如下语法

print >>file [("," expression)+ [","]])

其中[]里面的内容如果有东西,必须加, 在输出表达式。 例如print >>fp,123,123

Python2之中,print切换输出位置

这一点,我们会在IO操作的时候,重新详细给大家讲解

2、if statement(If 条件分支)

1、 if

在我们的需求之中,我们往往会并不是简单的顺序结构。

条件分支则是通过判断表达式执行结果(True/False)来决定执行哪个分支下的代码块。

使用if语句可以实现单分支结构,if语句的语法形式如下:

     if_stmt ::= "if" expression ":" suite
             ( "elif" expression ":" suite )*
             ["else" ":" suite]

注:

  • *表示前一项零次或多次;
  • +表示前一项一次或多次;
  • []表示零次或一次,换句话说,就是可选的;

上述是BNF规范的写法。如果觉得难以理解的话,可以看下面这个(其中,()表示零个或多个,…表示有多个,[]表示可选0个或一个):

if 条件表达式一 :
    分支一
(elif 条件表达式二 :
    分支二
...)
[else:
    分支三]

案例:输入两个数a,b,判断a是否大于b

# -*- coding:UTF-8 -*-
# Author: XiaoJia

a = float(input())
b = float(input())

if a > b:
    print("a > b")

2、if…else….

大多数情况下并不是只有一条分支路径供你选择,例如,我们要判断一个整数是奇数还是偶数。

num = int(input("please input one integer number: "))
if num % 2 == 0 :
    print(num, " is a even number ")

else:
    print(num, " is a odd number")

3、if…elif…elif…else

多条分支的情况,也是很常见的,例如我们输入一个学生的成绩,判断该成绩是优秀、中等、合格、还是不合格。

score = float(input("please input your score : "))

if score >= 90:
    print("perfect")
elif score >= 70:
    print("good")
elif score >= 60:
    print("qualified")
else:
    print("unqualified")

3、for statement(for loop)

1、range()与xrange()

1、range()

range(stop) -> range object
range(start, stop[, step]) -> range object
  • 参数一:start,表示范围的开始
  • 参数二:stop,表示范围的结束
  • 参数三:step,表示步长

注:

在Python3.x之中,这个range()的返回值是一个range object,而Python2.x之中返回的list of integers(列表)

2、xrange()

xrange(stop) -> xrange object
xrange(start, stop[, step]) -> xrange object

该方法是Python2.x系列有的,在Python3.x系列是没有的,同时该对象也米有start,stop,step属性

2、for…in…

for循环是Python这种最简单的循环,其语法形式如下

    for_stmt ::= "for" target_list "in" expression_list ":" suite
             ["else" ":" suite]

case 1 : please calculate sum from 1 to 100

mysum = 0

for i in range(1,101):
    mysum = mysum + i

print("sum  is  ", mysum)

3、for…else

mysum = 0
for i in range(1,101):
    mysum = mysum + i
else:
    print("else")

print("sum  is  ", mysum)

else的触发条件是循环正常终止(break、return引起的循环结束都不会触发)

Note: There is a subtlety when the sequence is being modified by the loop (this can only occur for mutable sequences, i.e. lists). An internal counter is used to keep track of which item is used next, and this is incremented on each iteration. When this counter has reached the length of the sequence the loop terminates. This means that if the suite deletes the current (or a previous) item from the sequence, the next item will be skipped (since it gets the index of the current item which has already been treated). Likewise, if the suite inserts an item in the sequence before the current item, the current item will be treated again the next time through the loop. This can lead to nasty bugs that can be avoided by making a temporary copy using a slice of the whole sequence, e.g.,

注(这个部分,将在讲列表的时候讲解):

4、while statement(while loop)

1、while

case 1 please calculate sum from 1 to 100

total = 0
i = 0
while i<=100:
    total = total + i
    i = i + 1

print("the sum is ", total)

2、while…else

total = 0
i = 0
while i<=100:
    total = total + i
    i = i + 1
else :
    print("else")
print("the sum is ", total)

else的触发条件是循环正常终止(break、return引起的循环结束都不会触发)

5、死循环

当你循环的条件恒为真的时候,就会出现这样循环条件无法终止的情况。例如while True : suite

6、pass statement

pass_stmt ::=  "pass"

其实就是一个空语句,什么都不执行,在C语言或者c++或Java这种空语句是;

if True:
    pass

while True:
    pass

for x in xrange(1,10):
    pass

def function():
    pass

class Person:
    pass

7、break and continue statement

1、break

break_stmt ::=  "break"

break语句只作用在与for或while循环之中,而不是嵌套没有该循环的函数或类之中。

它会终止最近当前所在的循环,如果循环有else,则会跳过该else。

如果for循环被终止,则循环控制目标保持当前值

如果循环里面有try…exception…else…finally…时候,遇到break之后,会先执行finally语句的内容再退出循环(这一点,我们将在错误处理的时候讲解)

break and continue 官网原文

2、continue

continue_stmt ::=  "continue"

同样continue只发生在for和while循环之中,而不是嵌套在没有这些循环内的函数、类定义和finally之中。它会继续当前循环的下一轮。

如果循环里面有try…exception…else…finally…时候,遇到break之后,会先执行finally语句的内容再进行下一轮循环(这一点,我们将在错误处理的时候讲解)

实例代码:

for i in range(1,10):
    print("当前是第",i,"次循环")
else:
    print('我是else输出的结果')

print("----------分割线------------")

for i in range(1,10):
    if i == 5:
        break
    print("当前是第",i,"次循环")
else:
    print('我是else输出的结果')



print("----------分割线------------")

for i in range(1,10):
    if i == 5:
        continue
    print("当前是第",i,"次循环")
else:
    print('我是else输出的结果')

猜你喜欢

转载自blog.csdn.net/fj_Author/article/details/79088983