Fundamentals 13 min read

Master Python Basics: Variables, Data Types, and Core Syntax

This article provides a comprehensive introduction to Python fundamentals, covering its key features, variable handling, core data types such as numbers, strings, lists, tuples, and dictionaries, as well as essential concepts like comments, indentation, operators, control structures, time handling, file I/O, exception handling, and function definitions, complete with practical code examples.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Master Python Basics: Variables, Data Types, and Core Syntax

Python Basics Overview

Python is an interpreted, object‑oriented language that runs on Windows, macOS, and Linux. It offers an interactive shell, simple syntax, and powerful built‑in features.

Key Features

Interpreted language – no compilation needed.

Interactive command line.

Object‑oriented programming.

Cross‑platform compatibility.

Simple yet powerful.

Variables

Variables act as containers for values. Names may contain letters, digits, and underscores but cannot start with a digit and are case‑sensitive.

Python is weakly typed; you do not declare a type when creating a variable.

Data Types

Common built‑in types include:

Numbers – integers and floating‑point numbers.

# integer a = 1
# float b = 2.1
print a, b

Strings – text enclosed in single or double quotes.

c = 'Hello'
d = '你好'
print c, d

Use + to concatenate and len() to get length. Slicing accesses substrings.

Lists – ordered collections that can hold any type.

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

Tuples – immutable ordered collections.

a = (1, 2.1, 'Hello')
# a[0] = 100  # raises error

Dictionaries – key‑value mappings accessed by keys.

di = {}
di['k1'] = 1
di['k2'] = 2.1
di['k3'] = 'Hello'
print di['k1']
print di.has_key('k4')  # False

Comments

Use # for single‑line comments and triple quotes '''...''' for block comments. In Sublime Text, select code and press Ctrl+/ to toggle comments.

Reserved Words

Avoid using Python keywords such as import, class, etc., as variable names.

Indentation

Code blocks are defined by indentation rather than braces. Consistent indentation is required for if, while, for, try, etc.

Operators

Arithmetic: +, -, *, /, % Comparison: ==, !=, >, <, >=, <= Assignment: =, +=, -=, *=, /=, %= Logical: and, or,

not

Conditional Statements

a = 1
if a == 1:
    print '11111'
else:
    print '33333'

if a == 1:
    print '11111'
elif a == 2:
    print '22222'
else:
    print '33333'

Loops

While loop repeats while a condition is true.

flag = 1
while flag < 10:
    print flag
    flag += 1

For loop iterates over a range or iterable.

for x in xrange(0, 10):
    print x

for item in li:
    print item
for key in di.keys():
    print key
for key, value in di.items():
    print key, value

Loop control statements include pass, continue, and break.

for x in xrange(0, 10):
    if x == 5:
        pass
    else:
        print x

Time Handling

Python represents time as a timestamp – seconds since 1970‑01‑01 00:00:00 UTC.

import time
t = time.time()
print t, type(t)
# Convert string to timestamp
s = '2016-10-01 10:00:00'
ts = int(time.mktime(time.strptime(s, '%Y-%m-%d %H:%M:%S')))
print ts
# Convert timestamp to string
now = int(time.time())
print time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(now))

File I/O

# Write file
fw = open('data.txt', 'w')
for x in xrange(0, 10):
    fw.write(str(x) + '
')
fw.close()
# Read file
fr = open('data.txt', 'r')
for line in fr:
    print line.strip()
fr.close()

Exception Handling

try:
    print 1 / 0
except Exception as e:
    print e
else:
    print 'No error'
finally:
    print 'Always runs'

Functions

Functions encapsulate reusable code and may accept parameters.

def hello(name1, name2):
    print 'Hello ' + name1 + ' ' + name2

hello('Python', 'JavaScript')
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.

functionsVariablesbasicscontrol-flowdata-types
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.