Python functions & Conditions, looping

Source: Internet
Author: User
Tags abs function definition

Conditions
If < condition judgment 1>:
< Executive 1>
Elif < condition judgment 2>:
< Executive 2>
Elif < condition judgment 3>:
< Executive 3>
Else
< Executive 4>
Note else after adding a colon:

The data type returned by input () is STR

Cycle
There are two types of Python loops, one of which is the for...in loop, which sequentially iterates through each element in the list or tuple.
For x in ... A loop is a statement that puts each element into the variable x and then executes the indented block.

Python provides a range () function that generates a sequence of integers that can be converted to a list by using the list () function. For example, the series generated by range (5) is an integer starting from 0 that is less than 5:

>>> List (range (5))
[0, 1, 2, 3, 4]
Range (101) to generate an integer sequence of 0-100

The second loop is the while loop

Dict
Python has a built-in dictionary: dict
>>> d = {' Michael ': Up, ' Bob ': +, ' Tracy ': 85}
>>> d[' Michael ']
95
The data is put into the Dict method, in addition to the initialization of the specified, can also be placed through key:

>>> d[' Adam '] = 67
>>> d[' Adam ']
67
Use in to determine if key exists:

>>> ' Thomas ' in D
False
Delete a key, using the Pop (key) method, the corresponding value will also be removed from the Dict

Set
In set, there is no duplicate key
To create a set, you need to provide a list as an input collection:

>>> s = Set ([1, 2, 3])
>>> s
{1, 2, 3}

Repeating elements are automatically filtered in set:

>>> s = set ([1, 1, 2, 2, 3, 3])
>>> s
{1, 2, 3}
add (key) method can add elements to set, can be added repeatedly, but will not have effect
remove (key) method can delete element
Set can be thought of as a set of unordered and non-repeating elements in mathematical sense, so two sets can do the intersection and set of mathematical meanings, and so on:

>>> S1 = set ([1, 2, 3])
>>> s2 = Set ([2, 3, 4])
>>> S1 & S2
Span style= "FONT-SIZE:18PT; Font-family: Imitation ">{2, 3}
>>> S1 | S2
{1, 2, 3, 4}

function
You can assign a function name to a variable
> >> a = ABS # variable a points to the ABS function
>> > A (-1) # So you can also call the ABS function by a
1

in Python, define a function to use the DEF statement, write down the function name, parentheses, the arguments in parentheses, and the colon: The function body is written in the indent block, and the return value of the function is returned with a return statement.
def my_abs (x):
if x >= 0:
return x
else:
return-x
If there is no return statement, the result is returned when the function is executed. Only the result is none. Return none can be shortened to return.
when defining functions in a python interactive environment, be aware that Python will appear ... The prompt. After the function definition ends, press two to return to the >>> prompt.
pass can be used as placeholders, such as the code that is not yet ready to write functions, You can put a pass on it so that the code can run.

default parameters
set the default value of the second parameter N to 2:
def Power (x, n=2):
s = 1
while n > 0:
n = n-1
S = S * x "/ strong>
return s
when power (5) is called, it is equivalent to calling power (5, 2):

>>> Power (5)
25
The required parameter is before the default parameter is

When you do not provide partial default parameters in order, you need to write the parameter names. For example, call Enroll (' Adam ', ' M ', city= ' Tianjin '), meaning that the city parameter is passed in the value

Variable parameters
def calc (numbers):
sum = 0
For N in numbers:
sum = SUM + N * n
return sum
When called, a list or tuple needs to be assembled first:

>>> Calc ([1, 2, 3])
-
Simplified:
def Calc (*numbers):
sum = 0
For N in numbers:
sum = sum + N * N
return sum
>>> Calc (1, 2, 3)
-
>>> nums = [1, 2, 3]
>>> Calc (*nums)
-

Keyword parameters
def person (name, age, **kw):
>>> extra = {' City ': ' Beijing ', ' job ': ' Engineer '}
>>> person (' Jack ', **extra)
**extra means that all key-value of extra this dict are passed into the **kw parameter of the function with the keyword parameter, and kw will get a dict

Only city and job are accepted as keyword parameters. The functions defined in this way are as follows:

def person (name, age, *, City, Job):
The named keyword parameter requires a special delimiter *,* after the argument is treated as a named keyword parameter

When using named keyword parameters, it is important to note that if there are no mutable parameters, you must add a * as a special delimiter. If the missing *,python interpreter will not recognize the positional parameter and the named keyword argument

If there is already a mutable parameter in the function definition, then the named keyword argument will no longer need a special delimiter *:
def person (name, age, *args, City, Job):

The order of the parameter definitions must be: required, default, variable, named keyword, and keyword parameters.
*args is a variable parameter, and args receives a tuple;

**KW is the keyword parameter, and kw receives a dict.

Python functions & conditions, looping

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.