
Data Types
Hello, new Python friend! Today we'll start with the most basic data types. Don't be intimidated by the term "data types" - it's simply the way programming languages store different kinds of data. You can think of it as different containers in real life, like baskets for storing fruits, boxes for storing files, and so on.
Python has several built-in common data types, such as integers (int), floating-point numbers (float), strings (str), and boolean values (bool). Let me give you a simple example:
age = 25 # integer
weight = 65.5 # float
name = "Alice" # string
is_student = True # boolean
See, we've used different data types to store age, weight, name, and student status. Python's power lies in its ability to easily handle various types of data.
However, data types are not limited to these. Today, we'll focus on a very practical data type - dictionary (dict).
Introduction to Dictionaries
Dictionaries are used to store key-value pair data, just like a real-life dictionary where you can look up the definition (value) of a word (key).
Let's look at an example. Suppose you have a good friend named Alice:
friend = {'name': 'Alice', 'age': 25, 'city': 'Beijing'}
We defined a dictionary using a pair of curly braces {}
, storing Alice's name, age, and city of residence. You can access values in the dictionary like this:
print(friend['name']) # Output: Alice
We use friend['name']
to get Alice's name. Isn't it intuitive? You can also modify or add new key-value pairs:
friend['age'] = 26 # Modify age
friend['email'] = '[email protected]' # Add email
In short, dictionaries allow you to efficiently store and manipulate paired data, which is hugely useful in programming. But this is just an appetizer; dictionaries have many more functions that you can explore as you become more familiar with the basics.
Function Basics
If data types are the containers of programming, then functions are the most basic operational units. Functions make code modular, which is beneficial for reuse and maintenance.
Defining a function in Python is super simple. You just need to use the def
keyword followed by the function name, and write your code in the function body. For example:
def greet(name):
print(f"Hello, {name}!")
greet('Alice') # Output: Hello, Alice!
We defined a function called greet
that takes a name
parameter and prints out a corresponding greeting. When calling it, you just need to pass in the required parameter value.
Functions can not only receive parameters but also return values. Let's modify the above example:
def greet(name):
return f"Hello, {name}!"
greeting = greet('Alice')
print(greeting) # Output: Hello, Alice!
Using the return
keyword, the function will return the value when it executes to that line, which can be assigned to other variables for use.
You see, although functions are small, they play a very important role in code. They allow us to encapsulate common operations, improving code readability and reusability. Once you master functions, the fun of programming begins!
List Techniques
In programming, we often need to handle a set of ordered data, such as a list of numbers or a string of characters. This is where the list data type comes in handy.
Creating a list in Python is super easy. You just need to use []
and put comma-separated elements inside:
numbers = [1, 2, 3, 4, 5]
fruits = ['apple', 'banana', 'orange']
We've created a list storing numbers and another storing fruit names. You can access elements in the list using an index:
print(numbers[0]) # Output: 1
print(fruits[2]) # Output: orange
Indexing starts from 0, so numbers[0]
represents the first element of the list.
However, sometimes we need to perform some complex operations on lists, such as creating a new list. This is where we can use list comprehension, a powerful syntactic sugar.
Suppose we want to create a list storing the squares of numbers 0-9. The traditional way is:
squares = []
for i in range(10):
squares.append(i**2)
Using list comprehension, it only takes one line of code:
squares = [x**2 for x in range(10)]
Isn't it much more concise? The syntax form of [x**2 for x in range(10)]
is equivalent to:
- Iterate through
range(10)
to get a sequence of numbers 0-9 - Perform the
x**2
operation on each elementx
in the sequence - Create a new list with the operation results
Besides being concise, list comprehension is also faster to execute! This is a technique you must remember.
Time Handling
In programming, we often need to handle time and date data. Fortunately, Python has prepared the datetime
module for us, which allows us to complete many tasks with just a few lines of code.
For example, if you want to calculate how many hours and minutes are between 9:15 and 14:50, you can do this:
from datetime import datetime
def time_diff(start, end):
start = datetime.strptime(start, "%H%M")
end = datetime.strptime(end, "%H%M")
diff = end - start
return diff.seconds//3600, (diff.seconds//60)%60
start_time = "0915"
end_time = "1450"
hours, mins = time_diff(start_time, end_time)
print(f"The time difference is {hours} hours and {mins} minutes")
The output will be The time difference is 5 hours and 35 minutes
.
Let me explain this code:
- First, we import the
datetime
class from thedatetime
module - We define a
time_diff
function that takes two time strings as parameters - Inside the function, we use the
strptime
method to convert strings todatetime
objects - Subtracting two
datetime
objects gives atimedelta
object, which records the time difference - We calculate the hours and minutes parts separately from the
timedelta
object - Finally, we print out the result
This is just a small example; the datetime
module has a lot of practical functions for you to explore. Time handling is an essential skill for every programmer, and now you've laid the foundation.
Exception Handling
During programming, we inevitably encounter various errors and exceptional situations. If not handled, the program will crash and exit directly, which is a terrible experience. So we need to learn exception handling techniques.
Python uses the try...except
structure to catch exceptions. The syntax is as follows:
try:
# Some code that might cause an error
except ExceptionType1:
# Code to handle ExceptionType1
except ExceptionType2:
# Code to handle ExceptionType2
When an exception occurs during the execution of statements in the try
block, Python will match the exception type after except
and execute the corresponding handling code.
For example, you can catch a ZeroDivisionError
exception like this:
try:
result = 10 / 0
except ZeroDivisionError:
print("The divisor cannot be 0!")
Since 0 cannot be used as a divisor, the statement 10 / 0
will raise a ZeroDivisionError
exception. We caught this exception through except
and executed custom handling code.
Common exception types include ValueError
, TypeError
, etc. You can catch and handle them friendly in your code. This not only makes the program more robust but also improves user experience.
Exception handling is a good habit that should be reflected in your code from now on. It might feel a bit unfamiliar at first, but with practice, you'll quickly master the trick.
Summary
Alright, that's all for today. We've gone through the basics of Python programming, including data types, functions, lists, and more. You must firmly grasp these concepts as they are the foundation for further learning.
Python is popular because of its simplicity and efficiency. It's not only easy to get started with but can also be used in various scenarios, from small programs to large website applications.
What we've learned today is just the tip of the iceberg. The path to mastering Python is still long. But as long as you maintain your enthusiasm and keep learning and practicing, one day you too can become a Python expert. Go for it, the gates of programming will open for you!
Next
Python Basics: From Beginner to Advanced
This article delves into Python fundamentals, covering core concepts such as data types, functional programming, time handling, and exception handling. It aims
Python Object-Oriented Programming: From Beginner to Master, A Complete Guide to Classes and Objects
A comprehensive guide covering Python programming fundamentals and advanced features, including environment setup, language elements, modular programming, object-oriented programming, and domain-specific development
Python Programming Beginner's Guide: Master This Simple and Easy-to-Learn Programming Language
This article introduces key knowledge points for getting started with Python programming, including an introduction to Python, basic syntax, practical examples, and recommended learning resources, helping beginners quickly master this simple and widely applicable programming language.
Next

Python Basics: From Beginner to Advanced
This article delves into Python fundamentals, covering core concepts such as data types, functional programming, time handling, and exception handling. It aims

Python Object-Oriented Programming: From Beginner to Master, A Complete Guide to Classes and Objects
A comprehensive guide covering Python programming fundamentals and advanced features, including environment setup, language elements, modular programming, object-oriented programming, and domain-specific development

Python Programming Beginner's Guide: Master This Simple and Easy-to-Learn Programming Language
This article introduces key knowledge points for getting started with Python programming, including an introduction to Python, basic syntax, practical examples, and recommended learning resources, helping beginners quickly master this simple and widely applicable programming language.