Python基礎-函數1(遺留問題)

基礎函數的運用

>>> abs(-199)
199


>>> abs(200,100)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: abs() takes exactly one argument (2 given)


>>> abs('abc')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: bad operand type for abs(): 'str'


>>> max(-100.3,200,3.5)
200
>>> min(-100.3,200,3.5)
-100.3


>>> int('123')
123

>>> int('12.9')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '12.9'
>>> int('12.34')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '12.34'

>>> int(12.34)
12

2.自定義函數

預留問題
在這裏插入圖片描述

zhengyoncongdeMacBook-Pro:python zhengyoncong$ cat my_abs.py 
#! /usr/bin/env

def my_abs(x)
	if(x>0):
		return x
	else:
		return -x
print(my_abs(-99))

運行結果:

zhengyoncongdeMacBook-Pro:python zhengyoncong$ ./myabs.py 
99

但如果輸入參數非整數,報錯:

zhengyoncongdeMacBook-Pro:python zhengyoncong$ ./myabs.py 
Traceback (most recent call last):
  File "./myabs.py", line 8, in <module>
    print(my_abs('hhh'))
  File "./myabs.py", line 4, in my_abs
    if(x>0):
TypeError: '>' not supported between instances of 'str' and 'int'

直接調用內置函數abs(),輸入字符參數,則會拋出異常

>>> abs('hheh')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: bad operand type for abs(): 'str'

解決辦法:在自定義函數時添加參數檢查,如果傳入錯誤的參數類型,則拋出異常

#! /usr/bin/env python3

def my_abs(x):
  
	if not isinstance(x,(int ,float)):
		raise TypeError('bad operand type')
	if(x>0):
		return x
	else:
		return -x
print(my_abs('hhh'))

運行結果:

zhengyoncongdeMacBook-Pro:python zhengyoncong$ ./myabs.py 
Traceback (most recent call last):
  File "./myabs.py", line 11, in <module>
    print(my_abs('hhh'))
  File "./myabs.py", line 6, in my_abs
    raise TypeError('bad operand type')
TypeError: bad operand type

多返回值

import math(必須放置在文件開頭,不能放置在註釋語句或其他語句之後)

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

#連個返回值
x,y = move(100,100,60,math.pi/6)
print(x,y)
#一個返回值
z=move(100,100,60,math.pi/6)
print(z)

運行結果:
zhengyoncongdeMacBook-Pro:python zhengyoncong$ ./myabs.py 
151.96152422706632 70.0
(151.96152422706632, 70.0)

結果解釋:

返回的是一個元組,多返回值的也是同一個值元組,只不過是按位置分配相應的值(多返回值接受的變量與多返回值的個數應該與之對應,否則會報錯)
如:在最後添加一組三個變量接受返回值

a,b,c = move(100,100,60,math.pi/6)
print(a,b,c)

報錯顯示:

zhengyoncongdeMacBook-Pro:python zhengyoncong$ ./myabs.py 
151.96152422706632 70.0
(151.96152422706632, 70.0)
Traceback (most recent call last):
  File "./myabs.py", line 25, in <module>
    a,b,c = move(100,100,60,math.pi/6)
ValueError: not enough values to unpack (expected 3, got 2)

總結:
自定義函數使用時,要注意函數參數個數及類型,不符合則會報錯或拋異常。
函數可以有多個返回值,但實際只有返回值,返回值類型爲元組。

定義函數時,函數體內部隨時可用return返回,如果函數結束都沒有return ,則默認返回None
函數體爲空時,用pass佔位。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章