Fundamentals 39 min read

Master Python Basics: Essential Syntax, Variables, and Operators Explained

This comprehensive guide walks you through Python fundamentals, covering its philosophy, installation, basic syntax, comments, operators, data types, variable naming, control structures, loops, functions, and module usage, providing clear examples and practical tips for quick reference.

Efficient Ops
Efficient Ops
Efficient Ops
Master Python Basics: Essential Syntax, Variables, and Operators Explained

Preface

This article aims to concisely summarize Python fundamentals for quick reference during practical exercises.

Part 1: Python Basic Syntax

1.1 Introduction to Python

Python was created by Guido van Rossum. Its design goals include being simple, powerful, open‑source, and easy to read like plain English, suitable for short‑term development tasks.

Python's design philosophy: "There should be one—and preferably only one—obvious way to do it."

Python is a fully object‑oriented language where everything is an object. Critical code can be written in C or C++ for performance.

1.2 First Python Program

Python programs can be run via interpreter, interactive shell, or IDE. Python 2.x interpreter is python, Python 3.x is python3. Transition version 2.7 is provided for compatibility.

Tip: If you cannot immediately use Python 3.0, develop with 3.0 first, then run with 2.6/2.7 for compatibility.

IPython offers a richer interactive shell than the default python shell and supports bash commands.

1.3 PyCharm Setup

PyCharm configuration files are stored in the user home directory under .PyCharm<version>. To reset settings:

Close PyCharm.

Run $ rm -r ~/.PyCharm2016.3 in terminal.

Re‑install PyCharm:

Extract the tarball:

$ tar -zxvf pycharm-professional-2017.1.3.tar.gz

Move the directory to /opt: $ sudo mv pycharm-2017.1.3/ /opt/ Start PyCharm: $ cd /opt/pycharm-2017.1.3/bin then $ ./pycharm.sh To create a desktop entry, enable "Create the entry for all users" in Tools → Create Desktop Entry.

1.4 Multi‑File Project Practice

Each project has an independent directory for all related files.

In PyCharm, right‑click a Python file to run it.

Beginner projects often contain multiple runnable scripts for practice; production projects usually have a single entry point.

2. Comments

Comments improve readability. Single‑line comments start with #. Use a space after # and at least two spaces before the comment text.

print("hello python")  # output "hello python"
For readability, add a space after # and keep at least two spaces between code and comment.

2.2 Multi‑Line Comments

Enclose text in triple quotes ( ''' or """) to create a block comment.

"""
This is a multi‑line comment
...
"""
print("hello python")

2.3 Code Style Guidelines

Refer to PEP 8 for Python style conventions.

Google also provides a Chinese style guide.

3. Operators

3.1 Arithmetic Operators

Operator

Description

Example

+

Addition

10 + 20 = 30

-

Subtraction

10 - 20 = -10

*

Multiplication

10 * 20 = 200

/

Division

10 / 20 = 0.5

//

Floor division

9 // 2 = 4

%

Modulo

9 % 2 = 1

**

Exponentiation

2 ** 3 = 8

3.2 Comparison Operators

Python 2.x also supports <> for inequality; != works in both versions.

3.3 Assignment Operators

Use = for assignment. Compound assignment operators (e.g., +=) combine arithmetic with assignment and must not contain spaces.

3.4 Identity Operators

is

checks whether two variables reference the same object; == checks value equality.

3.5 Membership Operators

in

tests whether a value exists in a sequence (list, tuple, string, dict keys).

3.6 Logical Operators

Use and, or, and not for logical conjunction, disjunction, and negation.

3.7 Operator Precedence

Operators are evaluated from highest to lowest precedence as documented in Python references.

4. Variables

4.1 Variable Definition

Variables must be assigned before use.

Assignment syntax: variable = value.

variable_name = value
In the interactive shell, typing a variable name displays its value; in scripts, use print() to output.

4.2 Variable Types

Numeric types: int, float, bool, complex.

Non‑numeric types: str, tuple, dict, list.

name_list = ["zhangsan", "lisi", "wangwu"]

4.3 Variable Naming

Identifiers consist of letters, digits, and underscores, cannot start with a digit, and must not clash with keywords.

Use snake_case for multi‑word names (e.g., first_name) or camelCase as needed.

4.4 Advanced Variable Types

4.4.1 Lists

Lists are ordered, mutable collections defined with [].

name_list = ["zhangsan", "lisi", "wangwu"]

4.4.2 Tuples

Tuples are ordered, immutable sequences defined with (). A single‑element tuple requires a trailing comma.

info_tuple = ("zhangsan", 18, 1.75)

4.4.3 Dictionaries

Dictionaries store key‑value pairs, defined with {}. Keys must be immutable.

xiaoming = {"name": "小明", "age": 18, "gender": True, "height": 1.75}

4.4.4 Strings

Strings are sequences of characters defined with single or double quotes. Use \ for escape sequences.

string = "Hello Python"
for c in string:
    print(c)

4.4.5 Common Operations

Length: len() Indexing and slicing: seq[start:stop:step] Concatenation: +, repetition:

*
num_str = "0123456789"
print(num_str[2:6])      # 2345
print(num_str[::2])      # 02468
print(num_str[::-1])     # 9876543210

4.5 Variable References

Variables hold references to objects in memory. The id() function shows an object's memory address. Assignment changes the reference, not the original object.

def test(num):
    print("%d address: %x" % (num, id(num)))
    result = 100
    print("%d address: %x" % (result, id(result)))
    return result

a = 10
print("before call address: %x" % id(a))
 r = test(a)
print("after call address: %x" % id(a))
print("return address: %x" % id(r))

4.6 Mutable vs Immutable Types

Immutable: int, float, bool, str, tuple.

Mutable: list, dict.

5. Conditional Statements

5.1 if Syntax

if condition:
    # true branch
else:
    # false branch
Indentation must be consistent (spaces recommended).

5.2 Logical Operators

condition1 and condition2   # both true
condition1 or condition2    # either true
not condition                # negation

5.3 elif

if cond1:
    ...
elif cond2:
    ...
else:
    ...

6. Loops

6.1 while Loop

counter = 0
while counter < 5:
    print(counter)
    counter += 1

6.2 break and continue

break exits the loop; continue skips to the next iteration.

6.3 Nested while Loops

row = 1
while row <= 9:
    col = 1
    while col <= row:
        print("%d * %d = %d" % (col, row, row*col), end="\t")
        col += 1
    print("")
    row += 1

7. Functions

7.1 Defining and Calling Functions

def sum_2_num(num1, num2):
    result = num1 + num2
    print("%d + %d = %d" % (num1, num2, result))

sum_2_num(50, 20)

7.2 Function Parameters

Positional parameters: def func(a, b): Default (optional) parameters: def func(a, b=True): Variable‑length arguments: *args (tuple) and **kwargs (dict).

def demo(num, *args, **kwargs):
    print(num)
    print(args)
    print(kwargs)

demo(1, 2, 3, name="小明", age=18)

7.3 Return Values

def sum_2_num(num1, num2):
    return num1 + num2

result = sum_2_num(10, 20)
print("Result is %d" % result)

7.4 Nested Function Calls

def test1():
    print("*"*50)
    print("test 1")
    print("*"*50)

def test2():
    print("-"*50)
    print("test 2")
    test1()
    print("-"*50)

test2()

7.5 Recursion

def sum_numbers(num):
    if num == 1:
        return 1
    return num + sum_numbers(num - 1)

print(sum_numbers(5))

7.6 Modules

Python files (*.py) are modules. Import them with import module_name and access their variables/functions via module_name.attribute. Modules are compiled to .pyc bytecode for faster loading.

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.

PythonfunctionssyntaxVariablesoperatorsbasics
Efficient Ops
Written by

Efficient Ops

This public account is maintained by Xiaotianguo and friends, regularly publishing widely-read original technical articles. We focus on operations transformation and accompany you throughout your operations career, growing together happily.

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.