python中的power函数_python中pow如何使用内置调用?

本文介绍了Python中的内置pow()函数,讲解了其返回值和参数的使用,包括不同参数设置下的功能,如计算次方、取模等,并通过示例展示了其与math.pow()的区别。同时,文章还提到了参数类型限制和负指数的处理情况。
摘要由CSDN通过智能技术生成

我们在用函数调用的时候一般是要考虑函数的返回值,其次就是参数的问题。相信经过之前几篇参数文章的讲解,大部分小伙伴已经对参数不陌生了。那么今天我们就来讲讲常见返回值的问题。这里以pow函数的调用为例,在学习使用方法的同时,我们会试着找寻内置调用返回值得结果以及进行结果分析。

pow() 方法返回 xy(x 的 y 次方) 的值。

math 模块 pow() 方法的语法:import math

math.pow(x, y)

内置的 pow() 方法:pow(x, y[, z])

函数是计算 x 的 y 次方,如果 z 在存在,则再对结果进行取模,其结果等效于 pow(x,y) %z。

注意:pow() 通过内置的方法直接调用,内置方法会把参数作为整型,而 math 模块则会把参数转换为 float。

举例:# pow(base, exp[, mod])

# pow power exp exponent mod module

# 返回 base 的 exp 次幂;如果 mod 存在,则返回 base 的 exp 次幂对 mod 取余(比 pow(base, exp) % mod 更高效)。 两参数形式 pow(base, exp) 等价于乘方运算符: base**exp。

# 返回 base 的 exp 次幂;

print(f'{ pow(2, 3) = }')

print(f'{ pow(10, 2) = }')

# 两参数形式 pow(base, exp) 等价于乘方运算符: base**exp。

print(f'{ 2**3 = }')

print(f'{ 10**2 = }')

# 如果 mod 存在,则返回 base 的 exp 次幂对 mod 取余(比 pow(base, exp) % mod 更高效)

# 如果mod存在,会使用快速幂取模的算法来取模

import time

start = time.time()

print(f'{ pow(1234, 1234567, 67) = }')

end = time.time()

print(f' 耗时:{ end - start = } ')

# start = time.time()

# print(f'{ pow(1234, 1234567) % 67 = }')

# end = time.time()

# print(f' 耗时:{ end - start = } ')

#

# 参数必须具有数值类型。 对于混用的操作数类型,则将应用双目算术运算符的类型强制转换规则。 对于 int 操作数,结果具有与操作数相同的类型(强制转换后),除非第二个参数为负值;在这种情况下,所有参数将被转换为浮点数并输出浮点数结果。 例如,10**2 返回 100,但 10**-2 返回 0.01。

# 参数必须具有数值类型

# print(f'{ pow(2, "3") = }')

# 对于混用的操作数类型,则将应用双目算术运算符的类型强制转换规则。

print(f'{ pow(2.0, 3) = }')

# 对于 int 操作数,结果具有与操作数相同的类型(强制转换后),除非第二个参数为负值;在这种情况下,所有参数将被转换为浮点数并输出浮点数结果。

print(f'{ pow(2, 3) = }')

print(f'{ pow(2, -3) = }')

#

# 对于 int 操作数 base 和 exp,如果给出 mod,则 mod 必须为整数类型并且 mod 必须不为零。 如果给出 mod 并且 exp 为负值,则 base 必须相对于 mod 不可整除。 在这种情况下,将会返回 pow(inv_base, -exp, mod),其中 inv_base 为 base 的倒数对 mod 取余。

#

# 对于 int 操作数 base 和 exp,如果给出 mod,则 mod 必须为整数类型并且 mod 必须不为零。

# print(f'{ pow(2, 3, 0) = }')

# 下面的例子是 38 的倒数对 97 取余:

#

# >>>

# >>> pow(38, -1, mod=97)

# 23

# >>> 23 * 38 % 97 == 1

# True

# 在 3.8 版更改: 对于 int 操作数,三参数形式的 pow 现在允许第二个参数为负值,即可以计算倒数的余数。

#

# 在 3.8 版更改: 允许关键字参数。 之前只支持位置参数。

以上就是python中pow函数使用内置调用的方法,最后对于参数的输出和math有所不同,这点需要引起大家的注意。

CHAPTER 1 About Python ............................................................................................1 What Is Python? ................................................................................................................1 A Brief History of Python ................................................................................................2 Interpreters Versus Compilers .......................................................................................5 When to Use (or Not Use) an Interpreted Language .........................................8 Understanding Bytecodes ......................................................................................10 Why Use Python? ...........................................................................................................11 Object-Oriented ........................................................................................................11 Cross Platform ..........................................................................................................11 Broad User Base .......................................................................................................11 Well Supported in Third-Party Tools ...................................................................12 Good Selection of Tools Available ........................................................................12 Good Selection of Pre-built Libraries ..................................................................12 Where Is Python Used? .................................................................................................13 How Is Python Licensed? ..............................................................................................13 Where Do I Get Python? ...............................................................................................14 Installing Python ............................................................................................................14 Getting Information on Python ..................................................................................16 Python Communities .....................................................................................................17 Other Software ................................................................................................................18 And Now for Something Completely Different… ....................................................18 CHAPTER 2 Python Language Overview .................................................................19 Python Syntax .................................................................................................................20 Comments .................................................................................................................20 Indentation ...............................................................................................................20 Contents TABLE OF} vii Q Q Q Python Reserved Words ................................................................................................24 Decision Making and Iteration Keywords ..........................................................25 Debugging Keywords ..............................................................................................27 Package and Module Handling Keywords .........................................................27 Exception Handling Keywords ..............................................................................29 General Language Keywords .................................................................................31 Other Keywords ........................................................................................................32 Variable Usage ................................................................................................................34 The Continuation Variable ....................................................................................36 Watching Out for Spelling Mistakes! ..................................................................37 Predicates .........................................................................................................................38 Identifier Scope ...............................................................................................................39 Operators .........................................................................................................................42 Modulo Operator .....................................................................................................44 Exponential Operator .............................................................................................46 Logical Operators ....................................................................................................46 Comparative Operators ..........................................................................................49 Bitwise Operators ....................................................................................................51 Membership Operators and String Operators ..................................................53 Identity Operators ...................................................................................................53 In Conclusion ..................................................................................................................53 CHAPTER 3 Tools ..........................................................................................................55 IDLE ...................................................................................................................................55 File Menu ...................................................................................................................57 The Path Browser Dialog ........................................................................................62 Edit Menu ..................................................................................................................64 Shell Menu .................................................................................................................70 Debug Menu ..............................................................................................................71 The Edit Window ......................................................................................................79 Format Menu ............................................................................................................80 CONTENTS viii Q Q Q Command Line Compiler ..............................................................................................90 Creating Python Files ....................................................................................................93 Documentation ...............................................................................................................95 In Conclusion ..................................................................................................................96 CHAPTER 4 Data Types ...............................................................................................97 Numeric Types ................................................................................................................98 Integers ......................................................................................................................98 Demonstrating Long Integers ...............................................................................99 Octal and Hexadecimal ........................................................................................100 Floating Point Numbers .............................................................................................101 Strings ............................................................................................................................103 String Variables .....................................................................................................103 Concatenating Strings .........................................................................................106 Repeating Strings ..................................................................................................107 Substrings ...............................................................................................................108 Slicing ......................................................................................................................110 String Functions ....................................................................................................111 String Constants ....................................................................................................112 Conversion Functions ...........................................................................................114 Search Functions ...................................................................................................118 Formatting Functions ..........................................................................................120 Escape Sequences ..................................................................................................121 Sequences ......................................................................................................................122 Lists ..........................................................................................................................123 Shared References .................................................................................................128 Tuples .......................................................................................................................128 Dictionaries ............................................................................................................132 Advanced Type .............................................................................................................136 Classes and Objects ..............................................................................................136 Complex Type .........................................................................................................137 Generator Type ......................................................................................................138 CONTENTS ix Q Q Q None Type ...............................................................................................................139 Unicode Type ..........................................................................................................140 In Conclusion ................................................................................................................141 CHAPTER 5 Control Flow .........................................................................................143 Conditionals ..................................................................................................................144 The if Statement ..................................................................................................144 The elif Statement .............................................................................................147 The else Statement .............................................................................................149 Wrapping Up the Conditionals: A Cool Example ...........................................150 Loops ..............................................................................................................................153 The for Loop ..........................................................................................................153 The while Loop .....................................................................................................161 In Conclusion ................................................................................................................164 CHAPTER 6 Input and Output ................................................................................165 User Input ......................................................................................................................165 The input Function ..............................................................................................166 The raw_input Function ....................................................................................168 User Output ...................................................................................................................170 Formatting ..............................................................................................................172 File Input .......................................................................................................................175 File Output ....................................................................................................................177 Closing Files ..................................................................................................................179 Positioning in Files ......................................................................................................180 Directories and Files ...................................................................................................183 The stat Module: File Statistics ..............................................................................186 Command Line Arguments ........................................................................................190 Pickle ..............................................................................................................................192 In Conclusion ................................................................................................................195 CONTENTS x Q Q Q CHAPTER 7 Functions and Modules .....................................................................197 What Is a Function? ....................................................................................................197 Defining Functions in Python ...................................................................................197 What Are Arguments? ................................................................................................200 How Do You Pass an Argument to a Function? ....................................................201 Default Arguments ......................................................................................................203 Variable Default Arguments .....................................................................................205 Keyword Arguments ....................................................................................................206 Returning Values from Functions ............................................................................207 Returning Multiple Values from Functions ...........................................................209 Recursive Functions ....................................................................................................210 Passing Functions as Arguments .............................................................................212 Lambda Functions .......................................................................................................213 Variable Numbers of Arguments to a Function ....................................................215 Variable Scope in Functions ......................................................................................216 Using Modules ..............................................................................................................218 In Conclusion ................................................................................................................219 CHAPTER 8 Exception Handling ............................................................................221 Looking at Exceptions in Python ..............................................................................222 Traceback Example ......................................................................................................223 Understanding Tracebacks ........................................................................................224 Exceptions .....................................................................................................................225 Catching Exceptions with try..except .........................................................226 Multiple except Clauses .....................................................................................229 Blank except Clauses ..........................................................................................231 The else Clauses .........................................................................................................232 The finally Clause ....................................................................................................234 Raising Your Own Exceptions ...................................................................................235 Exception Arguments .................................................................................................237 User-Defined Exceptions ............................................................................................238 Working with the Exception Information ..............................................................239 CONTENTS xi Q Q Q exc_type ................................................................................................................239 exc_value ..............................................................................................................240 Using the with Clause for Files ................................................................................243 Re-throwing Exceptions .............................................................................................244 In Conclusion ................................................................................................................246 CHAPTER 9 Object-Oriented Programming .........................................................247 A Brief History of OOP ................................................................................................247 What Is an Object? ......................................................................................................248 Why Do We Use Objects? ...........................................................................................249 Reuse ........................................................................................................................249 Ease in Debugging .................................................................................................250 Maintainability ......................................................................................................250 The Attributes of Object-Oriented Development .................................................251 Abstraction .............................................................................................................251 Data Hiding ............................................................................................................252 Inheritance .............................................................................................................253 Polymorphism ........................................................................................................255 Terminology ..................................................................................................................256 Class .........................................................................................................................256 Object .......................................................................................................................256 Attribute ..................................................................................................................257 Method ....................................................................................................................258 Message Passing ....................................................................................................259 Event Handling ......................................................................................................260 Derivation ...............................................................................................................260 Coupling ..................................................................................................................261 Cohesion ..................................................................................................................261 Constants ................................................................................................................261 Other Concepts .............................................................................................................262 In Conclusion ................................................................................................................262 CONTENTS xii Q Q Q CHAPTER 10 Classes and Objects in Python ..........................................................265 Python Classes ..............................................................................................................265 Properties ......................................................................................................................267 Attribute Modifying Functions .................................................................................272 Private Attributes ........................................................................................................274 Doc Strings ....................................................................................................................275 Properties ......................................................................................................................277 The self Object ...........................................................................................................279 Methods .........................................................................................................................281 Special Methods ...........................................................................................................283 Initialization ...........................................................................................................283 Termination ............................................................................................................284 String Conversion ..................................................................................................285 Inheritance ....................................................................................................................287 Multiple Inheritance ...................................................................................................291 Using super ..................................................................................................................293 Polymorphism ..............................................................................................................295 Exception Classes .........................................................................................................297 Iterators .........................................................................................................................299 Operator Overloading .................................................................................................301 In Conclusion ................................................................................................................304 CHAPTER 11 The Python Library ..............................................................................305 Containers .....................................................................................................................305 Working with the deque Class ...........................................................................306 Math ................................................................................................................................312 Complex Math ..............................................................................................................313 Types ...............................................................................................................................315 Strings ............................................................................................................................318 Regular Expressions ....................................................................................................319 Patterns ...................................................................................................................320 Special Sequence Characters ..............................................................................323 CONTENTS xiii Q Q Q Compiling Regular Expressions .........................................................................323 Matching Strings ...................................................................................................324 Meta Characters ....................................................................................................326 Grouping .................................................................................................................327 System ............................................................................................................................328 Random Number Generation ....................................................................................330 Dates and Times ...........................................................................................................331 Creating a New Time ............................................................................................332 Time Operations ....................................................................................................332 Creating a New Date .............................................................................................333 Date Operations ....................................................................................................333 Time Zone Information ........................................................................................335 Operating System Interface .......................................................................................336 System Information ..............................................................................................336 Process Management ...........................................................................................337 In Conclusion ................................................................................................................341 CHAPTER 12 The GUI — TkInter ...............................................................................343 What Is TkInter? ...........................................................................................................343 Terms and Conditions .................................................................................................343 Event Handling ......................................................................................................344 Callbacks .................................................................................................................344 Widgets ....................................................................................................................345 Layout Managers ...................................................................................................345 Working with TkInter .................................................................................................346 Creating a Label ...........................................................................................................347 Frame Widgets and Centering ..................................................................................349 An Application with a Button ...................................................................................351 Working with Entry Fields and Grid Layouts ........................................................353 Creating a Class to Handle User Interfaces ...........................................................356 Working with List Boxes ............................................................................................358 Scrolling a List Box ................................................................................................361 CONTENTS xiv Q Q Q Menus .............................................................................................................................363 Context Menus .............................................................................................................366 Scale Widgets ................................................................................................................367 RadioButtons and CheckButton ...............................................................................370 Text Widgets .................................................................................................................373 In Conclusion ................................................................................................................375 CHAPTER 13 The Web Server—Apache ...................................................................377 Setting Up Apache .......................................................................................................377 Testing Apache .............................................................................................................378 Your First Python CGI Script: Hello Apache ...........................................................379 Examining the Hello Python Script ...................................................................380 The cgi-bin Directory ............................................................................................381 A Script for Displaying the Environment ...............................................................382 Receiving Data from an HTML File ..........................................................................384 Sending Data to an HTML File ..................................................................................387 How It All Works ...................................................................................................390 Dynamic HTML Displays Based on User Input ......................................................391 HTML Elements ............................................................................................................396 Cookies ...........................................................................................................................399 Uploading Files ............................................................................................................402 Redirection ....................................................................................................................403 Error Handling ..............................................................................................................405 In Conclusion ................................................................................................................406 CHAPTER 14 Working with Databases ...................................................................407 What Is a Database? ...................................................................................................407 Simple Database Terminology ...........................................................................408 What Is MySQL? ...........................................................................................................409 Downloading and Installing ......................................................................................409 Creating a New Database ..........................................................................................410 Creating a New User ....................................................................................................414 CONTENTS xv Q Q Q Opening an Existing Database .................................................................................415 Writing to a Database ................................................................................................417 Reading from a Database ..........................................................................................421 Updating a Database ..................................................................................................424 Deleting from a Database ..........................................................................................427 Searching a Database .................................................................................................430 In Conclusion ................................................................................................................436 CHAPTER 15 Putting It All Together .......................................................................437 Designing the Application .........................................................................................437 Program Flow .........................................................................................................437 User Interface Design ...........................................................................................438 Database Design ...................................................................................................439 Implementing the Database Tables ........................................................................440 Implementing the Forms ...........................................................................................442 Adding Reviews ............................................................................................................449 Adding the Review to the Database ........................................................................452 Listing the Reviews ......................................................................................................456 Deleting Books .............................................................................................................459 In Conclusion ................................................................................................................462 CHAPTER 16 Python and Graphics ..........................................................................463 The PIL Library ..............................................................................................................463 Downloading ..........................................................................................................464 Installing .................................................................................................................464 Verifying Your Installation ..................................................................................465 Creating a New Image ................................................................................................465 Function Parameters ............................................................................................466 Drawing on the Image ................................................................................................467 Drawing the Image ...............................................................................................468 Displaying the Image ...........................................................................................470 CONTENTS xvi Q Q Q
### Python 内置函数列表及其用途 Python 提供了一系列丰富的内置函数,这些函数可以直接调用而无需额外导入模块。以下是部分常用内置函数的介绍: #### abs() 返回数值的绝对值。 ```python print(abs(-5)) # 输出: 5 ``` #### all() 如果迭代器中的所有元素都为真,则返回 `True`;否则返回 `False`。 ```python print(all([1, 2, 3])) # 输出: True print(all([0, False, None])) # 输出: False ``` #### any() 只要有一个元素为真就返回 `True`,全部为假则返回 `False`。 ```python print(any([0, False, 'hello'])) # 输出: True print(any([])) # 输出: False ``` #### bin() 将整数转换成二进制字符串表示形式。 ```python print(bin(8)) # 输出: 0b1000 ``` #### bool() 将参数转换为布尔值,无参数时默认为 `False`。 ```python print(bool('')) # 输出: False print(bool('hello')) # 输出: True ``` #### chr() 返回给定 Unicode 编码对应的字符。 ```python print(chr(65)) # 输出: A ``` #### dict() 创建一个新的字典对象或从其他映射或可迭代项构建字典。 ```python d = dict(a=1, b=2) print(d) # 输出: {'a': 1, 'b': 2} ``` #### dir() 尝试返回由对象定义的有效属性列表。 ```python import math print(dir(math)) ``` #### enumerate() 返回枚举对象,默认索引从零开始计数。 ```python for i, v in enumerate(['apple', 'banana', 'orange']): print(f'{i}: {v}') # 输出: # 0: apple # 1: banana # 2: orange ``` #### filter() 用于过滤序列,筛选出符合条件的元素组成新的列表。 ```python def is_even(n): return n % 2 == 0 numbers = [1, 2, 3, 4, 5, 6] even_numbers = list(filter(is_even, numbers)) print(even_numbers) # 输出: [2, 4, 6] ``` #### float(), int(), str() 分别用来把数据类型转成浮点型、整形以及字符串。 ```python f = float('3.14') i = int('123') s = str(456) print(type(f), type(i), type(s)) # 输出: <class 'float'> <class 'int'> <class 'str'> ``` #### format() 格式化指定的字符串并将其写入到控制台。 ```python name = "Alice" age = 30 formatted_string = "Name: {}, Age: {}".format(name, age) print(formatted_string) # 输出: Name: Alice, Age: 30 ``` #### getattr(), hasattr(), setattr() 操作类实例的方法和属性。 ```python class Person: name = "Bob" p = Person() print(hasattr(p, 'name')) # 输出: True setattr(p, 'age', 25) print(getattr(p, 'age')) # 输出: 25 ``` #### help() 获取有关模块、关键字、函数的帮助文档。 ```python help(len) ``` #### input() 读取用户输入的一行文本作为字符串处理。 ```python user_input = input("Enter something:") print(user_input) ``` #### isinstance() 判断某个变量是否是指定的数据类型。 ```python print(isinstance(5, int)) # 输出: True print(isinstance("test", str)) # 输出: True ``` #### len() 计算容器(如字符串、元组、列表等)中元素的数量。 ```python my_list = ['red', 'green', 'blue'] length_of_my_list = len(my_list) print(length_of_my_list) # 输出: 3 ``` #### map() 应用一个函数到一系列项目上,并返回结果组成的迭代器。 ```python def square(x): return x ** 2 nums = [1, 2, 3, 4] result = list(map(square, nums)) print(result) # 输出: [1, 4, 9, 16] ``` #### max() 和 min() 找出最大最小值。 ```python max_value = max([1, 2, 3]) min_value = min([1, 2, 3]) print(max_value) # 输出: 3 print(min_value) # 输出: 1 ``` #### open() 打开文件进行读写操作。 ```python with open('example.txt', mode='w') as f: f.write('Hello world!') with open('example.txt', mode='r') as f: content = f.read() print(content) # 输出: Hello world! ``` #### pow() 求幂运算。 ```python base = 2 exponent = 3 power_result = pow(base, exponent) print(power_result) # 输出: 8 ``` #### range() 生成不可变序列,在循环语句里经常被使用来遍历数字序列。 ```python for num in range(5): print(num) # 输出: # 0 # 1 # 2 # 3 # 4 ``` #### reversed() 反转任何支持顺序访问的对象的内容。 ```python reversed_sequence = ''.join(reversed('hello')) print(reversed_sequence) # 输出: olleh ``` #### round() 四舍五入到最接近的整数或者指定位数的小数。 ```python rounded_number = round(3.14159, 2) print(rounded_number) # 输出: 3.14 ``` #### sorted() 对所有可迭代对象进行排序操作。 ```python unsorted_list = [3, 1, 4, 1, 5, 9] sorted_list = sorted(unsorted_list) print(sorted_list) # 输出: [1, 1, 3, 4, 5, 9] ``` #### sum() 求数列之和。 ```python total_sum = sum([1, 2, 3, 4]) print(total_sum) # 输出: 10 ``` #### tuple(), set(), frozenset(), list() 可以将其他类型的集合转化为相应的结构体。 ```python tup = tuple([1, 2, 3]) # 转换成元组 lis = list((1, 2, 3)) # 转换成列表 st = set([1, 2, 3, 3]) # 转换成集合 frz_st = frozenset(st) # 不可变集合 ``` #### zip() 将多个列表对应位置打包在一起形成元组的列表。 ```python names = ["John", "Mary"] ages = [27, 23] paired_data = list(zip(names, ages)) print(paired_data) # 输出: [('John', 27), ('Mary', 23)] ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值