Python- control statements and functions

  • if-elif-else
  • for
  • while
  • function
    • Function definition
    • Empty function pass
    • Return multiple values
    • variable parameter *
    • Keyword arguments **


Control statements

if - elif - else

For example, enter the user's age, print different content based on age, in a Python program, with the ifstatement to achieve:

1
2
3
4
age = 20
if age >= 18:
print('your age is', age)
print('adult')

Python indentation according to the rules, if ifthe statement judge True, put the two lines indented print statement is executed, otherwise, do nothing.

Also to ifadd a elsesentence, meaning that if the ifjudgment is False, do not perform ifthe content, to the elseimplementation of:

1
2
3
4
5
6
7
age = 3
if age >= 18:
print('your age is', age)
print('adult')
else:
print('your age is', age)
print('teenager')

Be careful not to write less colon :.

Of course, the above determination is very rough, you can use elifto make a more detailed determination:

1
2
3
4
5
6
7
age = 3
if age >= 18:
print('adult')
elif age >= 6:
print('teenager')
else:
print('kid')

elifIs the else ifabbreviation can have more elif, so ifthe full form of the statement is:

1
2
3
4
5
6
7
8
if <condition judgment 1>: 
<1 performs>
elif <conditional 2>:
<performing 2>
elif <conditional 3>:
<performed 3>
the else:
<performed 4>

ifThere is a characteristic statement is executed, it is down from the judge, if a judge is on True, the corresponding statement after the judgment executed, ignore the rest elifand else, so, please explain why the test and the following program print It is teenager:

1
2
3
4
5
6
7
age = 20
if age >= 6:
print('teenager')
elif age >= 18:
print('adult')
else:
print('kid')

ifJudging condition can also be abbreviated, such as writing:

1
2
if x:
print('True')

As long as xa non-zero value, non-empty string, other non-empty list, it is determined Trueotherwise False.


cycle

Python loop, there are two, one is for ... in loop, followed by the list or tuple each element iterative out, look at an example:

1
2
3
names = ['Michael', 'Bob', 'Tracy']
for name in names:
print(name)

The implementation of this code, in turn prints namesof each element:

1
2
3
Michael
Bob
Tracy

So for x in ...cycle each element is assigned to the variable x, and then execute the statement block indentation.

The second loop is the while loop, as long as the conditions are met, continuous cycle, the loop exits when the condition is not satisfied. For example, we want to calculate the sum of all odd-numbered less than 100, can be achieved using a while loop:

1
2
3
4
5
6
sum = 0
n = 99
while n > 0:
sum = sum + n
n = n - 2
print(sum)

The cycle variables ncontinue to decrement, until it was -1time, no longer satisfied while condition loop exits.


function

Function definition

In Python, to be used to define a function defstatement sequentially write the function name, parentheses, brackets and colon parameters :, then, write the function block body is in the retracted, with the return value of the function returnreturn statement.

Empty function pass

If you want a definition of doing nothing is an empty function, you can use passthe statement:

1
2
def nop():
pass

pass语句什么都不做,那有什么用?实际上pass可以用来作为占位符,比如现在还没想好怎么写函数的代码,就可以先放一个pass,让代码能运行起来。

pass还可以用在其他语句里,比如:

1
2
if age >= 18:
pass

缺少了pass,代码运行就会有语法错误。

返回多个值

函数可以返回多个值吗?答案是肯定的。

比如在游戏中经常需要从一个点移动到另一个点,给出坐标、位移和角度,就可以计算出新的新的坐标:

1
2
3
4
5
6
7
8
9
10
import math

def move(x, y, step, angle=0):
nx = x + step * math.cos(angle)
ny = y - step * math.sin(angle)
return nx, ny

>>> x, y = move(100, 100, 60, math.pi / 6)
>>> print(x, y)
151.96152422706632 70.0

但其实这只是一种假象,Python函数返回的仍然是单一值:

1
2
3
>>> r = move(100, 100, 60, math.pi / 6)
>>> print(r)
(151.96152422706632, 70.0)

大专栏  Python-控制语句及函数来返回值是一个tuple!但是,在语法上,返回一个tuple可以省略括号,而多个变量可以同时接收一个tuple,按位置赋给对应的值,所以,Python的函数返回多值其实就是返回一个tuple,但写起来更方便。


默认参数

1
2
3
4
5
6
def power(x, n=2):
s = 1
while n > 0:
n = n - 1
s = s * x
return s

则,我们调用power(5), 相当于调用 power(5, 2)。

1
2
3
4
>>> power(5)
25
>>> power(5, 2)
25

设置默认参数时,有几点要注意:

  • 一是必选参数在前,默认参数在后,否则Python的解释器会报错(思考一下为什么默认参数不能放在必选参数前面)

  • 二是如何设置默认参数。

    当函数有多个参数时,把变化大的参数放前面,变化小的参数放后面。变化小的参数就可以作为默认参数。


可变参数 *

要定义出这个函数,我们必须确定输入的参数。由于参数个数不确定,我们首先想到可以把a,b,c……作为一个list或tuple传进来,这样,函数可以定义如下:

1
2
3
4
5
def calc(numbers):
sum = 0
for n in numbers:
sum = sum + n * n
return sum

但是调用的时候,需要先组装出一个list或tuple:

1
2
3
4
>>> calc([1, 2, 3])
14
>>> calc((1, 3, 5, 7))
84

如果利用可变参数,调用函数的方式可以简化成这样:

1
2
3
4
>>> calc(1, 2, 3)
14
>>> calc(1, 3, 5, 7) // 区别少了 [] ()
84

所以,我们把函数的参数改为可变参数:

1
2
3
4
5
def calc(*numbers):   // 函数定义修改为  *numbers
sum = 0
for n in numbers:
sum = sum + n * n
return sum

定义可变参数和定义一个list或tuple参数相比,仅仅在参数前面加了一个*号。在函数内部,参数numbers接收到的是一个tuple,因此,函数代码完全不变。但是,调用该函数时,可以传入任意个参数,包括0个参数:

1
2
3
4
>>> calc(1, 2)
5
>>> calc()
0

如果已经有一个list或者tuple,要调用一个可变参数怎么办?可以这样做:

1
2
3
>>> nums = [1, 2, 3]
>>> calc(nums[0], nums[1], nums[2])
14

这种写法当然是可行的,问题是太繁琐,所以Python允许你在list或tuple前面加一个*号,把list或tuple的元素变成可变参数传进去:

1
2
3
>>> nums = [1, 2, 3]
>>> calc(*nums)
14

*nums表示把nums这个list的所有元素作为可变参数传进去。这种写法相当有用,而且很常见。


关键字参数 **

可变参数允许你传入0个或任意个参数,这些可变参数在函数调用时自动组装为一个tuple。而关键字参数允许你传入0个或任意个含参数名的参数,这些关键字参数在函数内部自动组装为一个dict。请看示例:

1
2
def person(name, age, **kw):
print('name:', name, 'age:', age, 'other:', kw)

函数person除了必选参数nameage外,还接受关键字参数kw。在调用该函数时,可以只传入必选参数:

1
2
>>> person('Michael', 30)
name: Michael age: 30 other: {}

也可以传入任意个数的关键字参数:

1
2
3
4
>>> person('Bob', 35, city='Beijing')
name: Bob age: 35 other: {'city': 'Beijing'}
>>> person('Adam', 45, gender='M', job='Engineer')
name: Adam age: 45 other: {'gender': 'M', 'job': 'Engineer'}

应用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def test(name, age, **kw):
print("name : " , name, " age = ", age ," other ", kw)
for k in kw:
#print(k, " = ", kw[k])

if k == 'addr':
print("addr = ", kw[k])
elif k == 'phone':
print("phone = ", kw[k])


if __name__ == '__main__':
test('lg', 12, addr='jn', phone='110')

>>phone = 110
>>addr = jn

或者:

1
2
3
4
5
6
7
8
def person(name, age, **kw):
if 'city' in kw:
# 有city参数
pass
if 'job' in kw:
# 有job参数
pass
print('name:', name, 'age:', age, 'other:', kw)

Guess you like

Origin www.cnblogs.com/lijianming180/p/12147621.html