For beginners in Python, the first step is often to understand how to make the program “speak” (output), how to make the program “listen” (input), and how to make the program perform calculations (operators).
These three fundamental concepts are like the “letters + phonetics” when learning English, forming the foundation of all Python programs. Today, we will use an easy-to-understand note to help you master these concepts at once, so you can start writing simple interactive programs right after reading!
1. print(): The Output Function that Makes the Program “Speak”
<span>print()</span> is the most commonly used “output tool” in Python, which prints data to the screen for us to view the results. Whether it’s variables, numbers, or text, it can display them.
1. Basic Usage: 3 Common Output Scenarios
(1) Outputting the Value of a Variable
First, define a variable, then use <span>print(variable_name)</span> to output its value:
# Define variable: age is 18<span>age = 18 # Output variable print(age) # Result: 18</span>
(2) Outputting Constants
Directly putting numbers or text (enclosed in quotes) into <span>print()</span> outputs constants:
# Output number constant<span>print(100) # Result: 100 # Output string constant (double or single quotes are fine) print("Hello Python") # Result: Hello Python</span>
(3) Outputting the Result of an Expression
<span>print()</span> can also directly calculate an “expression” (like addition, subtraction, multiplication, division) and output the result:
# Calculate the sum of 100 + 200 + 300<span>print(100 + 200 + 300) # Result: 600 # Want to output "100+200+300" as is? Just enclose it in quotes as a string print("100+200+300") # Result: 100+200+300</span>
2. Advanced Techniques: Outputting Multiple Contents at Once
If you want to output multiple pieces of data at the same time, use commas<span>,</span> to separate them, and <span>print()</span> will automatically add spaces between the data:
name = “Xiao Ming” age = 12 score = 95.5 # Mixed output of variables, strings, and expressions print(“Name:”, name, “Age:”, age, “Total Score:”, score + 4.5) # Result: Name: Xiao Ming Age: 12 Total Score: 100.0
3. Formatted Output: Making Content More Organized
When a fixed format is needed (like “My name is XX, I am XX years old”), using <span>%</span> format specifiers can make the output more concise. This is one of the most commonly used output methods in actual development.
Common Format Specifiers Quick Reference
| Format Specifier | Function | Example | Result |
|---|---|---|---|
<span>%s</span> |
Output string (universal specifier) | <span>print("Name: %s" % "Xiao Hong")</span> |
Name: Xiao Hong |
<span>%d</span> |
Output integer | <span>print("Age: %d" % 15)</span> |
Age: 15 |
<span>%f</span> |
Output floating-point number | <span>print("Score: %f" % 92.5)</span> |
Score: 92.500000 |
Practical Example: Combining Multiple Variables for Output
name = “Xiao Li” age = 20 height = 175.5 # Use multiple format specifiers to combine output print(“My name is %s, I am %d years old, and my height is %.1f cm” % (name, age, height)) # Result: My name is Xiao Li, I am 20 years old, and my height is 175.5 cm
⚠️ Note:<span>%.1f</span><span> means keeping 1 decimal place; adjust the number as needed (for example, </span><code><span>%.2f</span><span> keeps 2 decimal places).</span>
4. Escape Characters: Achieving Special Formats like New Lines and Tabs
Sometimes you need to output effects like new lines or indentation, and that’s when you use escape characters (which start with <span>\</span>). There are just 2 common ones to remember:
| Escape Character | Function | Code Example | Running Effect |
|---|---|---|---|
<span>\n</span> |
New line | <span>print("First line\nSecond line")</span> |
First line Second line |
<span>\t</span> |
Tab character (similar to the Tab key) | <span>print("Name\tAge")</span> |
Name Age |
For example, to create a simple “score sheet” format:
print(“Name\tChinese\tMath\tEnglish”) print(“Xiao Ming\t90\t95\t88”) print(“Xiao Hong\t85\t92\t96”) # Result: # Name Chinese Math English # Xiao Ming 90 95 88 # Xiao Hong 85 92 96
2. input(): The Input Function that Makes the Program “Listen”
<span>input()</span> is used to get the content entered by the user from the keyboard, enabling interaction between the program and the user. For example, allowing the user to input their name, password, score, etc., and then processing the input accordingly.
1. Basic Usage: Input with Prompt
The syntax is very simple:<span>variable = input("Prompt text")</span>, where “Prompt text” will be displayed on the screen to guide the user to input.
# Prompt the user to input their name and store the input in the name variable<span>name = input("Please enter your name:") # Output welcome message print("Welcome, " + name + "!")</span>
After running, it will first display “Please enter your name:”, wait for you to input and press enter, and then output “Welcome, XXX!”.
2. Core Pitfall: input() Returns a String by Default!
This is the most common pitfall for beginners:Regardless of whether the user inputs a number or text, input() will treat it as a “string”. If you want to perform mathematical calculations, you must first convert the string to a number!
Incorrect Example vs Correct Example
# Incorrect Example: Directly using the result of input() for calculations<span>num = input("Please enter a number:") print(num + 10) # Error! Cannot add string and number</span># Correct Example: Use int()/float() to convert to a number
# Convert to integer (suitable for integer input)<span>num1 = int(input("Please enter an integer:")) print(num1 + 10) # Normal calculation</span># Convert to floating-point number (suitable for decimal input)<span>num2 = float(input("Please enter a decimal:")) print(num2 + 2.5) # Normal calculation</span>
3. Practical Example: Input Two Numbers and Calculate the Sum
# Step 1: Input and convert types<span>a = float(input("Please enter the first number:")) b = float(input("Please enter the second number:")) # Step 2: Calculate the sum sum_ab = a + b # Step 3: Output the result print("The sum of the two numbers is:", sum_ab)</span>
Running effect: Please enter the first number: 15.5 Please enter the second number: 4.5 The sum of the two numbers is: 20.0
3. Operators: The Tools that Make the Program “Calculate”
Operators are the “calculator buttons” in Python, used for addition, subtraction, multiplication, division, comparison, etc. They can be divided into 4 main categories, but focusing on the first two is sufficient.
1. Arithmetic Operators: Performing Mathematical Calculations
The most commonly used operators handle addition, subtraction, multiplication, division, and modulus, taking <span>a=10, b=20</span> as an example:
| Operator | Name | Function Description | Example | Result |
|---|---|---|---|---|
<span>+</span> |
Addition | Adds two numbers; concatenates strings | <span>a+b</span> / <span>"a"+"b"</span> |
30 / “ab” |
<span>-</span> |
Subtraction | Subtracts two numbers | <span>a-b</span> |
-10 |
<span>*</span> |
Multiplication | Multiplies two numbers; repeats strings | <span>a*b</span> / <span>"a"*3</span> |
200 / “aaa” |
<span>/</span> |
Division | Result is a floating-point number | <span>b/a</span> |
2.0 |
<span>//</span> |
Floor Division | Only keeps the integer part of the quotient | <span>9//2</span> |
4 |
<span>%</span> |
Modulus | Returns the remainder of division (commonly used) | <span>21%10</span> |
1 |
<span>**</span> |
Exponentiation | Calculates a number raised to the power of n | <span>2**3</span> |
8 |
Practical Scenarios:
- Modulus
<span>%</span>: Determine odd/even numbers (<span>num%2==0</span>is even), loop counting; - Floor Division
<span>//</span>: Pagination calculation (for example, 100 items, 10 per page, total<span>100//10=10</span>pages).
Priority Reminder:
Like in mathematics, calculate exponentiation first (<span>**</span>), then multiplication and division (<span>*</span>, <span>/</span>, <span>//</span>, <span>%</span>), and finally addition and subtraction (<span>+</span>, <span>-</span>); use <span>()</span> to force change the order, and it is recommended to use it often to avoid ambiguity: print<span>(10 + 5 * 2) # Multiply first, result 20 print((10 + 5) * 2) # Add first, result 30</span>
2. Assignment Operators: Assigning Values to Variables
(1) Basic Assignment:<span>=</span>
Assign the value on the right to the variable on the left; this is the most basic operation:
x = 5 # Assign 5 to x y = x + 3 # Assign the result of x + 3 (8) to y
(2) Multiple Variable Assignment: Assigning Multiple Values in One Line
Assign multiple values to multiple variables at once; the number on both sides must match:
name, age, score = “Xiao Zhang”, 16, 90 print(name) # Xiao Zhang print(age) # 16
(3) Compound Assignment: Simplifying “Operation + Assignment”
When you need to perform an operation on a variable and then assign it, using compound assignment is more concise, taking <span>c=10, a=5</span> as an example:
| Operator | Equivalent Writing | Example | Result |
|---|---|---|---|
<span>+=</span> |
<span>c = c + a</span> |
<span>c += a</span> |
15 |
<span>-=</span> |
<span>c = c - a</span> |
<span>c -= a</span> |
5 |
<span>*=</span> |
<span>c = c * a</span> |
<span>c *= a</span> |
50 |
<span>/=</span> |
<span>c = c / a</span> |
<span>c /= a</span> |
2.0 |
For example, to “accumulate” a variable:
count = 0 # Add 1 each time, for a total of 3 times count += 1 count += 1 count += 1 print(count) # Result: 3
3. Comparison Operators: Judging “True or False”
Used to compare the relationship between two values, the result can only be:<span>True</span> (true) or <span>False</span> (false), commonly used in conditional judgments.
| Operator | Name | Example | Result |
|---|---|---|---|
<span>==</span> |
Equal | <span>10==20</span> |
False |
<span>!=</span> |
Not Equal | <span>10!=20</span> |
True |
<span>></span> |
Greater Than | <span>10>20</span> |
False |
<span><</span> |
Less Than | <span>10<20</span> |
True |
<span>>=</span> |
Greater Than or Equal | <span>10>=10</span> |
True |
<span><=</span> |
Less Than or Equal | <span>20<=15</span> |
False |
⚠️ Important Distinction:<span>=</span> is “assignment”, while <span>==</span> is “equality check”; do not confuse them!
4. Logical Operators: Combining “Conditional Judgments”
When you need to judge multiple conditions at the same time, use logical operators to connect them, and the result is also <span>True</span> or <span>False</span>.
| Operator | Name | Function Description | Example | Result |
|---|---|---|---|---|
<span>and</span> |
Logical AND | Returns True only if both sides are True | <span>(10>5) and (20<30)</span> |
True |
<span>or</span> |
Logical OR | Returns True if either side is True | <span>(10>20) or (20<30)</span> |
True |
<span>not</span> |
Logical NOT | Negates (turns true to false, false to true) | <span>not (10>5)</span> |
False |
Practical Example: Judging “Whether Adult and Score Passed”
age = 19 score = 80 # Judging: age >= 18 and score >= 60 is_qualified = (age >= 18) and (score >= 60) print(is_qualified) # Result: True
4. Comprehensive Practice: Writing a “Score Calculator”
Combine what we learned today: <span>print()</span>, <span>input()</span>, and operators to write a small program that calculates the “total score” and “average score”:
print(“===== Score Calculator =====”) # 1. Input scores for 3 subjects (convert to float) chinese = float(input(“Please enter Chinese score:”)) math = float(input(“Please enter Math score:”)) english = float(input(“Please enter English score:”)) # 2. Calculate total and average total = chinese + math + english average = total / 3 # 3. Format output result (average keeps 1 decimal place) print(“\n===== Score Summary =====”) print(“Chinese: %.1f points” % chinese) print(“Math: %.1f points” % math) print(“English: %.1f points” % english) print(“———————“) print(“Total: %.1f points” % total) print(“Average: %.1f points” % average) # 4. Judging whether passed (average >= 60) if average >= 60: print(“Conclusion: Passed! 🎉”) else: print(“Conclusion: Not Passed, keep working hard! 💪”)
Running effect:
===== Score Calculator =====<span>Please enter Chinese score: 85 Please enter Math score: 92 Please enter English score: 78 ===== Score Summary ===== Chinese: 85.0 points Math: 92.0 points English: 78.0 points --------------------- Total: 255.0 points Average: 85.0 points Conclusion: Passed! 🎉</span>
5. 3 Key Points Every Beginner Must Remember
<span>print()</span>separates multiple outputs with commas, formatting uses<span>%s</span>/<span>%d</span>/<span>%f</span>;<span>input()</span>results must be type-converted for calculations, use<span>int()</span>for integers, and<span>float()</span>for decimals;- Operator precedence: calculate
<span>()</span>and<span>**</span>first, then multiplication and division, and finally addition and subtraction; if unsure, add<span>()</span>.
Mastering these three points, you have already crossed the first hurdle of getting started with Python. Next time, we will learn about “conditional statements” and “loops”, allowing the program to handle different situations differently. Stay tuned!
If you find this useful, feel free to like and bookmark it, and try typing the code yourself for a deeper impression!