Python

Download Markdown

Basics

Console I/O

print("Hello World!")
input("What is your name?")

Comments

# This is a single line comment
''' This is a
multiline comment '''

Variables

a = 0
Types
a_number = 21
a_float = 1.23

a_string = "Ben"

a_bool = True or False
Type Conversions:

Operators

Operation Syntax
addition 1 + 2
subtraction 1 - 2
multiplication 1 * 2
division 1 / 2
modulus 1 % 2
increment a = a + 1
decrement a = a - 1

Comparison

Operation Syntax
equal a == b # or is or bools
not equal a != b # or is not for bools
greater than a > b
less than a < b
greater than or equal to a >= b
less than or equal to a <= b

Logical

Operation Syntax
and a and b
or a or b
not not a

Conditionals

if name == "Joe":
  # ...
elif name == "Bob":
  # ...
else: 
  # ...

print("if part") if name == "Joe" else print("else part")

# only available in python 3.10 and later
match name:
  case "Joe":
    break
  case "Bob"
    break
  case _:
    break

Loops:

for i in range(100):
  # ...

for val in ["a", "b", "c"]:
  # ...

while condition is True:
  # ...

not available

Functions

def some_function(a):
  return a + 100

lambda a, b : a + b

Classes

class AClass:
  a_public_field = "hi everyone!"
  _a_private_field = "shh! secret"
  _some_prop = None # private property for getters and setters
  
  # constructor
  def __init__(self, param):
    self.a_public_field = param
  
  def random_method(self):
    # ...
  
  @property
  def some_prop(self):
    return self._some_prop
  
  @some_prop.setter
  def some_prop(self, value):
    self._some_prop = value
  
  @some_prop.deleter
  def some_prop(self):
    del self._someprop
  
  @staticmethod
  def some_static_method():
    pritn("Hello from static method!")
  

class AChild extends AClass:
  # constructor
  def __init__(self, other_param):
    super().__init__(other_param)
  
  # overridden method
  def random_method(self):
    # ...

my_class = AClass("foo")

Advanced

Arrays/Lists

my_arr = ['a', 'b', 'c']

my_dict = {'key1': 1, 'key2': 2, 'key3': 3}
Function Syntax
search my_arr.index(val) val in my_arr
push, pop my_arr.append(val) my_arr.pop()
insert my_arr.insert(start, items)
concatenate arr_one + arr_two
subarray my_arr[start : end : step]
sort my_arr.sort(reverse=True|False, key=my_func) # key function takes value and returns a key for what position it has relative to others. Higher is later.
loop for key, value in enumerate(my_arr): # ...
map map(func, my_arr)

Strings

Function Syntax
search sub_str in my_str
insert my_str[:index] + sub_str + my_str[index:]
replace my_str.replace(oldvalue, newvalue, count)
concatenate 'a string' 'another string'
substring my_str[start : end : step]

Math

math.pi # = 3.14159265...

math.e # = 2.71828182...
Function Syntax
square root math.sqrt(a)
exponentiation math.pow(a, b)
random number random.random() # between 0 and 1 random.randint(a, b) # a <= random_number <= b
absolute value abs(a)
round round(number[, ndigits])
ceiling math.ceil(a)
floor math.floor(a)
max max(arg1, arg2, *args) max(iterable)
min min(arg1, arg2, *args) min(iterable)
sine math.sin(a)
cosine math.cos(a)
tangent math.tan(a)
arcsine math.asin(a)
arccosine math.acos(a)
arctangent math.atan(a)

Dates

from datetime import date, time
current_date= date.today() # has properties year, month, day
a_date = date(2022, 5, 16)
a_time = time(11, 29, 30) # 11:29am and 30 seconds. has properties hour, minute, second, and microsecond

# dates and times can be combined in datetime.today()

#string formatting
now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")
# '12-02-03. 02 Dec 2003 is a Tuesday on the 02 day of December.'

# arithmetic works
birthday = date(2000, 1, 27)
age = now - birthday

Files

# open, write, close
f = open("file.txt", 'w') #r = read, w = write, x = create
f.write("This is the entire file.")
f.close()

# alternative method:
with open("file.txt", 'w') as f:
    f.write("This is the \nentire file.")

# read
with open("file.txt", 'r') as f:
    print(f.read()) # read entire file
    f.seek(0) # go to first byte
    for line in f: # read line by line
        print(line, end="")

new_file = open("new_file.txt", 'x') #create
new_file.close()
import os
os.remove("new_file.txt") # delete

Bitwise Operations

Operation Syntax
AND a & b
OR a | b
XOR a ^ b
NOT ~ a
Left Shift a << b
Right Shift a >> b
Zero fill right shift not available

Errors

try:
  pass
except SomeException as err:
  pass
else: 
  pass # happens if an exception is not raised
finally:
  pass

raise Exception("Error message")

Extra