1, Basic use
Input and output
- Use print()
- Use input()
notes:
-
Single line comment, starting with #
-
Multiline comment, using three pairs of single quotes or three pairs of double quotes
Coding specification:
- Don't put a semicolon at the end of the line
- Case sensitive
- It is suitable to add spaces and empty lines to make the code layout more elegant, beautiful and reasonable
- Use indentation to represent code blocks
2, Variables and data types
Variable:
- When defining a variable, you do not need to specify the type of the variable. You can assign a value to the variable directly
- Variable names should conform to naming conventions
Data types: integer, floating point, string, Boolean, null, etc
#!/usr/bin/env python3 # * coding: utf8 * __author__ = 'early summer' '''Data types: integer, floating point, string, Boolean, null, etc ''' # Integer int a = 3454566666666666666 print(a) print(type(a)) # Floating point float b = 12.5 print(b, type(b)) # String str, which defines the string. Single quotation marks or double quotation marks can be used (single quotation marks are recommended) c = 'ccc' d = "ddd" print(c, type(c)) print('Zhang San said:"Do you have chicken tonight?"') # When a string has multiple lines, three pairs of single quotation marks can be used to represent multiple lines e = ''' welcome to chuxia0811 ''' print(e) print(type(e)) # Boolean bool, values: True, False f = True print(f, type(f)) g = 5 < 3 print(g) print(5 + False) # True means 1 and False means 0 # Null NoneType h = None print(h, type(h))
3, String
Type conversion
# Convert string to numeric value a = '25' b = int(a) print(type(a), type(b)) c = '12.5' d = float(c) print(type(c), type(d)) # Converts a numeric value to a string print('hello ' + str(25)) # Numeric types cannot be directly spliced with characters, and type conversion is required
String common methods
string = ' hello world ' print(string.islower()) print(string.isupper()) print(string.capitalize()) print(string.index('llo')) print(string) print(string.strip()) # Similar to trim in java print(len(string)) # Call the len() function to get the length
Slice (very important)
name = 'tom cruise' print(name[0]) print(name[4], name[len(name) - 1], name[-1]) print(name[1:5]) # Get characters with index [1,5] print(name[:5]) # Represents a de novo acquisition print(name[2:]) # Indicates getting to the end print(name[1:8:2]) # For characters with index [1,8), take one from every two print(name[::2]) # All characters, one for every two
format
# Format the string and specify a placeholder in the string # Method 1: use% operator,% s represents any character,% d represents integer and% f represents floating point number name = 'tomaaaa' age = 20 height = 180.5 print('Hello, my name is' + name + ',Age:' + str(age) + ',Height:' + str(height)) print('Hello, my name is%2.4s,Age:%d,Height:%.2f' % (name, age, height))# 2.4s indicates that the string length is 2 4 digits,. 2f means two decimal places are reserved print('Current time:%d year%02d month%d day' % (2018, 5, 14))# The specified month is two digits. If it is less than two digits, make up 0 # Method 2: use the format() method and use {} to represent the placeholder print('Hello, my name is{0},Age:{1},Height:{2:.2f}'.format(name, age, height)) print('Hello, my name is{name},Age:{age},Height:{height}'.format(age=age, name=name, height=height)) # Method 3: add an f before the string and use {variable name} to embed the variable print(f'Hello, my name is{name},Age:{age},Height:{height}')
4, Operator
Arithmetic operator, comparison operator, assignment operator, logical operator, bit operator, condition operator, member operator, identity operator
#!/usr/bin/env python3 # * coding: utf8 * __author__ = 'early summer' ''' Python Operators supported in: 1.Arithmetic operator + * / % // **Auto increment + + and auto decrement are not supported 2.Comparison operator > < >= <= == !=or<> 3.Assignment Operators = += = *= /+ %= **= 4.Logical operator and or not 5.Conditional operator, also known as ternary operator Syntax: the result when the condition is true if condition else Result when condition is false 6.Bitwise Operators And& or| wrong~ XOR^ Shift left<< Shift right>> 7.member operator innot in 8.Identity operator isis not ''' # 1. Arithmetic operator print(3 + 5) print(3 * 5) print(30 * '')# Multiplication can be used for strings print(5 % 3) print(5 // 3) # division, rounding print(2 ** 3) # power print(pow(2, 3)) i = 5 i = i + 1 print(i) # 2. Comparison operator j = 5 print(j > 2) print(10 > j > 1) # This notation is not supported print('abc' > 'acd') # Can be used for string comparison, comparing the Unicode encoding of strings # 3. Assignment operator a = 10 a += 5 # Equivalent to a= a+5 print(a) # 4. Logical operators print(True and False) print(5 > 2 or 4 < 1) print(not 5 > 2) x = 0 # 0 means False, non-0 means True y = 8 print(x and y) # Returns y if x is True; otherwise, returns X print(x or y) # Returns x if x is True; otherwise, returns y print(not x) # Returns False if x is True, otherwise returns True #5. Conditional operator, also known as ternary operator print('aaa' if 5 < 2 else 'bbb') # 6. Bitwise operator a = 5 # 00000101 b = 8 # 00001000 print(a & b) # If both digits are 1, it will be 1, otherwise it will be 0 print(a | b) # As long as one bit is 1, it is 1, otherwise it is 0 print(~a) # 0 if 1, 1 if 0 print(a ^ b) # If the two digits are the same, it is 0 and the difference is 1 print(b >> 2) # All bits of binary are shifted 2 bits to the right # 7. Member operator c = [3, 5, 12, 15, 7, 2] d = 5 print(d not in c) # 8. Identity operator m = [1, 3, 5, 7] n = [1, 3, 5, 7] x = n print(m is n) print(x is n) ''' is and == Differences between is Judge whether two variables refer to the same object == Judge whether the values of two variables are equal ''' print(m == n)
5, Lists and tuples
A list is an ordered collection that stores multiple values and can add or remove elements from the list
Tuple is similar to list in that it is also used to store multiple values, but the elements in tuple can only be initialized at the time of definition and cannot be modified after initialization
Summary: both list and tuple are built-in collections in Python, one variable and the other immutable
# List list # Define list, using [] names = ['tom', 'jack', 'alice', 'mike'] print(names) print(type(names)) # Get / set element print(names[1], names[:3]) names[0] = 'lucy' print(names) # Append element names.append('zhangsan') # Inserts an element at the specified location names.insert(1, 'lisi') # Delete element names.remove('jack') # Pop up element print(names.pop(0)) # Get the number of elements print(len(names)) # Different types of data can be stored names.append(25) # Not recommended names.append(True) print(names) # Tuple tuple # Define tuples, using () nums = (3, 8, 13, 25, 38, 250) print(nums) print(type(nums)) int(nums[2], nums[-1]) print(nums[1:3]) # Destructuring assignment # a = nums[0] # b = nums[1] # c = nums[2] # d = nums[3] # e = nums[4] # f = nums[5] a, b, c, d, e, f = nums print(a, b, c, d, e, f)
6, Conditional judgment
Judge according to the conditions to perform different operations
Use the if... elif... else statement
7, Circulation
Repetitive execution of an operation is called a loop
Two cycles:
while Loop
for... in loop
# for...in loop ames = ['tom', 'jack', 'alice', 'mike'] for name in names: print(name, end=',') print() # Use the range() function to generate a sequence for i in range(1, 100, 2): # Generate an integer sequence of [1100] in steps of 2 print(i, end=',') print() # Calculate the sum of 1 to 100 sum = 0 for i in range(1, 101): sum += i print(sum) break and continue keyword
8, Dictionaries and collections
The full name of dict is dictionary. Use the key value (key) value) stores data, commonly referred to as map in other languages
set is unordered and cannot be repeated
# Dictionaries # Define dict with curly braces {}, which is very similar to json in js scores = {'tom': 98, 'jack': 100, 'alice': 60} print(scores) print(type(scores)) # obtain print(scores['jack']) print(scores.get('alice')) # Add / set scores['lucy'] = 89 scores['tom'] = 100 # Pop up (delete) print(scores.pop('tom')) # Determine whether the specified key exists print('alice' in scores) print(scores) # ergodic print(scores.keys()) print(scores.values()) print(scores.items()) for k in scores.keys(): print(k, scores[k]) print('' * 80) for v in scores.values(): print(v) print('' * 80) for k, v in scores.items(): print(k, v) print('' * 80) # Set set # Define set with curly braces {} # s = {3, 12, 5, 7, 34, 12, 3} nums = [4, 23, 1, 23, 4, 23] s = set(nums) # Call the set() function to convert the list to set and remove duplicate values print(s) print(type(s)) # add to s.add(666) s.add(1) # delete s.remove(1) print(s) # ergodic for i in s: print(i)