Fundamentals 21 min read

Python Basics: Comments, Indentation, Variables, Data Types, Operators, Strings, Lists, Conditionals, Loops, and Functions

This comprehensive tutorial introduces Python fundamentals, covering comments, indentation, variable naming rules, core data types, type conversion, arithmetic and comparison operators, string manipulation, list operations, conditional statements, loop constructs, and custom function definitions with clear examples and code snippets.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Python Basics: Comments, Indentation, Variables, Data Types, Operators, Strings, Lists, Conditionals, Loops, and Functions

Before diving into statistical analysis with Python, it is essential to master the basic syntax and common operations of the language. This guide consolidates the most frequently used Python constructs to help beginners quickly become familiar with core concepts.

1. Comments and Indentation

Comments

Comments do not affect program execution and improve readability.

Single‑line comments start with #:

# comment on its own line
print("Python statistical analysis")  # print output

Running the above prints:

Python statistical analysis

Indentation

Python uses indentation to define code blocks. The PEP 8 style guide recommends four spaces per level and discourages mixing spaces with tabs.

Although any number of spaces or tabs can technically be used, it is strongly recommended to follow the PEP 8 guideline of using 4 spaces as the indentation unit.

All statements in the same block must have the same indentation:

if True:
    print("True")
else:
    print("False")

Inconsistent indentation causes a runtime error:

if True:
    print("Answer")
    print("True")
else:
    print("Answer")
  print("False")  # Indentation mismatch

2. Variable Naming

Python variables are created by assignment without explicit type declaration:

x = 10      # integer
y = "Python statistical analysis"  # string
z = 3.14    # float

Rules

Names may contain letters (A‑Z, a‑z), digits (0‑9), and underscores ( _).

The first character must be a letter or underscore; it cannot be a digit.

Variable names are case‑sensitive ( myVariablemyvariable).

Names cannot be Python reserved keywords (e.g., for, if, while, class).

Use meaningful names; follow PEP 8 by using lowercase words separated by underscores, e.g., employee_name instead of EmployeeName or employeename.

3. Data Types

Numeric Types

int : arbitrary‑size integers, e.g., 123, -456.

float : floating‑point numbers, e.g., 3.14, -2.0.

complex : numbers with real and imaginary parts, e.g., 3+2j.

Boolean

Two values: True and False.

String ( str )

Text enclosed in single or double quotes, e.g., "Hello, World!".

Sequence Types

list ( []): ordered, mutable collection, e.g., [1, 2, "three"].

tuple ( ()): ordered, immutable collection, e.g., (1, 2, 3).

Mapping Type

dict ( {}): unordered key‑value pairs, e.g., {"name": "Alice", "age": 25}.

Set Type

set ( {} for non‑empty sets, set() for an empty set) stores unordered, unique elements.

Other Special Types

NoneType ( None) represents the absence of a value.

4. Type Conversion

Implicit Conversion

When mixing types, Python automatically promotes to the higher‑precision type:

num_int = 123
num_flo = 1.23
num_new = num_int + num_flo
print("num_int type:", type(num_int))
print("num_flo type:", type(num_flo))
print("num_new value:", num_new)
print("num_new type:", type(num_new))

Explicit Conversion

Use built‑in functions such as int(), float(), str():

x = int(1)      # 1
y = int(2.8)    # 2
z = int("3")   # 3
print(x, type(x))
print(y, type(y))
print(z, type(z))

5. Operators

Arithmetic

Assuming a = 10 and b = 21:

Operator

Description

Example

+

Addition

a + b → 31

-

Subtraction

a - b → -11

*

Multiplication

a * b → 210

**

Exponentiation

a ** b → 10⁽²¹⁾

/

Division

b / a → 2.1

//

Floor division

b // a → 2

%

Modulo

b % a → 1

Comparison

With a = 10, b = 20:

Operator

Description

Result

==

Equal

(a == b) → False

!=

Not equal

(a != b) → True

>

Greater than

(a > b) → False

<

Less than

(a < b) → True

>=

Greater or equal

(a >= b) → False

<=

Less or equal

(a <= b) → True

Assignment

Common operators include =, +=, -=, *=, /=, %=, **=, //=.

6. Strings

Creation

str1 = 'Hello, World!'
str2 = "This is also a string."

Access

greeting = "Hello!"
first_char = greeting[0]  # 'H'

Slicing

sub_str = greeting[0:5]  # 'Hello'

Length

length = len(greeting)  # 6

Concatenation and Repetition

name = "Alice"
message = "Hi, " + name + "!"
repeated = "Python " * 3  # 'Python Python Python '

Formatting

num = 42
formatted = f"The answer is {num}"  # f-string

Common Methods

lower()

,

upper()
strip()
split()
join()
find()

,

index()
replace(old, new)

7. Lists

Creation

empty_list = []
numbers_list = [1, 2, 3, 4, 5]
mixed_list = [1, "apple", True, None]
another_list = list(("a", "b", "c"))

Access and Slicing

lst = ["apple", "banana", "cherry"]
first_item = lst[0]   # 'apple'
last_item = lst[-1]   # 'cherry'
sublist = lst[1:3]    # ['banana']

Modification

lst[0] = "grape"
lst.append("date")
lst.insert(0, "kiwi")
removed = lst.pop()      # last element
lst.pop(0)               # remove first element
lst.remove("apple")
lst.extend([6,7])
lst.sort()
lst.reverse()
len_lst = len(lst)
count = lst.count("banana")

8. Conditional Statements

if condition:
    # true block
elif other_condition:
    # else‑if block
else:
    # false block

Example:

temperature = 25
if temperature > 20:
    print("It's warm outside.")

9. Loop Statements

while Loop

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

for Loop

numbers = [1, 2, 3, 4, 5]
for number in numbers:
    print(number)

Control keywords: break – exit the loop immediately. continue – skip the rest of the current iteration.

for i in range(10):
    if i % 2 == 0:
        continue  # skip even numbers
    print(i)      # prints odd numbers

j = 0
while j < 10:
    j += 1
    if j == 5:
        break   # exit when j reaches 5
    print(j)

10. Custom Functions

def greet(name):
    print(f"Hello, {name}!")

greet("Bob")  # Output: Hello, Bob!

Function definition uses the def keyword, optional parameters, default values, and variable‑length arguments ( *args, **kwargs). Functions may return a value with return; otherwise they return None.

Parameter Types

Required positional parameters.

Keyword parameters (named arguments).

Default parameters with preset values.

Variable‑length parameters: *args for extra positional arguments, **kwargs for extra keyword arguments.

def add_numbers(*nums):
    total = sum(nums)
    return total

result = add_numbers(1,2,3,4)
print(result)  # 10

References

Python 3 Tutorial | 菜鸟教程

Python Official Documentation

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 Typesprogramming fundamentalssyntaxControl Flow
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

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.