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 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:
#!/usr/bin/env python
# coding:utf802 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:
# integer a = 1
# float b = 2.1
print a, b04 Strings
Strings are enclosed in single or double quotes. They can be concatenated with + and their length obtained with len(). Slicing accesses substrings:
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]05 Lists
Lists store ordered collections of arbitrary objects. Elements are accessed by index, and the list size is obtained with len():
# 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 a06 Tuples
Tuples are immutable ordered collections:
# define a tuple
a = (1, 2.1, "Hello")
# a[0] = 100 # raises an error07 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:
# define a dictionary
di = {}
di["k1"] = 1
di["k2"] = 2.1
di["k3"] = "Hello"
print di.has_key("k4") # False08 Comments
Comments start with # and are ignored by the interpreter, improving code readability.
# single‑line comment
# multi‑line comment can be written with multiple # symbols09 Reserved Keywords
Avoid using Python reserved words (e.g., import, class) as variable names.
# this would raise a SyntaxError
# import = 110 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).
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 # False12 Conditions
Conditional statements execute code based on boolean expressions:
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"13 Loops
Loops repeat actions while a condition holds or for a known number of iterations.
14 while Loop
flag = 1
while flag < 10:
print flag
flag += 1 # modify the condition variable15 for Loop
for x in xrange(0, 10):
print xIterate over lists or dictionaries:
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, value16 Loop Control
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 x17 Time Handling
Python represents moments as timestamps (seconds since 1970‑01‑01 00:00:00 UTC). Conversions between timestamps and formatted strings are common:
# 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 b18 Exceptions
Use try/except/else/finally to catch and handle runtime errors, preventing abrupt termination.
try:
print 1 / 0
except Exception as e:
print e
else:
print "No error"
finally:
print "Always executed"19 Functions
Functions encapsulate reusable logic. Define with def and call by name, passing arguments as needed.
# define a function
def hello(name1, name2):
print "Hello " + name1 + " " + name2
# call the function
hello("Python", "JavaScript")Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
