python入门基础篇(二)

此篇承接

python入门基础篇(一)

Python提供了for循环和while循环(在Python中没有do..while循环):

一、循环类型

循环类型 描述
while 循环 在给定的判断条件为 true 时执行循环体,否则退出循环体。
for 循环 重复执行语句
嵌套循环 你可以在while循环体中嵌套for循环

  循环控制语句

循环控制语句可以更改语句执行的顺序。Python支持以下循环控制语句:

控制语句 描述
break 语句 在语句块执行过程中终止循环,并且跳出整个循环
continue 语句 在语句块执行过程中终止当前循环,跳出该次循环,执行下一次循环。
pass 语句 pass是空语句,是为了保持程序结构的完整性。

1.1   while  例子

count = 0
while (count <3):
    print('The count is:', count)
    count = count + 1

print ("Good bye!")

输入结果是

The count is: 0
The count is: 1
The count is: 2
Good bye!

加点控制

count = 0
while (count <5):
    if count == 2:
        count = count + 1
        continue
    if count == 4:
        break
    print('The count is:', count)
    count = count + 1

print ("Good bye!")

The count is: 0
The count is: 1
The count is: 3
Good bye!

分析:当count 为 0,1时,会直接打印 0,1 

          当count 为 2 时,count 变为 3 退出当前循环 进入下次循环,

          当count为3时,直接打印 3

          当count 为4时,直接退出循环

二、Python 函数

     python 的函数就是一个方法,做单一的事情,可被重复调用

    具体定义如下

 2.1 函数定义

  • 函数代码块以 def 关键词开头(必须以def开头),后接函数标识符名称和圆括号()
  • 任何传入参数和自变量必须放在圆括号中间。圆括号之间可以用于定义参数。
  • 函数的第一行语句可以选择性地使用文档字符串—用于存放函数说明。
  • 函数内容以冒号起始,并且缩进。
  • return [表达式] 结束函数,选择性地返回一个值给调用方。不带表达式的return相当于返回 None。

 简单公式为 

def  functionname( parameters ):

      detail   # 逻辑代码 

return [expression]  #返回值  可以不写

2.2 函数调用

# 定义函数
def printme( str ):
    "打印任何传入的字符串"
    print(str)
    return

# 调用函数
printme("我要调用用户自定义函数!");
printme("再次调用同一函数");

输入结果是:

我要调用用户自定义函数!
再次调用同一函数

发布了57 篇原创文章 · 获赞 22 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/yb546822612/article/details/93603090