Day One: Getting to Know Python Scripts
The file that contains a Python program is called a Python script or program. The file extension for a Python script must be .py.
Notes on Using PyCharm
You need to clearly know which Python environment you have selected in PyCharm.
Comments
A comment is a piece of explanatory text that is not executed. In a Python script, if the first character is #, then it is a comment.
print() Output Function
print can output some content in the program, such as strings and numbers. The function is designed to fulfill certain functionalities; for example, print is used to output data.
Variables
# What is a variable?
# A variable is an English string used to record or label some data, and this labeled data can change.
# Understanding num = 10
# This means assigning the value 10 to the variable num for later use; afterward, you can use num to replace the data of 10.
Naming Conventions
Variable naming should follow certain conventions.
-
Variable names can use letters, numbers, and underscores (_).
-
They cannot start with a number.
-
Case sensitivity must be strictly followed.
-
Do not use Chinese characters.
-
Do not use keywords like if, else, True, False, print.
Additionally, the naming conventions for variables apply to script names, function names, and other command conventions.
Ways to Define Variables
When defining variables, it is important to adhere to naming conventions.
# First method of defining variables
a = 10
b = 20
# Second method of defining variables
a, b = 30, 40
Thought: How to Swap the Values of the Following Two Variables
# Define two variables
a = 10
b = 20
# Swap the values of the two variables
# 。。。
'''
Using a normal method to swap variable data:
1. Assign the value of variable a to c; now c contains 10.
2. Assign the value of variable b to a; now a contains 20.
3. Assign the value of variable c to b; now b contains 10.
'''
# c = a
# a = b
# b = c
# Using Python's syntax to swap variable data
a, b = b, a
Data Types in Python
What is a Data Type?
A data type is the representation of data.
For example, ‘Hello’ is a string, and 200 is a number.
In programming, apart from common characters and numbers, there are many other forms of data representation.
The type() Function Returns the Current Data Type
s = 'iloveyou'
res = type(s)
print(res) # <class 'str'> str == string
1. String Type
-
Both single and double quotes can define a string.
-
Triple quotes can also define a string.
-
Strings defined with single or double quotes cannot be arbitrarily broken across lines; line breaks must be indicated.
-
Quotes within strings can nest, but cannot nest themselves (e.g., you cannot nest single quotes in single quotes unless escaped).
-
Escape characters can be used in strings, such as \r, \n, \t, …
-
If you do not want to implement escape characters in a string, you can define it as
love = r'\nihao \shijie'
.
# Defining a string using single or double quotes
love = 'iloveyou'
hello = "你好 世界"
# You can also define a large string using triple quotes, generally for large text strings, and they can span multiple lines.
s = '''
For example, this is a
very long article content...
'''
2. Number Types
-
int: Integer
-
float: Floating-point type
-
complex: Complex number
-
bool: Boolean type (True, False)
# Number Types
'''
int: Integer
float: Floating-point type
complex: Complex number
bool: Boolean type (True, False)
'''
varn = 521
varn = -1111
varn = 3.1415926
varn = 0x10 # Hexadecimal
varn = b'001100111' # Bytes
# Complex number
varn = 5 + 6j # complex
# Boolean type
varn = True
varn = False
# print(varn,type(varn))
# Numeric types can participate in calculations
a = 10
b = 20
print(a + b)
3. List Type
-
A list is used to represent a series of data, for example, to record a group of numbers or other data.
-
The data stored in a list can be of any type.
-
When recording multiple data points, you can define them using square brackets [].
-
Each piece of data is separated by a comma.
-
For example, the following data defines several groups of numbers.
-
Each piece of data stored in a list is called an element.
-
The data in a list can be accessed by index.
-
Can the values of elements in a list store another list? This is called a secondary list (two-dimensional list) or multi-level list (multi-dimensional list).
''' About the index in a list 0 1 2 3 4 ['a','b',521,'pai',3.1415926] -5 -4 -3 -2 -1 '''
4. Tuple Type Definition
-
When defining multiple data contents, you can choose to use the List type.
-
You can also use the tuple type to define it.
-
Tuples and lists are very similar and are used to store multiple data.
-
Tuples are defined using parentheses (), while lists are defined using square brackets [].
-
The main feature of tuples is that their values cannot be changed.
vart = (1, 2, 3, 'a', 'b') # Other ways to define tuples vart = 1, 2, 3
Note: When defining a tuple with only one element, a comma is required; otherwise, it will not be a tuple.
5. Dictionary Type
-
A dictionary is also used to store one or more sets of data, defined using curly braces {}.
-
A dictionary stores data in key-value pairs, such as name: admin.
-
Keys and values are separated by a colon, and multiple key-value pairs are separated by commas.
-
Keys must be strings or numbers, and values can be of any type.
-
Key names cannot be repeated, but values can be repeated.
# For example, to record the related data of a book: title, author, price, etc.
vard = {'title':'<<鬼谷子>>','author':'鬼谷子','price':'29.99'}
# print(vard,type(vard))
# {'title': '<<鬼谷子>>', 'author': '鬼谷子', 'price': '29.99'} <class 'dict'>
Accessing Values in a Dictionary
print(vard[‘title’])
Keys in a Dictionary Cannot Be Used Repeatedly; Otherwise, They Will Be Overwritten
vard = {‘a’:10,’b’:10,’c’:20,’a’:’aa’,1:’abcdef’,’2′:’2222′}
print(vard)
##### Tip: In versions of Python before this, dictionaries were unordered.
---
### 6. Set Type
+ A set is an unordered collection of unique elements.
+ Sets can be defined using square brackets or the set() method.
+ To define an empty set, you can only use the set() method; using curly braces will define an empty dictionary.
+ Sets are mainly used for operations: intersection, difference, union, symmetric difference.
```python
a = {1, 2, 3, 'a'}
# Adding elements to the set
# a.add('b')
# Individual elements in a set cannot be accessed, but can be added or removed.
# a.discard('a')
# print(a)
# Check if the current element is in the set
# print(1 in a)
# Sets are mainly used for operations: intersection, difference, union, symmetric difference.
a = {1, 2, 3, 'a', 'b'}
b = {1, 'a', 22, 33}
print(a & b) # Intersection {1, 'a'}
print(a - b) # Difference {'b', 2, 3} Elements in set a that are not in set b.
print(a | b) # Union {1, 2, 3, 33, 'a', 'b', 22} Combining two sets and removing duplicates.
print(a ^ b) # Symmetric Difference {33, 2, 3, 'b', 22}
Summary of Data Types
'''
String: string
Number Types: Number
Integer: int
Floating-point: float
Complex: complex
Boolean: bool
List: list
Tuple: tuple
Dictionary: dict
Set: set
Mutable Data Types: list, dict, set
Immutable Data Types: string, number, tuple
Container Types: string, list, tuple, set, dict
Non-container Types: number, boolean
'''
Data Type Conversion
-
What is data type conversion?
-
It is converting one data type into another, for example, converting a string to a number.
-
Why is data type conversion necessary?
-
Because different data types cannot be operated on together.
-
Forms of data type conversion?
-
Automatic type conversion.
-
Forced type conversion.
Automatic Type Conversion
# Automatic type conversion
# When two different values are operated on, the result is calculated with higher precision.
# True ==> Integer ==> Float ==> Complex
a = 123
b = True # When operating with numbers, True is converted to 1, False to 0.
# print(a + b)
# print(12.5 + 22)
# print(True + 3.14)
Forced Type Conversion
Each data type in Python has a corresponding method to convert data types.
-
str() can convert all other data types to string type.
-
int(): When converting a string to a number, if the string contains only digits, it can be converted.
-
Other container types cannot be converted to int type.
-
float(): The conversion of floating-point types is similar to int, but the result is a floating-point type.
-
bool(): Can convert other types to boolean type True or False.
-
Summary: Cases where the result of converting to bool is False:
-
'', 0, 0.0, False, [], {}, (), set()
-
list(): List
-
Numeric types are non-container types and cannot be converted to list.
-
When converting a string to a list, each character in the string is treated as an element of the list.
-
Sets can be converted to list type.
-
Tuples can be converted to list type.
-
Dictionaries can be converted to list type, retaining only the keys of the dictionary.
-
tuple(): Tuple
-
Numeric types are non-container types and cannot be converted to tuple.
-
When converting other container types, it is similar to lists.
-
set(): Set
-
Numeric types are non-container types and cannot be converted to set.
-
Strings, lists, and tuples can be converted to sets, resulting in an unordered collection.
-
Dictionaries converted to sets retain only the keys.
-
dict(): Dictionary
-
Numeric types are non-container types and cannot be converted to dictionary.
-
Strings cannot be directly converted to dictionaries.
-
Lists can be converted to dictionaries, requiring a two-dimensional list where each secondary element must have two values.
-
Tuples can be converted to dictionaries, requiring a two-dimensional tuple where each secondary element must have two values.