Fundamentals 18 min read

Master Python Basics: Data Types, Control Flow, Functions, and More

This tutorial walks through Python fundamentals, covering primitive data types, operators, variables, collections, control structures, functions, classes, modules, and advanced features such as generators and decorators, all illustrated with clear code examples and explanations.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Master Python Basics: Data Types, Control Flow, Functions, and More

1. Primitive Data Types and Operators

# Single-line comment starts with a hash

""" Multi-line strings are enclosed in triple quotes
    and are often used for multi-line comments
"""
# Integer
3  # => 3

# Arithmetic behaves as expected
1 + 1  # => 2
8 - 1  # => 7
10 * 2  # => 20

# Division always returns a float
35 / 5  # => 7.0
5 / 3  # => 1.6666666666666667

# Integer division floors the result
5 // 3      # => 1
5.0 // 3.0  # => 1.0
-5 // 3     # => -2
-5.0 // 3.0 # => -2.0

# Float arithmetic yields floats
3 * 2.0  # => 6.0

# Modulo
7 % 3  # => 1

# Exponentiation
2**4  # => 16

# Parentheses control precedence
(1 + 3) * 2  # => 8

# Booleans
True
False

# Logical NOT
not True   # => False
not False  # => True

# Logical AND / OR
True and False  # => False
False or True   # => True

# Integers can be used as booleans
0 and 2   # => 0
-5 or 0   # => -5
0 == False  # => True
2 == True   # => False
1 == True   # => True

# Equality and inequality
1 == 1   # => True
2 == 1   # => False
1 != 1   # => False
2 != 1   # => True

# Comparison operators
1 < 10   # => True
1 > 10   # => False
2 <= 2   # => True
2 >= 2   # => True
1 < 2 < 3  # => True
2 < 3 < 2  # => False

# Strings
"这是个字符串"
'这也是个字符串'
"Hello " + "world!"  # => "Hello world!"
"This is a string"[0]  # => 'T'
"{} can be {}".format("strings", "interpolated")
"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick")
"{name} wants to eat {food}".format(name="Bob", food="lasagna")
"%s can be %s the %s way" % ("strings", "interpolated", "old")

# None and truthiness
None  # => None
"etc" is None  # => False
None is None   # => True
bool(0)   # => False
bool("")  # => False
bool([])  # => False
bool({})  # => False

2. Variables and Collections

# print is the built‑in output function
print("I'm Python. Nice to meet you!")

# No need to declare variables beforehand
some_var = 5  # => 5

# Accessing an undefined variable raises NameError
# some_unknown_var  # raises NameError

# Lists store ordered sequences
li = []
other_li = [4, 5, 6]
li.append(1)   # li is now [1]
li.append(2)   # li is now [1, 2]
li.append(4)   # li is now [1, 2, 4]
li.append(3)   # li is now [1, 2, 4, 3]
li.pop()       # => 3 and li becomes [1, 2, 4]
li.append(3)   # li back to [1, 2, 4, 3]

# Indexing works like arrays
li[0]   # => 1
li[-1]  # => 3
# Out‑of‑range access raises IndexError
# li[4]

# Slicing syntax
li[1:3]   # => [2, 4]
li[2:]    # => [4, 3]
li[:3]    # => [1, 2, 4]
li[::2]   # => [1, 4]
li[::-1]  # => [3, 4, 2, 1]

# Delete an element
del li[2]   # li becomes [1, 2, 3]

# List concatenation (original lists unchanged)
li + other_li   # => [1, 2, 3, 4, 5, 6]
li.extend(other_li)  # li becomes [1, 2, 3, 4, 5, 6]
1 in li   # => True
len(li)   # => 6

# Tuples are immutable sequences
tup = (1, 2, 3)
tup[0]   # => 1
# tup[0] = 3  # raises TypeError
len(tup)   # => 3
tup + (4, 5, 6)   # => (1, 2, 3, 4, 5, 6)
tup[:2]   # => (1, 2)
2 in tup   # => True

a, b, c = (1, 2, 3)   # a=1, b=2, c=3

d, e = 4, 5
# Swap values
e, d = d, e   # d=5, e=4

# Dictionaries map keys to values
empty_dict = {}
filled_dict = {"one": 1, "two": 2, "three": 3}
filled_dict["one"]   # => 1
list(filled_dict.keys())   # => ["three", "two", "one"] (order not guaranteed)
list(filled_dict.values()) # => [3, 2, 1]
"one" in filled_dict   # => True
1 in filled_dict         # => False
filled_dict["four"]      # raises KeyError
filled_dict.get("one")   # => 1
filled_dict.get("four")  # => None
filled_dict.get("one", 4)   # => 1
filled_dict.get("four", 4)  # => 4
filled_dict.setdefault("five", 5)   # adds key "five"
filled_dict.update({"four": 4})
filled_dict["four"] = 4

del filled_dict["one"]   # removes key "one"

# Sets store unique unordered items
empty_set = set()
some_set = {1, 1, 2, 2, 3, 4}   # => {1, 2, 3, 4}
filled_set = some_set
filled_set.add(5)   # => {1, 2, 3, 4, 5}
other_set = {3, 4, 5, 6}
filled_set & other_set   # => {3, 4, 5}
filled_set | other_set   # => {1, 2, 3, 4, 5, 6}
{1, 2, 3, 4} - {2, 3, 5}   # => {1, 4}
2 in filled_set   # => True
10 in filled_set  # => False

3. Control Flow and Iterators

some_var = 5

if some_var > 10:
    print("some_var比10大")
elif some_var < 10:
    print("some_var比10小")
else:
    print("some_var就是10")

# For‑loop over a list
for animal in ["dog", "cat", "mouse"]:
    print("{} is a mammal".format(animal))

# Range generates numbers from 0 up to n‑1
for i in range(4):
    print(i)

x = 0
while x < 4:
    print(x)
    x += 1

# Exception handling
try:
    raise IndexError("This is an index error")
except IndexError as e:
    pass
except (TypeError, NameError):
    pass
else:
    print("All good!")

# Iterables and iterators
filled_dict = {"one": 1, "two": 2, "three": 3}
our_iterable = filled_dict.keys()
print(our_iterable)  # dict_keys(['one', 'two', 'three'])

for i in our_iterable:
    print(i)  # prints one, two, three

# Direct indexing raises TypeError
# our_iterable[1]

our_iterator = iter(our_iterable)
our_iterator.__next__()  # => "one"
our_iterator.__next__()  # => "two"
our_iterator.__next__()  # => "three"
# Next call raises StopIteration
# list(filled_dict.keys())  # => ["one", "two", "three"]

4. Functions

# Define a function
def add(x, y):
    print("x is {} and y is {}".format(x, y))
    return x + y

add(5, 6)   # prints and returns 11
add(y=6, x=5)  # keyword arguments, order irrelevant

# Variable‑length positional arguments
def varargs(*args):
    return args
varargs(1, 2, 3)   # => (1, 2, 3)

# Variable‑length keyword arguments
def keyword_args(**kwargs):
    return kwargs
keyword_args(big="foot", loch="ness")  # => {"big": "foot", "loch": "ness"}

# Mix both
def all_the_args(*args, **kwargs):
    print(args)
    print(kwargs)
# all_the_args(1, 2, a=3, b=4) prints (1, 2) and {"a": 3, "b": 4}
args = (1, 2, 3, 4)
kwargs = {"a": 3, "b": 4}
all_the_args(*args)      # equivalent to all_the_args(1,2,3,4)
all_the_args(**kwargs)   # equivalent to all_the_args(a=3, b=4)
all_the_args(*args, **kwargs)

# Scope example
x = 5

def setX(num):
    x = num  # local x
    print(x)  # => 43

def setGlobalX(num):
    global x
    print(x)  # => 5
    x = num
    print(x)  # => 6

setX(43)
setGlobalX(6)

# Functions are first‑class objects
def create_adder(x):
    def adder(y):
        return x + y
    return adder

add_10 = create_adder(10)
add_10(3)   # => 13

# Anonymous lambda
(lambda x: x > 2)(3)   # => True

# Higher‑order built‑ins
map(add_10, [1, 2, 3])   # => [11, 12, 13]
filter(lambda x: x > 5, [3,4,5,6,7])   # => [6,7]
[add_10(i) for i in [1,2,3]]   # => [11,12,13]
[x for x in [3,4,5,6,7] if x > 5]   # => [6,7]

5. Classes

class Human(object):
    species = "H. sapiens"

    def __init__(self, name):
        self.name = name

    def say(self, msg):
        return "{name}: {message}".format(name=self.name, message=msg)

    @classmethod
    def get_species(cls):
        return cls.species

    @staticmethod
    def grunt():
        return "*grunt*"

# Instances
i = Human(name="Ian")
print(i.say("hi"))   # Ian: hi
j = Human("Joel")
print(j.say("hello"))  # Joel: hello

# Class method
print(i.get_species())   # H. sapiens
Human.species = "H. neanderthalensis"
print(i.get_species())   # H. neanderthalensis
print(j.get_species())   # H. neanderthalensis

# Static method
print(Human.grunt())   # *grunt*

6. Modules

# Import a module
import math
print(math.sqrt(16))  # => 4.0

# Import specific names
from math import ceil, floor
print(ceil(3.7))   # => 4.0
print(floor(3.7))  # => 3.0

# Import all (not recommended)
from math import *

# Alias a module
import math as m
print(math.sqrt(16) == m.sqrt(16))   # => True

# Modules are just .py files; you can list their contents
import math
print(dir(math))

7. Advanced Usage

# Generators for lazy evaluation
def double_numbers(iterable):
    for i in iterable:
        yield i + i

range_ = range(1, 900000000)
for i in double_numbers(range_):
    print(i)
    if i >= 30:
        break

# Decorators
from functools import wraps

def beg(target_function):
    @wraps(target_function)
    def wrapper(*args, **kwargs):
        msg, say_please = target_function(*args, **kwargs)
        if say_please:
            return "{} {}".format(msg, "Please! I am poor :(")
        return msg
    return wrapper

@beg
def say(say_please=False):
    msg = "Can you buy me a beer?"
    return msg, say_please

print(say())                     # Can you buy me a beer?
print(say(say_please=True))      # Can you buy me a beer? Please! I am poor :(
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonData Typesclassesprogramming basics
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.