Full-stack Python tutorial day2 and stack Python tutorial day2

Source: Internet
Author: User

Full-stack Python tutorial day2 and stack Python tutorial day2
 I. List and tuplesThe list is one of the most common data types in the future. You can use the list to conveniently store and modify data.Definition list

names=['lv','shi','hai','ll']
Result: Access the elements in the list by subscript. The subscript starts counting from 0.
print(names[1])
Slice: Multiple Elements
names=['lv','shi','hai','ll']
Print (names [1: 3]) # Take the number between subscript 1 and subscript 3, including 1 but not 3   
Print (names [-1]) # obtain the last value
Print (names [-2:]) # obtain the last two values
Print (names [: 3]) # obtain the first three values
Step Size slice:
Names = ['1lv', '# Shi', 'hai', ['hh ', 'kk'], 'l', 'fadfa ']
Print (names [0:-]) # two values
Print (names [: 2]) # both 0 and-1 can be omitted.
 
Append: 
names=['lv','shi','hai','ll']
names.append('ls')
  Insert:
Names = ['lv', 'shi ', 'hai','ll ']
Names. insert (2, 'lil') # numbers represent subscripts and cannot be inserted in batches.
Modify:
Names = ['lv', 'shi ', 'hai','ll ']
Names [2] = 'Liu '# Change li to liu,
Print (names)
Delete:Method 1:
Names = ['lv', 'shi ', 'hai','ll ']
Names. remove ('lv ') # Delete lv
Print (names)
Method 2:
Names = ['lv', 'shi ', 'hai','ll ']
Del names [0] # Delete lv, method 2
Print (names)
Method 3:
Names = ['lv', 'shi ', 'hai','ll ']
Names. pop () # by default, no subscript is input. The last value is deleted. The input subscript is the same as the del usage.
Print (names)
  Obtain Subscript:
names=['lv','shi','hai','ll']
print(names)
print(names.index('shi'))
 
names=['lv','shi','hai','ll']
print(names)
Print (names [names. index ('shi ')]) Statistics: 
names=['lv','shi','hai','ll']
print(names)
Print (names. count ('lv ')) Reverse:
names=['lv','shi','hai','ll']
print(names)
names.reverse()
print(names)
Sort: 
names=['lv','shi','hai','ll']
print(names)
names.sort()
print(names)
Extension:
names=['lv','shi','hai','ll']
Print (names) names2 = [1, 2, 3, 4]
names.extend(names2)
print(names,names2)
Copy:Names = ['1lv', '# Shi', 'hai','ll ', 'fadfa']
names2=names.copy()
print(names)
print(names2)
Shortest copy:Names = ['1lv', '# Shi', 'hai', ['hh ', 'kk'], 'l', 'fadfa ']
Names2 = names. copy ()
Names [2] = 'hai'
Names [3] [0] = 'hh'
Print (names)
Print (names2)
Import copy
Names = ['1lv', '# Shi', 'hai', ['hh ', 'kk'], 'l', 'fadfa ']
Names2 = copy. copy (names) # shallow copy
Names [2] = 'hai'
Names [3] [0] = 'hh' # shallow copy
Print (names)
Print (names2)
Deep copy:
Import copy
Names = ['1lv', '# Shi', 'hai', ['hh ', 'kk'], 'l', 'fadfa ']
Names2 = copy. deepcopy (names) # Deep copy
Names [2] = 'hai'
Names [3] [0] = 'hh'
Print (names)
Print (names2) List loop: 
names=['1lv','#shi','Hai',['hh','kk'],'ll','fadfa']
for i in names:
print(i)
TuplesThe number of tuples is similar to that of the list. It is also called the read-only list.

Syntax

1 names = ("alex","jack","eric")

It only has two methods: count and index.

names = ('lv','shi')
print(names.count('lv'))
names = ('lv','shi')
Print (names. index ('lv ') program exercise

Program: Shopping Cart program

Requirements:

  1. After the program is started, ask the user to enter the salary and print the product list
  2. Allows users to purchase products based on product numbers
  3. After you select a product, check whether the balance is sufficient. If the balance is sufficient, you will be charged directly. If the balance is insufficient, you will be reminded.
  4. You can exit at any time. When you exit, the purchased items and balances are printed.
The source code is as follows:
Product_list = [('iphone ', 5800), ('mac Pro', 9800), ('bike', 800), ('Watch', 1000 ), ('book', 58)]
Shopping_list = []
Salary = input ("Input your salary :")
If salary. isdigit (): # determine whether the salary is a number. isdigtit determines whether the salary is a number.
Salary = int (salary)
While True:
# For item in product_list:
# Print (product_list.index (item), item) # obtain the item number by obtaining the lower mark
For index, item in enumerate (product_list): # obtain the product number enumerate to retrieve the subscript of the list by obtaining the lower mark.
Print (index, item)
User_choice = input ("Please select the item to buy :")
If user_choice.isdigit ():
User_choice = int (user_choice)
If user_choice <len (product_list) and user_choice> = 0: # len indicates determining the list Length
P_item = product_list [user_choice] # obtain the product
If p_item [1] <= salary: # can afford p_item [1] indicates the product price
Shopping_list.append (p_item) # Add to shopping cart
Salary-= p_item [1] # deduction
Print ("add % s to the shopping cart. Your balance is \ 033 [31; 1 m % s \ 033 [0 m" % (p_item, salary )) # \ 033 [31; 1 m % s \ 033 [0 m change % s color
Else:
Print ("\ 033 [41; 1 M. You have only [% s] of your remaining balance, and you still need to buy a wool! \ 033 [0 m "% salary)
Else:
Print ("\ 033 [31; 1 m item does not exist !!! \ 033 [0 m ")
Elif user_choice = 'q ':
Print ('------- shopping list -------')
For p in shopping_list:
Print (p)
Print ("your balance is \ 033 [21; 1 m % s \ 033 [0 m" % salary)
Exit ()
Else:
Print ("\ 033 [31; 1 m Error !!! \ 033 [0 m ")
Else:
Print ("\ 033 [31; 1 M Please enter the correct salary! \ 033 [0 m ")

String operation
 
Name = "my \ tname is shihai"
Print (name. capitalize () # uppercase letters
Print (name. count ("I") # statistics
Print (name. center (50, "_") # place the name in the middle and print 50 characters
Print (name. endswith ("ai") # determine the end of a string
Print (name. expandtabs (tabsize = 30) # convert it to a space and use it with \ t in name.
Print (name. find ("hai") # search for hai and return the subscript
Name = "my name is {name} and I am {year} old"
Print (name. format (name = 'lv', year = 25) # format
Print (name. format_map ({'name': 'lv', 'Year': 12}) # The dictionary is in format_map.
Print ('ab23'. isalnum () # contains a to z and all Arabic numerals
Print ('adda'. isalpha () # English letters only
Print ('200'. isdecimal () # decimal
Print ('1a '. isdigit () # integer
Print ('1 Chinese'. isidentifier () # determine if it is a legal identifier (variable name)
Print ('33. 3'. isnumeric () # determine if it is a number
Print ('33a'. isspace () # Is it a space?
Print ('33a'. istitle () # Is it the title?
Print ('33a'. isprintable () # Is it true that the drive file of the tty file cannot be printed?
Print ('33a'. isupper () # whether it is capitalized
Print (','. join (['1', '2', '3', '4'])
Print (name. ljust (50, '*') # The length is 50. If not, use * to complete
Print (name. Must ust (50, '_') # Same as above
Print ('aaadfs'. lower () # Small write in upper case
Print ('aaadfs'. upper () # uppercase for lowercase letters
Print ('\ nAaadfs'. lstrip () # Remove spaces from the left or press ENTER
Print ('aaadfs \ n'. rstrip () # Remove spaces from the right side or press ENTER
Print ('aaadf \ n'. strip () # Remove the space or press ENTER
P = str. maketrans ("abcdefli", '2017 # $ 56') # match the front string with the back string to generate a random password.
Print ("alex li". translate (p) # The result is 15 # x 56
Print ('lvshh'. replace ('h', 'h', 1) # replace. If there are more than one, add the corresponding number to the back.
Print ('lv shi hai '. rfind (' I ') # Find the subscript of the rightmost character from left to right
Print ('1 + 2 + 3 + 4'. split ('+') # split the string into a list by the characters in parentheses
Print ('1 + 2 \ n + 3 + 4'. splitlines () # split the string into a list by line feed.
Print ('lv shi Hai '. swapcase () # convert uppercase to lowercase and lowercase to uppercase.
Print ('lv shi Hai '. title () # uppercase letters
Print ('lv shi Hai '. zfill (50) # specify the width and fill it with 0 if it is not enough.
Dictionary usageA dictionary is a key-value data type. It is used to query the details of a corresponding page through strokes and letters. Syntax:
info = {
'stu1101': "ll",
'stu1102': "xiaoming",
'stu1103': "wangli",
}
print(info)
Dictionary features:Dict is unordered, And the dictionary does not need to be down-marked; The key must be unique, so is inherently de-duplicated;
Instance:
Info = {
'Stu1101': "ll ",
'Stu1102': "xiaoming ",
'Stu1103': "wangli ",
}
B = {
'Stu1101': "lv ",
1: 3,
2: 5
}
Info. update (B) # merge two dictionaries. If there is a cross key in the middle, merge and overwrite them. If there is no cross, create them.
Print (info)
C = dict. fromkeys ([6, 7, 8], [1, {"name": "lv"}, 444]) # initialize a new dictionary
Print (c)
C [7] [1] ['name'] = "li"
Print (c)

Print (info. items () # convert a dictionary to a list
Print (info ["stu1101"])
Info ["stu1101"] = "Lili" # modify data
Info ["stu1104"] = "Lili" # add data
# Del Delete
Del info ["stu1104"]
# Info. pop standard Deletion
Info. pop ("stu1104 ")
Info. popitem () # Delete randomly
Print (info. get ("stu1104") # search. If there is any output, none is printed.
Print (info. get ("stu1103 "))
Print ("stu1101" in info) # info. has_key ("1103") usage in python2

# Multi-level dictionary nesting and operations
Av_catalog = {
"Europe and America ":{
"Www.youporn.com": ["a lot of free, the world's largest", "general quality"],
"Www.pornhub.com": ["a lot of free, great", "higher than yourporn"],
"Letmedothistoyou.com": ["a lot of selfies, many high-quality images", "a lot of resources, slow updates"],
"X-art.com": ["high quality, really high", "all charges, Please bypass"]
},
"Japan and South Korea ":{
"Tokyo-hot": ["The quality is unclear. I don't like Japan and South Korea anymore.", "I heard it's a charge."]
},
"Mainland China ":{
"1024": ["all free, good, good person, safe life", "server abroad, slow"]
}
}
Av_catalog [""] ["1024"] [1] + = ", which can be crawled by crawlers"
Av_catalog.setdefault ("", {"www.baidu.com": [1, 2]}) # first, set the value in the dictionary. If the value can be obtained, the system returns the result. If the value cannot be obtained, a new one is created.

Print (av_catalog)
# Ouput
['All free, good, good person's life safe ', 'servers are abroad, slow, crawlers can be crawled.']


# Dictionary Loop
Info = {
'Stu1101': "ll ",
'Stu1102': "xiaoming ",
'Stu1103': "wangli ",
}
For I in info: # The most basic loop, which is more efficient than the following Loop Method
Print (I, info [I])

For k, v in info. items ():
Print (k, v)
 
Level 3 menu:
 
 
 
  
  

<Wiz_tmp_tag id = "wiz-table-range-border" contenteditable = "false" style = "display: none;">



From Weizhi note (Wiz)



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.