Python3 basic knowledge, python3 basic knowledge

Source: Internet
Author: User

Python3 basic knowledge, python3 basic knowledge
I. Data Types1. Number

  • Int (integer)
  • Long (long integer)
  • Float (float type)
  • Complex (plural)
2. Boolean Value
  • True or False
3. String Ii. VariablesVariable naming rules:
  • Variable names can only be any combination of letters, numbers, or underscores
  • The first character of the variable name cannot be a number.
  • Variable names cannot be keywords (for example, and, or, continue, break, in, else, print, etc)
  III,String concatenation1. Use the plus sign (+)
Name = "Tom" age = 25 print (name + "s age is" + str (age) # output: Toms age is 25

2. String formatting

Name = "Tom" age = 25 print ("% s's age is % d" % (name, age) # output: Toms age is 25

Ps: in python, The + number is used to connect to the string. Every time a + number appears, you need to apply for a space in the memory again. How many + numbers are there, how much space will be applied. Generally, you do not need to create a connection string using the "+" sign.

 

Iv. List and metadata

1. list)

  • Create list
Str_list = ['Tom ', 'Lucy', 'Mary '] Or str_list = list (['Tom', 'Lucy ', 'Mary'])
  • Index (a value in the access list)
str_list[0]
  • Append (add elements to the end)
Str_list.append ('lilei') print (str_list) # output: ['Tom ', 'Lucy', 'Mary ', 'lilei']
  • Insert (add an element at a specified position)
Str_list.insert (1, 'lilei') print (str_list) # output: ['Tom ', 'lilei', 'Lucy', 'Mary ']
  • Delete (delete a specified element)
Str_list.remove ('Lucy ') print (str_list) # output: ['Tom', 'Mary ']
  • Slice
Str_list = [3, 4, 5, 6, 7, 8, 9] new_1 = str_list [] # obtain the index 3new_2 = str_list [] # Start from index 0, take one of every two digits, Until 6th bits new_3 = str_list [-2:] # Take the next two numbers new_4 = str_list [: 3] # Take the first three numbers new_5 = str_list [:: 3] # print (new_1, new_2, new_3, new_4, new_5) for each of the three numbers # output: [4, 5] [3, 5, 7] [8, 9] [3, 4, 5] [3, 6, 9]

2. tuple)

  • Create tuples
Age = (18,25, 33) or age = tuple (18,25, 33 ))

Except that elements cannot be modified, added, or deleted, other operation tuples are almost the same as those in the list.

 

V. Dictionary

Key-value Storage

  • Create a dictionary
Phone = {'zhang san': '123', 'Li si': '123', 'wang wu': '123 ',}
  • Obtain the value of the key in the dictionary.
Print (phone ['zhang san']) # If the key does not exist, an error is reported. The key is enclosed in brackets (phone. get ('old yellow ') # If the key does not exist, None is returned, and the key is enclosed in parentheses # output: 13075632152 # None
  • Assignment
Phone ['old yellow '] = '000000' # New phone ['zhang san'] = '000000' # modify print (phone) # output: {'wang wu': '123 ', 'Old yellow ': '123', 'zhang san': '123', 'Li si': '123 '}
# Because the dictionary isUnorderedSo the order of each output may be different.
  • Delete
Phone. pop ('zhang san') # method 1 del phone ['Li si'] # method 2 phone. popitem () # delete a random
  • Traversal
For key in phone: print (key, phone [key]) # output: # Wang Wu 13420321523 # Zhang San 13075632152 # Li si5 15732015632
  • Multilevel nesting
Phone = {'hr Department ': {'zhang': '123', 'lil': '123'}, 'Finance Department ': {'lily': '123 ', 'xiao ying': '000000'}, 'technical Department ': {'Ron': '000000'} print (phone ['personnel author'] ['lily']) # output: 13432023152

 

Vi. if statement

1. if... else

Age = 16if age <18: print ('Are you not a minor? ') else: print ('you are an adult ')

2. if... elif... else

Score = 85if score> 0 and score <60: print ('your score is failed') elif score> = 60 and score <80: print ('your scores passed ') elif score> = 80 and score <90: print ('your scores are excellent') else: print ('your scores are excellent ')

 

7. while Loop

I = 0num = 0 while I <= 100: num + = I + = 1 print ('1-100 cumulative equals % d' % num)

 

8. for... in Loop

Num = [] for I in range (10): num. append (I) print (num) # output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

 

9. User Interaction)

Name = input ('enter YOUR name: ') height = input ('enter your height :') print ('% s height % s cm' % (name, height ))

 

10. Basic File Operations

Open the file: f = open ('file path', 'Mode') or with open ('file path', 'Mode') as f:

Mode:

  • R: open a file in read-only mode
  • W: open a file for writing only. If the file already exists, overwrite it. If the file does not exist, create a new file.
  • A: open a file for append. If the file already exists, the file pointer is placed at the end of the file. That is to say, the new content will be written to the existing content. If the file does not exist, create a new file for writing.
  • W +: open a file for reading and writing. (The file is cleared as soon as it is opened. Can you read it ?)
  • A +: open a file for reading and writing.

Read files:

Read () readlines () readline () Usage

F = open ('d:/test.txt ', 'R') # open the file print (f. read () # read () read all the content of the file at a time for line in f. readlines (): # readlines () read the entire file and store it in the print (line. strip ('\ n') # Remove' \ n' at the end of the row while 1: line = f. readline () # readline () reads only one row of print (line. strip ('\ n') if not line: breakf. close () # close a file

Write File:

f =open('d:/test.txt','a')f.write('hello,boy!\n')  f.close()

 

 

 

 

 

 

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.