Virtual Env
Create Venv
python -m venv myVenv/Create Venv.
Windows
myVenv/scripts/activateActivate Venv.
deactivateDeactivate Venv.
Linux
source myVenv/bin/activateActivate Venv.
deactivateDeactivate Venv.
Data Types
Tuples
Tuples are like lists, but can’t be changed (immutable).
# Declare an empty typle
empty_tuple = ()
# Declare a tuple
players = "player1", "player2"
Note: A tuple is not defined by parenthesis, it is defined by commas (except for declaring an empty tuple).
String Manipulation
Input / Output
input("Message")Keyboard input.
print("Message")Write a message to the output.
print("Message {}".format(myVar))Replace
{}
withmyVar
.print("Message", myVar)Variable concatenation.
print(f "Message {myVar}")Replace
{myVar}
withmyVar
.
print(r "c:\path\name")Do not interpret special characters (e.g.
\
',\n
).
print("Message" + myString)String concatenation.
print("Message".join(myString))String concatenation.
Strip & Split
split(",")Split a string based on a delimiter.
myString.strip([chars])Remove all "chars" at the beginning and the end of the string.
myString.rstrip([chars])Remove all "chars" at the end of the string.
Encoding
ord('A')Convert character to Decimal ASCII code.
chr(65)Convert Decimal ASCII code to character.
"\x41"Convert Hexadecimal ASCII code to character.
bytes("myString", "UTF-8")Convert a string into an array of bytes.
Misc
str(intVar)Convert int variable to string.
len(myVar)Count the number of characters in the variable.
myString.title()Convert to title (e.g. This Is A Title).
myString.upper()Convert to uppercase.
myString.lower()Convert to lowercase.
Files
Read File
with open("myFile.txt", "r") as file:
# Get entire file content
file_data = file.read()
# Get all lines at once
lines = file.read().splitlines()
# Get lines one by one
line1 = file.readline()
line2 = file.readline()
This syntax handles automatically closing the file if anything goes wrong inside the with
block.
Write File
with open('myFile.txt', 'w', encoding="utf-8") as file:
file.write('This is a line\n')
This syntax handles automatically closing the file if anything goes wrong inside the with
block.
Read File (Old Way)
from typing import TextIO
file: textIO = open('myFile.txt')
try:
content: str = file.read()
print(content)
finally:
file.close()
OOP
Main
This condition will be evaluated to True
if this file is the one that was run. This is not the case is the file is imported thus the condition is will be evaluated to False
.
if __name__ == '__main__':
print("Hello")
Class
class Player:
# Constructor
def __init__(self, name:str) -> None:
self.name: str = name
self.health: int = 100
self.max_health: int = 100
# Method
def increase_max_health(self) -> None:
self.max_health += 10
# Init new instance of the class (a new object)
myPlayer: Player = Player(name: 'myPlayerName')
# Use a method
myPlayer.increase_max_health()
# Access an attribute
print(myPlayer.max_health) # Will print 110
Class Attributes vs Instance Attributes
class Player:
# Class Attribute
max_mana: int = 100
# Constructor
def __init__(self) -> None:
# Instance Attribute
self.health: int = 100
myPlayer1: Player = Player()
myPlayer2: Player = Player()
# Implicitly create an Instance Attribute
myPlayer1.max_mana = 200
print(myPlayer1.max_mana) # Will print 200
print(myPlayer2.max_mana) # Will print 100
# Change the Class Attribute value
Player.max_mana = 300
print(myPlayer1.max_mana) # Will print 300
print(myPlayer2.max_mana) # Will print 300
@staticmethod
Adding the @staticmethod
annotation allows creating a method that don't require anything from the object (self
). This method could be defined outside the class but if its only relevant to this class, it can be nice to keep the code inside this class.
class Player:
# Constructor
def __init__(self) -> None:
self.health: int = 100
self.max_health: int = 100
# Non static method
def increase_max_health(self) -> None:
self.max_health += 10
# Static method
@staticmethod
def say_hello() -> None:
print("Hello")
Also, @staticmethod
allows calling the method even if no object were instantiated.
Player.say_hello()
Dunder Methods
class Player:
# Constructor
def __init__(self) -> None:
self.health: int = 100
self.max_health: int = 100
# Dunder Methods
__add__(self, other):
...
__mul__(self, other):
...
# __str__ should return something user friendly
# If __str__ is not defined is will fallback to __repr__
__str__(self) -> str:
...
# __repr__ should return something usefull for developpers
# Default is memory address
__repr__(self) -> str:
...
myPlayer1: Player = Player()
myPlayer2: Player = Player()
print(myPlayer1 + myPlayer2) # Will use dunder method __add__
print(myPlayer1 * myPlayer2) # Will use dunder method __mul__
print(myPlayer1) # Will use dunder method __str__
print(repr(myPlayer1)) # Will use dunder method __str__