This post is a quick summary of the Python language. This is for version 3 and above.
.py
or in the interactive shell.python my-script.py
in the terminal.print
function to print to the console.print
function can also take args. example print("You owe", total)
. This results in You owe 100
. It adds space automaticallysep
arg. example print("You owe $", total, sep='')
. This results in You owe $100
end
arg. example print("You owe $", total, end='')
. This results in You owe $100
without a newline.input
to get user input. example name = input("Enter your name: \n")
print(f"Hello {name}")
:,.2f
in the f string. example print(f"Hello {name}, your total is ${total:,.2f}")
. This will make it look like a currency.x = 1
will make x
an integer.x = 10.50
int
function. x = int(10.50)
float
function to convert to float. example x = float(10)
x = "Hello World"
in
keyword. for example: if "e" in "Hello":
would evaluate to true
x = "Don't"
. Using single quote with apostrophe will cause an error.+
to concatenate strings. example x = "Hello" + "World"
. Use space between as necessary.*
to repeat a string. example x = "Hello" * 3
//
to perform a whole integer division. example x = 10 // 3
would yield 3
. Whereas x = 10 / 3
would yield 3.33
%
for the remainder of a division. example x = 10 % 3
would yield 1
if condition1 or condition2: # can also use `and`
print("do something")
elif:
print("do something else")
else:
print("cant do something")
not
operator to negate a condition. example if not condition:
append
method to add to the listlist.remote(item)
or del list[index]
in
to check if an item is in the list. example if item in list:
for in
loop. example for item in list:
sum
function to add all elements of a list.range
function to generate a list. for example range(0, 10, 2)
would result in [0, 2, 4, 6, 8]
, where 10 is the stop value and 2 is the step/increment value.del
keyword to delete a key/value pair. example del dict[key]
get
method on dictionary for safe lookup. example dict.get(key, default_value)
get
method can be chained to get nested values. example dict.get(key1).get(key2)
None
is returned, this is equivalent to null
in JavaScript and evaluates to false
in a conditional statement.items
method on a dictionary to extract both key and value. example for key, value in dict.items():
python -m venv my_venv
source my_venv/bin/activate
deactivate
def
keyworddef greet(name):
print("Hello", name)
return
keywordclass
keyword, followed by name and colon. ex: class MyClass:
__init__
method is the constructor. ex: def __init__(self, name, age):
self
is always the first param of the init method. It refers to the current instance of the class. somewhat equivalent to this
in JavaScript.class MyClass(ParentClass):
super()
function to call parent classes methods. example: super().__init__(name, age)
new
keyword is not required to instantiate a class object. for ex: my_obj = MyClass()
is sufficient.import
keyword. example: import my_module
__init__.py
fileimport
keyword. example: import my_package
try
, catch
and finally
blocks to handle exceptionstry:
# do something
except:
# handle exception
finally:
# do something
raise
keyword. ex: - raise Exception("Invalid value")
as
keyword. ex: except FileNotFoundError as e:
open
function to open a file. example: file = open("file.txt")
close
method to close the file. example: file.close()
with
keyword to open a file. example: with open("file.txt") as file:
This will ensure the file is closed automatically.read
method can be used to read the contents of the file. example: file.read()
readlines
method can be used to read the contents of the file as a list. example: file.readlines()
This will return a list of lines in the file that can be looped over using the for-in loop.for line in file:
w
. example: file = open("file.txt", "w")
. This will overwrite the contents of the file, so be careful. use param 'a'
to append to the file instead.write
method on the file to write to the file. example: file.write("Hello")
os
python module provides methods to work with the operating system and file system. example: os.remove("file.txt")
will delete the file.