Python Basics
We all need to start somewhere, so how about doing it here. This guide covers the fundamental Python basics including operators, data types, variables, and core functions.
Python Basics Overview
The core Python basics every beginner should know:
- Variables and basic types
- Operators and expressions
- Strings and common methods
- Lists, tuples, and dictionaries
- Basic control flow (if, for, while)
- Simple functions
Math Operators
From highest to lowest precedence:
| Operators | Operation | Example |
|---|---|---|
| ** | Exponent | 2 ** 3 = 8 |
| % | Modulus/Remainder | 22 % 8 = 6 |
| // | Integer division | 22 // 8 = 2 |
| / | Division | 22 / 8 = 2.75 |
| * | Multiplication | 3 * 3 = 9 |
| - | Subtraction | 5 - 2 = 3 |
| + | Addition | 2 + 2 = 4 |
Examples of expressions:
# Multiplication has higher precedence than addition
# So this evaluates as: 2 + (3 * 6) = 2 + 18 = 20
2 + 3 * 6
20
# Parentheses override operator precedence
# This evaluates as: 5 * 6 = 30
(2 + 3) * 6
30
2 ** 8
256
23 // 7
3
23 % 7
2
(5 - 1) * ((7 + 1) / (3 - 1))
16.0
Sign in to answer this quiz and track your learning progress
4 + 2 * 3
Augmented Assignment Operators
| Operator | Equivalent |
|---|---|
var += 1 | var = var + 1 |
var -= 1 | var = var - 1 |
var *= 1 | var = var * 1 |
var /= 1 | var = var / 1 |
var //= 1 | var = var // 1 |
var %= 1 | var = var % 1 |
var **= 1 | var = var ** 1 |
Examples:
# Augmented assignment: equivalent to greeting = greeting + ' world!'
greeting = 'Hello'
greeting += ' world!'
greeting
'Hello world!'
# Increment a number by 1
number = 1
number += 1
number
2
# Replicate list elements: equivalent to my_list = my_list * 3
my_list = ['item']
my_list *= 3
my_list
['item', 'item', 'item']
Sign in to answer this quiz and track your learning progress
x after executing this code?x = 5
x += 3
Walrus Operator
The Walrus Operator allows assignment of variables within an expression while returning the value of the variable
Example:
# Walrus operator assigns and returns value in one expression
# my_var is assigned "Hello World!" and then printed
print(my_var:="Hello World!")
Hello World!
my_var="Yes"
print(my_var)
Yes
print(my_var:="Hello")
Hello
The Walrus Operator, or Assignment Expression Operator was firstly introduced in 2018 via PEP 572, and then officially released with Python 3.8 in October 2019.
Syntax Semantics & Examples
The PEP 572 provides the syntax, semantics and examples for the Walrus Operator.
Data Types
Understanding data types is one of the most important Python basics. Python has nine core built-in data types that cover almost everything you’ll need:
| Data Type | Examples | Description |
|---|---|---|
| Numbers | ||
int | -2, -1, 0, 1, 2, 3, 4, 5 | Whole numbers (integers) |
float | -1.25, -1.0, -0.5, 0.0, 0.5, 1.0, 1.25 | Numbers with decimal points |
complex | 2+3j, complex(1, 4) | Numbers with real and imaginary parts |
| Text | ||
str | 'a', 'Hello!', "Python" | Text and characters |
| Boolean | ||
bool | True, False | True or False values |
| None | ||
NoneType | None | Represents “no value” or “nothing” |
| Collections | ||
list | [1, 2, 3], ['a', 'b', 'c'] | Ordered, changeable collections |
dict | {'name': 'Alice', 'age': 30} | Key-value pairs |
tuple | (1, 2, 3), ('a', 'b') | Ordered, unchangeable collections |
set | {1, 2, 3}, {'a', 'b', 'c'} | Unordered collections of unique items |
Quick Examples
# Numbers
age = 25 # int
price = 19.99 # float
coordinate = 2 + 3j # complex
# Text
name = "Alice" # str
# Boolean
is_student = True # bool
# None
result = None # NoneType
# Collections
scores = [85, 92, 78] # list
person = {'name': 'Bob', 'age': 30} # dict
coordinates = (10, 20) # tuple
unique_ids = {1, 2, 3} # set
For a comprehensive guide with visual examples and detailed explanations of when to use each type, see: Python Data Types: A Visual Guide for Beginners.
Concatenation and Replication
String concatenation:
# String concatenation: adjacent strings are automatically joined
'Alice' 'Bob'
'AliceBob'
String replication:
# String replication: repeat string multiple times
'Alice' * 5
'AliceAliceAliceAliceAlice'
Variables
Variables are a fundamental part of Python basics. You can name a variable anything as long as it obeys the following rules:
- It can be only one word.
# bad
my variable = 'Hello'
# good
var = 'Hello'
- It can use only letters, numbers, and the underscore (
_) character.
# bad
%$@variable = 'Hello'
# good
my_var = 'Hello'
# good
my_var_2 = 'Hello'
- It can’t begin with a number.
# this wont work
23_var = 'hello'
- Variable name starting with an underscore (
_) are considered as “unuseful”.
# _spam should not be used again in the code
_spam = 'Hello'
Sign in to answer this quiz and track your learning progress
3valueuser-nameuser_nameforComments
Inline comment:
# This is a comment
Multiline comment:
# This is a
# multiline comment
Code with a comment:
a = 1 # initialization
Please note the two spaces in front of the comment.
Function docstring:
def foo():
"""
This is a function docstring
You can also use:
''' Function Docstring '''
"""
The print() Function
The print() function is one of the first Python basics you’ll learn. It writes the value of the argument(s) it is given. […] it handles multiple arguments, floating point-quantities, and strings. Strings are printed without quotes, and a space is inserted between items, so you can format things nicely:
print('Hello world!')
Hello world!
a = 1
print('Hello world!', a)
Hello world! 1
The end keyword
The keyword argument end can be used to avoid the newline after the output, or end the output with a different string:
# Use end parameter to change what comes after each print statement
phrase = ['printed', 'with', 'a', 'dash', 'in', 'between']
for word in phrase:
print(word, end='-') # Use '-' instead of newline
printed-with-a-dash-in-between-
The sep keyword
The keyword sep specify how to separate the objects, if there is more than one:
# Use sep parameter to specify separator between multiple arguments
print('cats', 'dogs', 'mice', sep=',') # Comma-separated output
cats,dogs,mice
The input() Function
This function takes the input from the user and converts it into a string:
# input() reads user input and returns it as a string
print('What is your name?') # ask for their name
my_name = input() # Wait for user to type and press Enter
print('Hi, {}'.format(my_name))
What is your name?
Martha
Hi, Martha
input() can also set a default message without using print():
my_name = input('What is your name? ') # default message
print('Hi, {}'.format(my_name))
What is your name? Martha
Hi, Martha
It is also possible to use formatted strings to avoid using .format:
# input() can display a prompt message directly
my_name = input('What is your name? ') # Prompt and read in one call
print(f'Hi, {my_name}') # f-string for string formatting
What is your name? Martha
Hi, Martha
Sign in to answer this quiz and track your learning progress
The len() Function
Evaluates to the integer value of the number of characters in a string, list, dictionary, etc.:
# len() returns the number of characters in a string
len('hello') # Returns 5
5
# len() returns the number of items in a list
len(['cat', 3, 'dog']) # Returns 3 (three items)
3
Test of emptiness
Test of emptiness of strings, lists, dictionaries, etc., should not use len, but prefer direct boolean evaluation.
Test of emptiness example:
a = [1, 2, 3]
# bad: unnecessary len() check
if len(a) > 0: # evaluates to True
print("the list is not empty!")
the list is not empty!
# good: direct boolean evaluation (Pythonic way)
if a: # evaluates to True if list is not empty
print("the list is not empty!")
the list is not empty!
The str(), int(), and float() Functions
These functions allow you to change the type of variable. For example, you can transform from an integer or float to a string:
# Convert integer to string
str(29) # Returns '29'
'29'
str(-3.14)
'-3.14'
Or from a string to an integer or float:
# Convert string to integer
int('11') # Returns 11
11
# Convert string to float
float('3.14') # Returns 3.14
3.14
Sign in to answer this quiz and track your learning progress
result = int('42')
type(result)
strfloatintNoneType