Python calls function/type conversions/slices/iterations

Source: Internet
Author: User

Calling function/type conversions/slices/iterations

1. Calling function: ABS (), Max (), Min ()

2. Data type conversion: Int (), float (), str (), tool (), A=abs,

3. Define the function, if there is no return statement, the function will return the result after execution, but the result is None

In Python, define a function to use the DEF statement, write down the function name, parentheses, the arguments in parentheses, and the colon: and then, in the indent block, write the function body, and the return value of the function is returned with a return statement.

Let's take the example of a custom my_abs function that asks for an absolute value:

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

When defining functions in the Python interactive environment, be aware that Python will appear ... The prompt. After the function definition ends, you need to press two to return to the >>> prompt: *nums indicates that all elements of the list are nums as mutable parameters. This writing is quite useful and common.

4 slices/iterations

Python provides the slice (Slice) operator, which greatly simplifies the operation of the Intercept function (for example, substring), in fact, to slice the string. Python does not have an intercept function for a string, it can be done simply by slicing one operation. With the slicing operation, many local loops are no longer needed. Python's slices are very flexible, and one line of code can implement many lines of work to complete.

>>> ‘ABCDEFG‘[:3]
‘ABC‘
>>> ‘ABCDEFG‘[::2]
‘ACEG‘

Any iterator object can be used for a for loop, including our custom data types, and can be used for loops as long as the iteration criteria are met.

>>> for x, y in [(1, 1), (2, 4), (3, 9)]:
...     print(x, y)
...
1 1
2 4
3 9

Python calls function/type conversions/slices/iterations

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.