The path to learning in Python day2

Source: Internet
Author: User
Tags arithmetic

The path to learning in Python day2

One: formatted output of the string

Name = "abc" Name2 = 123name3 = 22name4 = "abc\n\t123" ABC = "   name:%s  name2:%d  name3:%f  name4:%r< c6/>name5:%s '% (name,name2,name3,name4,name4) Print (abc)

The result is:

      

As the above example, summarize the following bits

%s: Input string

%d: can only output the number, otherwise it will error

%f: Show floating-point numbers

%r: output by original format

Two: arithmetic

A = #0 0 1 1 1 1 0 0
b = #0 0 0 0 1 1 0 1

1: with arithmetic, The binary value of two digits must be all 1, then the result is 1

A & b = 0 0 0 0 1 1 0 0 = 12

2: or arithmetic, a binary value of two digits, as long as one is 1, the result is 1

a/b = 0 0 1 1 1 1 0 1 = 49

3: xor, two digit binary value, the upper and lower contrast is different is 1

# a ^ b = 0 0 1 1 0 0 0 1 = 49

Three: for Loop

The main purpose of the loop is to reduce duplication of code

As example one: Loop code 4 times

1 ' abc123 ' 2  3  for  in range (4):  4      print(" loop:", I)        

Results:

        

Example Two: Loop 10 times, show only after 6 times

1  for  in range:2     if i<5:3         continue # without going down, go straight to the next loop. 4     Print ("loop:", I)

Results:

      

Four: while loop

1: the cycle of death, will always cycle

1 count = 023 while True:4     print(" Here we go . " , Count) 5     Count +=1

2:while Limit number of cycles, guess Age:

Age = 18count = 0while Count < 3:    input_age = int (input ("enter your Age:"))    if  input_age = = age:        print ("guess Right ! ")        Break    elif Input_age < age:        print ("guess Small")    else:        print ("guess Big!")    Count + = 1  # Each loop counter +1else:    print ("wrong 3 times, Exit.")

  

5:3-dollar operation

is to display the criteria for multiple lines of printing as one line:

Example One:

A = 1b = 2if a > b:    c = a+belse:    c = a-d  

can be reduced to one line as follows

c = a+b if a>b else a-b

The Format is:

    result  = 1 if 条件  else 2

If the condition is true: result = value 1
If the condition is false: result = value 2

Six: string Other usages

print (name.capitalize ()), First Capital print (name.casefold ()), full variable lowercase print ( Name.center (10, '-')), make up 10 characters not enough according to "-" to indicate, if not write the default is separated by a space, the string is Centered. Print (name.encodswith ()), prints true or false print (name.expandtabs)), enlarges the String's space print (name.find ("lib")), searches for values, finds early reply values, cannot find a reply -1print (name.format ()), similar to%s (according to photo) print (name.isdigit ()), to determine whether it is a number ============================print ("ad". isalpha ()) , which contains only letters, replies to True print ("a2d". Isalnum ()), which contains only a combination of letters and arrays, and replies to true print ("2". isdecimal), where a decimal number returns Trueage = "" "print (age.isdecimal ( ) Print ("2". isdigit ()), containing only the integer positive print ("al_ex". isdentifier ()) # is not a valid variable name print ("al_ex". isupper ()) print ("2". islower () Print ("2". isumeric ()) print (float ("3.1"), Judging whether it is a floating-point number, not the error print ("3.1". Isspase ()), Determines whether it is a space print (",". join ("alex")), Results: a,l,e,x//* decided to split print ("alex". Ljust (50, '-')), starting from the left to display strings, insufficient "-", print ("alex". Rjust (50, '-')), starting from the right to display strings, insufficient "-" , =================== print ("alex". translate (trantab)), print ("alex". partition ("1")), print ("alex". replace ("ex", " 123 ")), result: al123//* replacement character 

  

Seven: tuples

Tuples are actually similar to the list, but also to save a group of numbers, it is not once created, it can not be modified, so it is called a read-only list

Syntax: names  =("alex","jack","eric")

Eight: Dictionary

1: the role of the dictionary, why should have a dictionary: because the list query value, need to know the index value, or to know all the values in the sub-list, query is very inconvenient, so the value and query is very inconvenient, so there is a dictionary to compensate for the lack of the list

2: Dictionary syntax, and Features:

Variable = {key,value} # Dictionary

Variable = [value 1, value 2, value 3] # list

Variable = (value 1, value 2, value 3) # tuple

1: in the dictionary key, the key value must be unique, otherwise in the query value, there will be an error,

2: the key value in the dictionary is unordered, the value corresponding to the key is constant, unless it is artificially modified

3: Dictionary Additions and Deletions:

names = {    "stu1101": {"name": "Alex", "age": "$", "hobbie": "girl"},    "stu1102": "Jack",    "stu1103": "rain"}

  

1): Check

Print (names["stu1101" ["hobbie"])

Print (names.get ("stu1104", "abc123")) #查询stu1104值是否存在, exists to return the value that he looks for, does not exist to return abc123 is self-defined, and does not define to return None.

(1): query all key values in the dictionary

Print (names.keys ())

(2): query all value values in the dictionary

Print (names. values ())

2): Increase

names["stu1104"] = ["zsy", "ABC123"]

3): Change

names["stu1104"]= ' New_value_1 ' #如果要替换值, after replacement, he will replace the key corresponding value of the value of all, can not modify key corresponding to one of the values in the value

4): Delete

(1): Print (names.pop ("stu1101", "abc123"))

# Delete the value of stu1101, if the value exists to return his deleted value value, does not exist on the return abc123,abc123 is self-defined, if not defined, the value to be deleted does not exist, will be an error, so you must add the value of Echo

(2): # del names["stu1103"]

4: Other operations of the dictionary

1): Fromkeys (variable, Value) # change list to Dictionary

Comments

1:dict is a data type, only dict can be used to invoke Fromkeys ()

2: the value for Jack and Eric corresponds to a memory id, so you can tell that the value is one of the values that they point to, so if one is modified, the other will change, 8-4-1. therefore, If you do not want this to happen, you can modify the value values by 8-4-2:

Figure 8-4-1

Figure 8-4-2

2): Items (): Print the dictionary as a list

Use is generally used to cycle the printing of dictionary information: but the efficiency is not high

3): SetDefault (n,m): Find n, if n exists, returns the value of n, figure 8-4-3

If n does not exist, add n,m. (n is key,m as Value) figure 8-4-4

Figure 8-4-3

Figure 8-4-4

4): Update (): Merge two lists, If two lists have the same value, use the newly added value

5): copy (): copies a dictionary: takes up a separate memory space:

(1): Light Copy

* note:1: Copy is a separate memory address, so the two outermost dictionary memory ID is different

2 : The second level of the dictionary ID is the same meaning because, stu1101 corresponding value is not directly in the entire dictionary, he is stu1101 point to a memory id, two dictionary two-level dictionary, and point to an id, so it appears above the situation

Example 1: you can use the copy of this commonality, to achieve the two accounts at the same time the use of a library, as if the bank card of the Child Mother bank card

(2): deep copy, full copy Lianzi dictionary redefined

Example Two:

      

Python Learning Path day2

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.