目錄
基礎 Python 學習路線推薦 : Python 學習目錄 >> Python 基礎入門
一.Python pow 函數介紹
在 Python 中內置函數 pow 共有兩個參數,x 和 y,並返回 xy(x 的 y 次方) 的值,語法如下:
'''
參數介紹:
x — 數值表達式(整數或者浮點數);
y — 數值表達式(整數或者浮點數);
z — 數值表達式(整數或者浮點數),默認不設置z值;
返回值:返回 xy(x的y次方)的值;如果設置了z值,則再對結果進行取模,其結果等效於pow(x,y) %z;
'''
pow(x, y[, z])
二.Python pow 函數使用
案例 1:pow 函數常規使用
# !usr/bin/env python
# !usr/bin/env python
# -*- coding:utf-8 _*-
"""
@Author:猿說編程
@Blog(個人博客地址): www.codersrc.com
@File:Python pow 函數.py
@Time:2021/04/19 07:37
@Motto:不積跬步無以至千里,不積小流無以成江海,程序人生的精彩需要堅持不懈地積累!
"""
print(pow(2,5)) # 等價 2*2*2*2*2 = 32
print(pow(2,3)) # 等價 2*2*2 = 8
print(pow(2,3,5)) # 等價 2*2*2%5 = 8 % 5 = 3
print(2*2*2%5) # 等價 pow(2,3,5) = 3
'''
輸出結果:
32
8
3
3
'''
案例 2:pow 函數所有的參數必須是數值類型,不能是其他類型,否則報錯 TypeError
# !usr/bin/env python
# !usr/bin/env python
# -*- coding:utf-8 _*-
"""
@Author:猿說編程
@Blog(個人博客地址): www.codersrc.com
@File:Python pow 函數.py
@Time:2021/04/19 07:37
@Motto:不積跬步無以至千里,不積小流無以成江海,程序人生的精彩需要堅持不懈地積累!
"""
print(pow(2,'2'))
'''
產生異常:
Traceback (most recent call last):
File "E:/Project/python_project/untitled10/123.py", line 18, in <module>
print(pow(2,'2'))
TypeError: unsupported operand type(s) for ** or pow(): 'int' and 'str'
'''
案例 3:若果 x,y 有一個浮點數,則結果將轉換為浮點數
# !usr/bin/env python
# !usr/bin/env python
# -*- coding:utf-8 _*-
"""
@Author:猿說編程
@Blog(個人博客地址): www.codersrc.com
@File:Python pow 函數.py
@Time:2021/04/19 07:37
@Motto:不積跬步無以至千里,不積小流無以成江海,程序人生的精彩需要堅持不懈地積累!
"""
print(pow(2,3.2))
print(pow(2,3.0))
'''
輸出結果:
9.18958683997628
8.0
'''
三.猜你喜歡
- Python for 循環
- Python 字符串
- Python 列表 list
- Python 元組 tuple
- Python 字典 dict
- Python 條件推導式
- Python 列表推導式
- Python 字典推導式
- Python 函數聲明和調用
- Python 不定長參數 *argc/**kargcs
- Python 匿名函數 lambda
- Python return 邏輯判斷表達式
- Python 字符串/列表/元組/字典之間的相互轉換
- Python 局部變量和全局變量
- Python type 函數和 isinstance 函數區別
- Python is 和 == 區別
- Python 可變數據類型和不可變數據類型
- Python 淺拷貝和深拷貝
未經允許不得轉載:猿說編程 » Python pow 函數
本文由博客 - 猿說編程 猿說編程 發布!
