Python Learning: 5, if statements, while statements, functions, and marketplace examples

Source: Internet
Author: User

Conditional control Statements

If statement

Simple if judgment statement, when the condition after the if is true, execute print (' yes '), otherwise execute the statement inside the Else, print (' No ')

if True:    print ('yes')else:    print ('  No')

Multiple judgments

First determine if PD is greater than 0, otherwise determine if PD is less than 0

PD = input ('Please enter a number:') PD= Int (PD)#use input to get the user input of the worthwhile type is a stringifPD >0:Print('A positive value is entered')elifPD <0:Print('negative values for the input')Else:    Print('the input is zero')
Trinocular operation

The trinocular operation is to represent the IF Else statement through a statement, in the following format

 name= value 1 if  condition else   value 2 if  "   "  set  "  value 1   assigns a value to "  name   "   "   " does not hold "   value 2   is assigned to   Name   
Name="alexsel"ifelse"Eric"Print  (name) output: Alexsel

The goal of the trinocular operation is to reduce the amount of code.

Looping statements

One, for loop

Traversing the output has multiple elements of data, such as a string, a list. Use in to get the individual elements in the later variables.

str ="Alexsel"List= [A.'Alexsel'] forIinchStr:Print(i)Print('----------------') forKinchlist:Print(k) Output result: Alexsel----------------123Alexsel

You can use break to end the loop prematurely

 for inch # use range A loop of 0 to 9 of the series.     Print(i)    if i = =5        :print('  End Loop ')        break# Output 1 to 9 output results if you do not end prematurely : 0 12345 End    

Use continue to skip a loop

 for  in range:     if i = = 5:        continue    # after using this statement , skipping the statement after continue in this loop, skipping print (i), 5 no output    print(i) output: 012346789

Second, while loop

While the general form is as follows

 while condition:    statement

Executes until the condition is true, until the condition is false.

var = 1 while Var <:    print(var    )+ = 1 output result:123456789

When the condition is always true, there is an infinite loop.

var = 1 while var = =1    :print(VAR) output result:11111 ....

While loop uses else, when the while loop is false, the statement in else is executed.

i = 0 while I < 5:    print(i)    + = 1else:     Print ('i equals 5') output result: 01234i equals 5

Function

First, create a function 1, create a function of the basic format
def function name (formal parameter):    function Body     return"123"   
Second, the return value of the function

After the function executes a return, the following code is no longer executed, and the returned value is given to the variable assigned after the function was called.

def F2 ():     ' Alexsel '    return  = F2 ()print(TEM) Output result: Alexsel
Iii. Invocation of functions

Calling a function using the function's name

def F1 ():     Print (' I was called up ') F1 ()     # here the function is called
Iv. passing in parameters to a function

The arguments in the incoming function need to correspond to one by one, in the following example, Alexsel passes the value to name,50 to age, which is the first number to pass to the first.

def obj (name,age):     return name+' 's age is '# The type of the parameter passed in is numeric, we want to do string concatenation, convert it to a string  = obj ('alexsel', ')print(str) Output: Age of Alexsel
function can have default parameters

A parameter in a function can set a default value, and when it is not worthwhile to pass the parameter, the default value is used, and the parameter with the default value should be placed after the default parameter.

defDrive (name="I'm"):#name This has a default parameter, the default parameter should be placed after no default parameters, otherwise error, no default parameters must pass parameters, there are default parameters can not pass parameterstemp=name+"Drive"        returnTempret=drive (" You") Print(ret) RET=drive ("He")Print(ret) RET=Drive ()Print(ret) output: You drive he drive I drive
Six. Dynamic parameters 1. Dynamic parameters that can receive multiple values
def A1 (*a):  #  dynamic parameter, can accept multiple values    print(A, type (a))  #  Now the type of a is a tuple, and the arguments you pass in are treated as elements of the tuple A1 (123, 3, 444, 555, [one, one, and all])  #  The incoming list here is treated as an element Output Result: (('tuple'>)
2. And dynamic parameters that convert multiple parameters to dictionaries
def A2 (**b):  #  dynamic parameter, received parameter converted to dictionary    print(b, type (b))  #  The type of B is a dictionary, and the passed parameter is converted to the dictionary A2 (K1=123, k2=345) output: ({'K2'  'K1'dict'>)
defA3 (P, *a, **AA):#here a gets the first parameter passed in, *a gets the parameter that is not the dictionary type, * * Gets the parameter that passed in the dictionary type    Print(P, type (p))Print(A, type (a))Print(AA, type (AA)) A3 (One, one, one, k1=123, k2=456)#here automatically give the 11 to p,22,33 to *a, k1=123,k2=456 to **a#* * in front of *, these two are to be followed by the general number of arguments, and the arguments will be sorted by thisoutput Result: (One by one, <type'int'>)(((<type),'tuple'>)({'K2': 456,'K1': 123}, <type'Dict'>)
3. Examples of incoming lists, dictionaries, and tuples for dynamic parameters:

The dictionary passed into the function cannot be passed directly, and needs to be added before the passed function * *

defF1 (*args):Print(args) Li= [11, 22, 33]f1 (LI)#This argument is the first element of the args tuple as a list [11,22,33]F1 (*li)#This argument is going to pass every element of this list to one by one and the result will be#each element of this list becomes each element of the args tuple (11,22,33)defF2 (* *Kwargs):Print(Kwargs) dic= {"K1": 123,"K2":"AAs"}#F2 (DIC) # This is an error in passing parametersF2 (K1=dic)#This parameter will become kwargs={"K1": {"K1": 123, "K2": "AAs"}F2 (**dic)#To pass the elements of DIC in one pass, the format is kwargs={"K1": 123, "K2": "AAs"}, which needs to be added before DiCoutput Result: ([11, 22, 33],)(11, 22, 33){'K1': {'K2':'AAs','K1': 123}}{'K2':'AAs','K1': 123}
Vii. local variables, global variables 1, local variables

A local variable is typically defined in a function, and its scope is only called in this function and cannot be called outside of the function.

def F1 ():    a=123    Print (a) # This is a local variable, only this function can be used. F1 () Print (a) # outputting this A in addition to the function will cause an error . output:123 then an error message
2. Global variables
A = 1234  #  global variable b = 1000001def  F1 ():    = 123  #  This is a local variable. Only this function can be used to    print(a)  #  Here is a local variable, in its own function first to find out whether the variable is defined in the function, If not, use global variables    print(b) F1 () output results:1231000001

If you want to call a variable defined in a function outside of a function, you can define a global variable in the function

A = 1234def  F1 ():    Global a  # defines a globally variable here and assigns a value to the global variable below    = 123    print(a)  #  output is: 123F1 ()print(a)  #  Output Result: 123 output:123123

Python also has a large number of built-in functions, we will continue to explain in the future study, today's study to this end, if there are errors in the place to welcome everyone to point out.

Python Learning: 5, if statements, while statements, functions, and marketplace examples

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.