1.1 Literals
A literal is a fixed value written directly in the source code. It represents a constant value that doesn't change during program execution.
Common literal types in Python:
100
3.14159
"Software Engineer"
print(100)
print(3.14159)
print("Software Engineer")
1.2 Comments
Comments are annotations ignored by the Python interpreter. They help developers understand code.
Single-line comments use the # symbol. Everything after # on that line is treated as a comment. A space after # improves readability. Single-line comments typically explain specific lines or small code blocks.
Multi-line comments use triple quotes ''' or """. All content within these quotes is ignored and can span multiple lines. Multi-line comments are commonly used to document modules, classes, and functions.
# This is a single-line comment
"""This is a multi-line comment
that spans several lines
for comprehensive documentation"""
1.3 Variables
Variables store values that can be modified during program execution.
Definition format:
variable_name = value
Key characteristic: The value stored in a variable can change throughout the program's lifecycle.
Outputting multiple values: Use commas within the print() function to display multiple items.
# Store account balance in a variable
balance = 1000
print("Current balance:", balance)
# Withdraw 250 dollars
balance = balance - 250
print("After withdrawal:", balance, "dollars")
user_name = "Alice"
user_age = 28
1.4 Data Types
Checking data types: Use the type() function to determine a value's data type.
About variables: Variables themselves don't have types. A variable marked as a string means it contains a string value, not that the variable itself is classified as a string type.
# Method 1: Print type information directly
print(type("Hello World"))
print(type(999))
print(type(2.71828))
# Method 2: Store type() results in variables
string_type = type("Hello World")
int_type = type(999)
float_type = type(2.71828)
print(string_type)
print(int_type)
print(float_type)
# Method 3: Use type() to check the type of data stored in a variable
country = "United States"
country_type = type(country)
print(country_type)
1.5 Type Conversion
Conversion funcsions: str(), int(), float()
Important rules:
- Any type can be converted to a string
- Converting a string to a number requires the string to contain only numeric characters
- Converting a float to an integer truncates the decimal portion, losing precision
# Convert numbers to strings
num_str = str(42)
print(type(num_str), num_str)
float_str = str(3.14159)
print(type(float_str), float_str)
# Convert strings to numbers
num = int("42")
print(type(num), num)
num2 = float("3.14159")
print(type(num2), num2)
# Conversion error example - string must contain only digits
# num3 = int("twenty")
# print(type(num3), num3)
# Integer to float
float_num = float(42)
print(type(float_num), float_num)
# Float to integer - decimal is truncated
int_num = int(3.14159)
print(type(int_num), int_num)
1.6 Identifiers
Identifiers are names created by the developer to label variables, classes, functions, and other code elements.
Naming rules:
- Character restrictions: Only Chinese characters, English letters, digits, and underscores are allowed. Digits cannot start the name.
- Case sensitivity:
Variableandvariableare treated as different identifiers - Reserved keywords: Cannot use Python's built-in keywords
Naming conventions for variables:
- Names should be descriptive and self-explanatory
- Use snake_case (words separated by underscores)
- Keep all letters lowercase
# Rule 1: Only letters, digits, underscores; cannot start with a digit
# Invalid: 2nd_place = "runner"
# Invalid: total! = 100
first_name = "Bob"
_last = "Smith"
item2 = "widget"
# Rule 2: Case-sensitive
PythonCourse = "Advanced"
python_course = "Beginner"
print(PythonCourse)
print(python_course)
# Rule 3: Cannot use reserved keywords
# Invalid: def = 1
# Invalid: class = "Container"
Class = 1
1.7 Operators
Arithmetic operators:
- Addition:
+ - Subtraction:
- - Multiplication:
* - Division:
/ - Floer division:
// - Modulus:
% - Exponentiation:
**
Assignment operators:
- Simple assignment:
= - Compound assignments:
+=,-=,*=,/=,//=,%=,**=
1.8 String Definition Methods
Python supports three ways to define strings:
- Single quotes:
'text' - Double quotes:
"text" - Triple quotes:
'''text'''or"""text"""- allows multi-line strings
Quote nesting:
- Use backslash
\for escaping quotes - Single quotes can contain double quotes, and vice versa
1.9 String Concatenation
Concatenation method: Use the + operator to join string literals or string variables.
Limitation: Cannot directly concatenate strings with non-string types.
# Concatenating string literals
print("Learn " + "Python " + "Today")
# Concatenating literal with variable
title = "Engineer"
company = "TechCorp"
phone = 5551234
print("Position: " + title + " at " + company)
# This would error: print("Phone: " + phone)
1.10 String Formatting with Placeholders
Syntax: "%placeholder" % variable
Common placeholders:
%s- strings%d- integers%f- floats
# Using placeholders for string concatenation
developer = "Backend Specialist"
message = "Career path: %s" % developer
print(message)
# Combining numbers and strings
cohort = 23
salary = 95000
message = "Web Development track, cohort %d, average salary: $%s" % (cohort, salary)
print(message)
company = "InnovateTech"
founded = 2015
stock_value = 45.67
message = "%s founded in %d, stock price: %f" % (company, founded, stock_value)
print(message)
1.11 Format Specifier Precision Control
Syntax: Use m.n format like %5d, %7.2f, %.2f
mcontrols minimum width.ncontrols decimal precision- Both can be omitted
Behavior:
- If
mis less than the number's width,mhas no effect .nrounds the decimal portion
num1 = 42
num2 = 3.14159
print("Width 5:", "%5d" % num1)
print("Width 1:", "%1d" % num1)
print("Width 8, precision 2:", "%8.2f" % num2)
print("Auto width, precision 2:", "%.2f" % num2)
1.12 f-String Formatting
Syntax: f"{variable} {variable}"
Advantages:
- Ignores type specifications
- No precision control
- Cleaner and more readable for quick formatting
1.13 Formatting Expressions
Expression definition: Code that evaluates to a specific result, such as 1 + 1, len("text"), or 5 * 8.
During variable assignment like total = 25 + 30, the right side is an expression that produces a result assigned to the variable.
Formatting methods:
f"{expression}""%s\%d\%f" % (expr1, expr2, expr3)
1.14 User Input with input()
The input() function reads data from the keyboard.
Usage: input("prompt message") displays a prompt before waiting for user input.
Critical note: All input values are returned as strings, regardless of what the user types.