Getting Started

f-Strings (Python 3.6+)

>>> website = 'Quickref.ME'
>>> f"Hello, {website}"
"Hello, Quickref.ME"
>>> num = 10
>>> f'{num} + 10 = {num + 10}'
'10 + 10 = 20'

See: Python F-Strings

Plus-Equals

counter = 0
counter += 10           # => 10
counter = 0
counter = counter + 10  # => 10
message = "Part 1."
# => Part 1.Part 2.
message += "Part 2."   

Arithmetic

result = 10 + 30 # => 40
result = 40 - 10 # => 30
result = 50 * 5  # => 250
result = 16 / 4  # => 4.0 (Float Division)
result = 16 // 4 # => 4 (Integer Division)
result = 25 % 2  # => 1
result = 5 ** 3  # => 125

The / means quotient of x and y, and the // means floored quotient of x and y, also see StackOverflow

File Handling

with open("myfile.txt", "r", encoding='utf8') as file:
    for line in file:
        print(line)

See: File Handling

Functions

>>> def my\_function():
...     print("Hello from a function")
...
>>> my_function()
Hello from a function

See: Functions

Loops

for item in range(6):
    if item == 3: break
    print(item)
else:
    print("Finally finished!")

See: Loops

If Else

num = 200
if num > 0:
    print("num is greater than 0")
else:
    print("num is not greater than 0")

See: Flow control

Lists

mylist = []
mylist.append(1)
mylist.append(2)
for item in mylist:
    print(item) # prints out 1,2

See: Lists

Slicing String

>>> msg = "Hello, World!"
>>> print(msg[2:5])
llo

See: Strings

Data Types

str Text
int, float, complex Numeric
list, tuple, range Sequence
dict Mapping
set, frozenset Set
bool Boolean
bytes, bytearray, memoryview Binary
See: Data Types

Variables

age = 18      # age is of type int
name = "John" # name is now of type str
print(name)

Python can't declare a variable without assignment.

Hello World

>>> print("Hello, World!")
Hello, World!

The famous "Hello World" program in Python

Introduction

Comments