Fundamentals 15 min read

Python Basics: Variables, Data Types, Control Flow, Functions, and Common Operations

This article provides a comprehensive introduction to Python fundamentals, covering language features, variable handling, data types such as numbers, strings, lists, tuples, dictionaries, as well as control structures, loops, functions, exception handling, file I/O, and time processing with practical code examples.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Python Basics: Variables, Data Types, Control Flow, Functions, and Common Operations

Python Basics Overview

Python is an easy‑to‑learn yet powerful interpreted language. This guide walks through the most essential concepts for beginners.

Python Characteristics

Interpreted language – no compilation needed.

Interactive command line support.

Object‑oriented programming paradigm.

Cross‑platform compatibility (Windows, macOS, Linux).

Simple syntax with strong capabilities.

01 Encoding

Linux and macOS use UTF‑8 by default, while Windows often uses ASCII. Mismatched encodings cause garbled text. It is common to declare UTF‑8 at the top of a Python script:

<code>#!/usr/bin/env python
# coding:utf8</code>

02 Variables

Variables act as containers for values. Names may contain letters, digits, and underscores but cannot start with a digit. Python is weakly typed, so no explicit type declaration is required.

03 Numbers

Python supports integers and floating‑point numbers:

<code># integer a = 1
# float b = 2.1
print a, b</code>

04 Strings

Strings are enclosed in single or double quotes. They can be concatenated with + and their length obtained with len() . Slicing accesses substrings:

<code>c = "Hello"
d = "你好"
print c, d
print c + d
print len(c)
# slice examples
c[0]      # first character
c[-1]     # last character
c[1:5]    # characters 2 to 5
c[1:-1]
</code>

05 Lists

Lists store ordered collections of arbitrary objects. Elements are accessed by index, and the list size is obtained with len() :

<code># create and populate a list
a = []
a.append(1)
a.append(2.1)
a.append("Hello")
print a
print len(a)
print a[1], a[-1]
a[1] = 100
print a
del a[0]
print a
</code>

06 Tuples

Tuples are immutable ordered collections:

<code># define a tuple
a = (1, 2.1, "Hello")
# a[0] = 100  # raises an error
</code>

07 Dictionaries

Dictionaries map keys to values. Keys must be unique and immutable. Use has_key() (or in in modern Python) to test for a key:

<code># define a dictionary
di = {}
di["k1"] = 1
di["k2"] = 2.1
di["k3"] = "Hello"
print di.has_key("k4")  # False
</code>

08 Comments

Comments start with # and are ignored by the interpreter, improving code readability.

<code># single‑line comment
# multi‑line comment can be written with multiple # symbols
</code>

09 Reserved Keywords

Avoid using Python reserved words (e.g., import , class ) as variable names.

<code># this would raise a SyntaxError
# import = 1
</code>

10 Indentation

Python uses indentation to define code blocks. Consistent indentation is required for constructs such as if , for , while , try , etc.

11 Operators

Common operators include arithmetic ( + - * / % ), comparison ( == != > < >= <= ), assignment ( = += -= *= /= %= ), and logical ( and or not ).

<code>a = 1
b = 2
print a + b          # 3
print a == b         # False
# equivalent to a = a + 3
a += 3
print a              # 4
c = True
d = False
print c and d        # False
</code>

12 Conditions

Conditional statements execute code based on boolean expressions:

<code>a = 1
if a == 1:
    print "11111"
if a == 2:
    print "22222"
else:
    print "33333"
if a == 1:
    print "11111"
elif a == 2:
    print "22222"
else:
    print "33333"
</code>

13 Loops

Loops repeat actions while a condition holds or for a known number of iterations.

14 while Loop

<code>flag = 1
while flag < 10:
    print flag
    flag += 1  # modify the condition variable
</code>

15 for Loop

<code>for x in xrange(0, 10):
    print x
</code>

Iterate over lists or dictionaries:

<code>li = [1, 2.1, "Hello"]
di = {"k1":1, "k2":2.1, "k3":"Hello"}
for item in li:
    print item
for key in di.keys():
    print key
for value in di.values():
    print value
for key, value in di.items():
    print key, value
</code>

16 Loop Control

<code>for x in xrange(0, 10):
    if x == 5:
        pass
    else:
        print x
for x in xrange(0, 10):
    if x == 5:
        continue
    print x
for x in xrange(0, 10):
    if x == 5:
        break
    print x
</code>

17 Time Handling

Python represents moments as timestamps (seconds since 1970‑01‑01 00:00:00 UTC). Conversions between timestamps and formatted strings are common:

<code># current timestamp
import time
t = time.time()
print t, type(t)
# string to timestamp
a = "2016-10-01 10:00:00"
a = int(time.mktime(time.strptime(a, "%Y-%m-%d %H:%M:%S")))
print a
# timestamp to string
b = int(time.time())
b = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(b))
print b
</code>

18 Exceptions

Use try/except/else/finally to catch and handle runtime errors, preventing abrupt termination.

<code>try:
    print 1 / 0
except Exception as e:
    print e
else:
    print "No error"
finally:
    print "Always executed"
</code>

19 Functions

Functions encapsulate reusable logic. Define with def and call by name, passing arguments as needed.

<code># define a function
def hello(name1, name2):
    print "Hello " + name1 + " " + name2
# call the function
hello("Python", "JavaScript")
</code>
PythonData Typeserror handlingFunctionsVariablesProgramming Basicscontrol 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

login 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.