How to save data in Python? How to choose data types? What conditions should be used to make the program make automatic judgments?
Don’t worry, today we will start with the basic concepts of “variables”, “data types”, and “conditional statements” to unlock the first step of Python programming in the most relatable way!
These seemingly simple basics are actually the foundation for various cool features later on. With a solid foundation, you can build your own Python mansion!
1. What is a variable? How to name it without “crashing”?
In Python, a variable is like a little sticky note you put on your computer to store things (data). For example, if you want to remember a person’s name, you can write:
name = "Tony" # Store "Tony" in the variable name
From then on, whenever you use name, Python knows you are referring to “Tony”.
Tip:
- The variable name cannot start with a number, for example,
1st_nameis not allowed! - Variable names are case-sensitive, for example,
ageandAgeare two different variables.
Exercise: Give yourself a nickname and save it in a variable, for example:
nickname = "SuperCoder"
print(nickname) # Try to see what it outputs?
2. What are the common data types in Python?
Different types of data will have different “boxes” to store them. The common ones are:
- Integer (int)
Used to store age, scores, and other data without decimal points.
age = 18
print(type(age)) # Output: <class 'int'>
- Float (float)
Numbers with decimal points, suitable for storing prices, heights, etc.
price = 19.99
print(type(price)) # Output: <class 'float'>
- String (str)
A string of characters, can be used for greetings or recording names.
greeting = "Hello, 世界!"
print(type(greeting)) # Output: <class 'str'>
- Boolean (bool)
Actually just True (true) and False (false), suitable for making judgments.
is_adult = True
print(type(is_adult)) # Output: <class 'bool'>
Tip:
- When assigning values to variables, the data type is automatically determined; there is no need to declare the type, Python will do it for you.
- If you want to change a certain data type, you can use functions like
int(),float(),str()to convert.
For example:
s = "100"
n = int(s) # Convert the string "100" to an integer
print(n + 50) # Output: 150
3. Let Python help you make choices – Conditional Statements (if statements)
In life, there are often scenarios like: “If I am hungry, I will eat; otherwise, I won’t eat”. In Python, this kind of **”either/or, multiple choices”** is called a conditional statement.
- Basic structure
if condition:
# Execute this code if the condition is true
else:
# Execute this code if the condition is false
For example: you want to determine if someone is an adult
age = 20
if age >= 18:
print("You are now an adult!")
else:
print("Not yet an adult, keep growing!")
Output:
You are now an adult!
- Multiple condition judgments (
elif)
Sometimes there are more than two choices, you can use elif (which means “else if…”).
score = 75
if score >= 90:
print("Excellent!")
elif score >= 60:
print("Passed!")
else:
print("Almost there, keep it up!")
Output:
Passed!
- Compound conditions (
and,or)
Sometimes you need to meet multiple conditions (and), or just one of the conditions is enough (or):
user = "root"
pwd = "123456"
if user == "root" and pwd == "123456":
print("Login successful!")
else:
print("Username or password is incorrect.")
4. Mixing variables & data types in conditions
Don’t think that judgments can only use numbers. Strings, booleans, and even other variables can participate in judgments. For example:
rain = False
if rain:
print("Take an umbrella!")
else:
print("The weather is nice, let's go!")
Here rain is directly used as a condition, True executes the first line, False executes the second line.
For example, to check if the input is valid:
username = input("Please enter your username:") # The input is always a string type
if username == "":
print("Username cannot be empty!")
else:
print("Welcome, " + username + "!")
5. Common pitfalls and confusing points
- Use
==for equality checks
Many students mistakenly use =, but the equal sign = is for assignment, while the double equal sign == is for comparison.
# Incorrect example
if x = 10: ❌ This will cause an error!
print("Correct!")
# Correct approach
if x == 10: ✔️
print("Correct!")
- Be careful with data type comparisons
Using input() will always return a string! If you want to input a number, remember to convert it:
num = input("Please enter a number:")
if num == 10: # This compares a string and an integer, which will never be equal!
print("You entered 10")
Correction:
num = int(input("Please enter a number:")) # Convert input to integer
if num == 10:
print("You entered 10")
- Indentation is crucial!
Python uses indentation (usually 4 spaces) to indicate the hierarchy of code. If the indentation is incorrect, the program will throw an error or run with logical errors, so be extra careful.
6. Hands-on practice – Post-class challenges
- Let the user input their age and determine if they can enter an internet cafe (18 years and older).
- Input a score, if it is greater than or equal to 90, output “Excellent”; if greater than or equal to 60, output “Passed”; otherwise output “Not Passed” (use
if...elif...elseto complete). - If it rains today (controlled by a boolean value rain), print “Remember to take an umbrella”, otherwise print “The weather is clear”.
Those with ideas can post in the comments section to discuss together!
7. Learn to search for information, everyone can be a “search expert”
It is normal to encounter things you don’t know while coding. Check the official documentation more, Google (or ask me on ChatGPT), and you will gradually get it! Don’t understand how to use variables, data types, and conditional statements? CTRL+F to the part you want to see, copy it once and then talk!
8. Summary of today’s gains
Today we discussed three major Python basics:
- Variables: Help you store data, naming cannot be random.
- Data types: Integers, floats, strings, booleans, each has its own use.
- Conditional statements: if judgments help you make choices, making the program smarter.
These contents may seem simple, but in reality, whether it’s web scraping, data analysis, or AI projects, they all rely on them. The more solid the foundation, the smoother the subsequent learning will be!
Friends, today’s Python learning journey ends here! Remember to practice coding, and feel free to ask questions in the comments section. Wishing everyone a happy learning experience and continuous improvement in Python!