Master Python Basics: Data Types, Control Flow, Functions, and More in Minutes
This tutorial introduces Python 3 fundamentals—including primitive data types, operators, variables, collections, control structures, functions, classes, modules, and advanced features like generators and decorators—through concise explanations and runnable code examples that let readers quickly grasp the language's core concepts.
Python was designed by Guido van Rossum in the early 1990s and is now one of the most widely used programming languages. Its syntax is concise and almost executable pseudocode.
Note: This tutorial is based on Python 3.
Source code download: https://learnxinyminutes.com/docs/files/learnpython3-cn.py
# Single‑line comment starts with a hash
""" Multi‑line string using three quotes
also often used as a multi‑line comment
"""1. Primitive Data Types and Operators
# integer
3 # => 3
# basic arithmetic
1 + 1 # => 2
8 - 1 # => 7
10 * 2 # => 20
# division always returns a float
35 / 5 # => 7.0
5 / 3 # => 1.6666666666666667
# floor division (integer division) truncates toward negative infinity
5 // 3 # => 1
5.0 // 3.0 # => 1.0
-5 // 3 # => -2
-5.0 // 3.0 # => -2.0
# float arithmetic results in a float
3 * 2.0 # => 6.0
# modulo
7 % 3 # => 1
# exponentiation
2**4 # => 16
# parentheses control precedence
(1 + 3) * 2 # => 8
# booleans
True
False
# logical NOT
not True # => False
not False # => True
# logical AND / OR (lowercase)
True and False # => False
False or True # => True
# integers can be used as booleans
0 and 2 # => 0
-5 or 0 # => -5
0 == False # => True
2 == True # => False
1 == True # => True
# equality and inequality
1 == 1 # => True
2 == 1 # => False
1 != 1 # => False
2 != 1 # => True
# comparison operators
1 < 10 # => True
1 > 10 # => False
2 <= 2 # => True
2 >= 2 # => True
1 < 2 < 3 # => True
2 < 3 < 2 # => False
# strings (single or double quotes)
"This is a string"
'This is also a string'
# concatenate strings with +
"Hello " + "world!" # => "Hello world!"
# indexing strings
"This is a string"[0] # => 'T'
# format strings
"{} can be {}".format("strings", "interpolated")
"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick")
"{name} wants to eat {food}".format(name="Bob", food="lasagna")
"%s can be %s the %s way" % ("strings", "interpolated", "old")
# None is an object
None # => None
"etc" is None # => False
None is None # => True
# falsy values: None, 0, empty string, empty list, empty dict
bool(0) # => False
bool("") # => False
bool([]) # => False
bool({}) # => False2. Variables and Collections
# print is the built‑in output function
print("I'm Python. Nice to meet you!")
# variable assignment (no prior declaration needed)
some_var = 5 # => 5
# accessing an undefined variable raises NameError
# some_unknown_var # NameError
# lists
li = []
other_li = [4, 5, 6]
li.append(1) # li is now [1]
li.append(2) # li is now [1, 2]
li.append(4) # li is now [1, 2, 4]
li.append(3) # li is now [1, 2, 4, 3]
li.pop() # => 3 and li is now [1, 2, 4]
li.append(3) # li becomes [1, 2, 4, 3]
li[0] # => 1
li[-1] # => 3
# out‑of‑range access raises IndexError
# li[4]
# slicing
li[1:3] # => [2, 4]
li[2:] # => [4, 3]
li[:3] # => [1, 2, 4]
li[::2] # => [1, 4]
li[::-1] # => [3, 4, 2, 1]
# delete element
del li[2] # li is now [1, 2, 3]
# list concatenation (original lists unchanged)
li + other_li # => [1, 2, 3, 4, 5, 6]
# extend list
li.extend(other_li) # li is now [1, 2, 3, 4, 5, 6]
# membership test
1 in li # => True
# length
len(li) # => 6
# tuples (immutable sequences)
tup = (1, 2, 3)
tup[0] # => 1
# tup[0] = 3 # TypeError
len(tup) # => 3
tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6)
tup[:2] # => (1, 2)
2 in tup # => True
# tuple unpacking
a, b, c = (1, 2, 3) # a=1, b=2, c=3
# parentheses are optional
d, e, f = 4, 5, 6
# swap values
e, d = d, e # d=5, e=4
# dictionaries (mapping)
empty_dict = {}
filled_dict = {"one": 1, "two": 2, "three": 3}
filled_dict["one"] # => 1
list(filled_dict.keys()) # order not guaranteed, e.g. ["three", "two", "one"]
list(filled_dict.values()) # e.g. [3, 2, 1]
"one" in filled_dict # => True
1 in filled_dict # => False
# accessing missing key raises KeyError
# filled_dict["four"]
filled_dict.get("one") # => 1
filled_dict.get("four") # => None
filled_dict.get("four", 4) # => 4
filled_dict.setdefault("five", 5) # adds key "five"
filled_dict.update({"four": 4}) # now contains "four"
filled_dict["four"] = 4
# delete key
del filled_dict["one"]
# sets (unordered collections of unique items)
empty_set = set()
some_set = {1, 1, 2, 2, 3, 4} # => {1, 2, 3, 4}
filled_set = some_set
filled_set.add(5) # => {1, 2, 3, 4, 5}
other_set = {3, 4, 5, 6}
filled_set & other_set # => {3, 4, 5}
filled_set | other_set # => {1, 2, 3, 4, 5, 6}
{1, 2, 3, 4} - {2, 3, 5} # => {1, 4}
2 in filled_set # => True
10 in filled_set # => False3. Control Flow and Iterators
# define a variable
some_var = 5
# if / elif / else example
if some_var > 10:
print("some_var is greater than 10")
elif some_var < 10:
print("some_var is less than 10")
else:
print("some_var is exactly 10")
# for loop over a list
for animal in ["dog", "cat", "mouse"]:
print("{} is a mammal".format(animal))
# range loop
for i in range(4):
print(i)
# while loop
x = 0
while x < 4:
print(x)
x += 1
# try / except example
try:
raise IndexError("This is an index error")
except IndexError as e:
pass # handle the error
except (TypeError, NameError):
pass
else:
print("All good!")
# iterables and iterators
filled_dict = {"one": 1, "two": 2, "three": 3}
our_iterable = filled_dict.keys()
print(our_iterable) # dict_keys(['one', 'two', 'three'])
for i in our_iterable:
print(i) # prints one, two, three
# our_iterable[1] # TypeError
our_iterator = iter(our_iterable)
print(our_iterator.__next__()) # => "one"
print(our_iterator.__next__()) # => "two"
print(our_iterator.__next__()) # => "three"
# next call raises StopIteration
# list(filled_dict.keys()) # => ['one', 'two', 'three']4. Functions
# define a function
def add(x, y):
print("x is {} and y is {}".format(x, y))
return x + y
add(5, 6) # prints and returns 11
add(y=6, x=5) # keyword arguments, order doesn't matter
# variable‑length positional arguments
def varargs(*args):
return args
varargs(1, 2, 3) # => (1, 2, 3)
# variable‑length keyword arguments
def keyword_args(**kwargs):
return kwargs
keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"}
# mixing both
def all_the_args(*args, **kwargs):
print(args)
print(kwargs)
# all_the_args(1, 2, a=3, b=4) prints (1, 2) and {"a": 3, "b": 4}
args = (1, 2, 3, 4)
kwargs = {"a": 3, "b": 4}
all_the_args(*args) # equivalent to all_the_args(1, 2, 3, 4)
all_the_args(**kwargs) # equivalent to all_the_args(a=3, b=4)
all_the_args(*args, **kwargs)
# scope example
x = 5
def setX(num):
x = num # local x
print(x) # => 43
def setGlobalX(num):
global x
print(x) # => 5 (original global)
x = num # modifies global x
print(x) # => 6
setX(43)
setGlobalX(6)
# functions are first‑class objects
def create_adder(x):
def adder(y):
return x + y
return adder
add_10 = create_adder(10)
add_10(3) # => 13
# lambda (anonymous) function
(lambda x: x > 2)(3) # => True
# higher‑order built‑ins
map(add_10, [1, 2, 3]) # => [11, 12, 13]
filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13]
[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7]5. Classes
# define a class inheriting from object
class Human(object):
species = "H. sapiens"
def __init__(self, name):
self.name = name
def say(self, msg):
return "{name}: {message}".format(name=self.name, message=msg)
@classmethod
def get_species(cls):
return cls.species
@staticmethod
def grunt():
return "*grunt*"
# instantiate and use
i = Human(name="Ian")
print(i.say("hi")) # "Ian: hi"
j = Human("Joel")
print(j.say("hello")) # "Joel: hello"
print(i.get_species()) # "H. sapiens"
# change class attribute
Human.species = "H. neanderthalensis"
print(i.get_species()) # "H. neanderthalensis"
print(j.get_species()) # "H. neanderthalensis"
print(Human.grunt()) # "*grunt*"6. Modules
# import a module
import math
print(math.sqrt(16)) # => 4.0
# import specific names
from math import ceil, floor
print(ceil(3.7)) # => 4.0
print(floor(3.7)) # => 3.0
# import everything (not recommended)
from math import *
# alias a module name
import math as m
print(math.sqrt(16) == m.sqrt(16)) # => True
# list all attributes of a module
import math
print(dir(math))7. Advanced Usage
# generators for lazy evaluation
def double_numbers(iterable):
for i in iterable:
yield i + i
# range itself is a lazy generator
range_ = range(1, 900000000)
for i in double_numbers(range_):
print(i)
if i >= 30:
break
# decorators
from functools import wraps
def beg(target_function):
@wraps(target_function)
def wrapper(*args, **kwargs):
msg, say_please = target_function(*args, **kwargs)
if say_please:
return "{} {}".format(msg, "Please! I am poor :(")
return msg
return wrapper
@beg
def say(say_please=False):
msg = "Can you buy me a beer?"
return msg, say_please
print(say()) # "Can you buy me a beer?"
print(say(say_please=True)) # "Can you buy me a beer? Please! I am poor :("Translation: Geoff Liu; original authors: Louie Dinh Source: https://learnxinyminutes.com/docs/zh-cn/python3-cn/
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.
21CTO
21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.
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.
