Code snippets in Python.
** 2**3=8
% 22%8=6
// 22//8=2
/ 22/8=2.75
* 3*3=9
- 5-2=3
+ 2+2=4
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
2 + 3 * 6 # 20
(2 + 3) * 6 # 30
2 ** 8 # 256
23 // 7 # 3
23 % 7 # 2
(5 - 1) * ((7 + 1) / (3 - 1)) # 16.0
example = 'hello'
example += 'world'
example
# hello world
number = 1
number += 1
number
# 2
exampleList = ['example']
exampleList *= 4
exampleList
# ['example', 'example', 'example', 'example']
'strOne' 'strTwo' #strOnestrTwo
'strOne' * 2 # strOnestrOne
Lists store items in a particular order.
new_fruit = [] #initialise empty array
fruit = ['apple', 'pear', 'orange', 'lemon']
fruit_one = fruit[0] # 'apple'
fruit_last = fruit[-1] # 'lemon'
fruit[0] = 'lime' # 'apple' is now 'lime'
fruit.append('apple') # add 'apple' to end of list
fruit.insert(2, "plum") # add 'plum' at position two
del fruits[0] # delete an element by position
fruit.remove("lemon") # delete an element by value
fruit_pop_last = fruit.pop() # pop last element from list
fruit_pop_first = fruit.pop(0) # pop first element from list
no_fruits = len(fruit) # length of list
fruit.sort() # sort list
fruit.sort(reverse=True) # revse list in alphabetical order
fruit.reverse() # reverse order of list
def greet_user():
""Display a simple greeting.""
print("Hello")
greet_user()
def greet_user(user):
""Display a simple greeting.""
print("Hello, " + user + "!")
greet_user('userOne')
def greet_user(name, age=None):
""Display information about user.""
print("Hello, " + user + " you are " + age + " years old!")
greet_user('userOne', 10)
greet_user('userTwo')
def get_full_name(first, last):
""Return a neatly formatted full name.""
full_name = first + '' + last
return full_name_title()
musician = get_full_name('Jimi", "Hendrix")
print(musician)
# returning a dictionary
def build_person(first, last):
""Return a dictionary of information about a person.""
person = {'first': first, 'last': last}
return person
musician = build_person("Jimi", "Hendrix")
print(musician)
# returning a dictionary with optional values
def build_person(first, last, age=None):
""Return a dictionary of information about a person.""
person = {'first': first, 'last': last}
if age:
person['age'] = age
return person
musician = build_person("Jimi", "Hendrix", 27)
print(musician)
musician = build_person("Janis", "Joplin")
print(musician)
# passing a list to a function
def greet_users(names):
""Print a simple greeting to everyone.""
for name in names:
msg = "Hello, " + name + "!"
print(msg)
usernames = ['userOne', 'userTwo']
greet_users(usernames)
# passing an arbitrary number of arguments
def make_pizza(size, *toppings):
""Make a pizza.""
print("\nMaking a " + size + " pizza.")
print("Toppings:")
for topping in toppings:
print("- " + topping)
make_pizza('small', 'cheese')
make_pizza('medium', 'mushrooms', 'peppers')
# modules
def make_pizza(size, *toppings):
""Make a pizza.""
print("\nMaking a " + size + " pizza.")
print("Toppings:")
for topping in toppings:
print("- " + topping)
import pizza
pizza.make_pizza('medium', 'mushrooms')
from pizza import make_pizza
make_pizza('medium', 'mushrooms')
import pizza as p
p.make_pizza('medium', 'mushrooms')
from pizza import make_pizza as mp
mp('medium', 'mushrooms')
from pizza import *
make_pizza('medium', 'mushrooms')
class Car():
""A simple attempt to model a car.""
def __init__(self, make, model, year):
""Initialise car attributes.""
self.make = make
self.model = model
self.year = year
self.fuel_capacity = 15
self.fueld_level = 0
def fill_tank(self):
""Fill gas tank to capacity.""
self.fuel_level = self.fuel_capacity
print("Fuel tank is full.")
def drive(self):
""Simulate driving""
print("The car is moving")
my_car = Car('audi', 'a4', 2016)
print(my_car.make)
print(my_car.model)
print(my_car.year)
my_car.fill_tank()
my_car.drive()
my_car = Car('audi', 'a4', 2016)
my_old_car = Car('subaru', 'outback', 2013)
my_truck = Car('toyota', 'tocoma', 2010)
my_new_car = Car('audi', 'a4', 2016)
my_new_car.fuel_level = 5
def update_fueld_level(self, new_level):
""Update the fuel level.""
if new_level <= self.fuel_capacity:
self.fuel_level = new_level
else:
print("The tank can't hold that much.")
def add_fuel(self, amount):
""Add fuel to the tank.""
if(self.fuel_level + amount <= self.fuel_capacity):
self.fueld_level += amount
print("Added fuel.")
else:
print("The tank won't hold that much.")
# inheritance
class ElectricCar(Car):
""A simple model of an electric car.""
def __init__(self, make, model, year):
""Initalise an electric car.""
super().__init__(make, model, year)
self.battery_size = 70
self.charge_battery = 0
# adding new methods to the child class
classElectricCar(Car):
--snip--
def charge(self):
""Fully charge the vehicle.""
self.charge_level = 100
print("The vehicle is fully charged.")
# using child and parent methods
my_ecar = EletricCar('tesla', 'mode s'. 2016)
my_ecar.charge()
my_ecar.drive()
# overring parent methods
class EletricCar(Car):
--snip--
def fill_tank(self):
""Display an error message.""
print("This car has no fuel tank.")
# instance as attributes
class Battery():
""A battery for an eletric car.""
def __init__(self, size=70):
""Initalise battery attributes.""
self.size = size
self.charge_level = 0
def get_range(self):
""Return the battery's range.""
if self.size == 70:
return 240
elseif self.size == 85:
return 270
# using an instance as an attribute
class EletricCar(Car):
--snip--
def __init(self, make, model, year):
""Initialise an electric car.""
super().__init__(make, model, year)
self.battery = Battery()
def charge(self):
""Fully charge the vehicle.""
self.battery.charge_level = 100
print("The vehicle is fully charged.")
my_ecar = EletricCar('tesla', 'model x', 2016)
my_ecard.charge()
print(my_ecar.battery.get_range())
my_ecar.drive()
# storing classes in a file (car.py)
""Represent gas and eletric cars.""
class Car():
""A simple attempt to model a car.""
--snip--
class Battery():
""A battery for an eletric car.""
--snip--
class EletricCar(Car):
""A simple model of an eletric car.""
--snip--
# importing individual classes from a module(my_cars.py)
from car import Car, EletricCar
my_beetle = Car('volkswagen', 'beetle', 2016)
my_beetle.fill_tank()
my_beetle.drive()
my_tesla = car.EletricCar('tesla', 'model s', 2016)
my_tesla.charge()
my_tesla.drive()
# importing an entire module
import car
my_beetle = car.Car('volkswagen', 'beetle', 2016)
my_beetle.fill_tank()
my_beetle.drive()
my_tesla = car.EletricCar('tesla', 'model s', 2016)
my_tesla.charge()
my_tesla.drive()
# importing all classes from a module
from car import *
my_beetle = Car('volkswagen', 'beetle', 2016)
# classes should inherit from object
class ClassName(object):
# other examples
class ChildclassName(Parentclass):
def __init__(self):
super(Classname, self).__init__()
class EletricCar(Car):
def __init__(self, make, model, year):
super(EletricCar, self).__init__(make, model, year)
Python dictionaries allow you to connect pieces of information. This information is stored as key-value pair. When you provide a key, Python returns the value associated with that key.
example_dict = {'colour': 'yellow', 'num': 10}
example_dict_colour = example_dict.get('colour') # 'yellow'
example_dict_num = example_dict.get('num', 0) # 10
example_dict['color'] = 'red' # modifying values
example_dict['num'] = 50
# storing key-value pairs
example_dict['x'] = 0
example_dict['y'] = 25
example_dict['another_example'] = 1.5
new_dict = {} # empty dictionary
new_dict['colour'] = 'green'
new_dict['num'] = 100
fav_colour = {
'red': 10,
'blue': 15,
'green': 20
}
for colour, num in fav_colour.items():
print(colour+ ": " + num)
# red: 10
# blue: 15
# green: 20
for colour in fav_colour.keys():
print(colour)
# red
# blue
# green
for num in fav_colour.values():
print(num)
# 10
# 20
# 30
fav_colour_len = len(fav_colour)
user_info = {
'userOne': ['female', 10],
'userTwo': ['male', 5],
'userThree': ['female', 6],
'userFour': ['male', 7]
}
for user, details in user_info.items():
print(user + ": )
for detail in details:
print("- " + detail)
# preserve order in which keys and values are ordered (via OrderedDict())
user_info = OrderedDict()
user_info['userOne'] = [2, 4]
user_info['userTwo'] = [6, 8]
user_info['userThree'] = [10, 12]
user_info['userFour'] = [14, 16]
for user, details in user_info.items():
print(user + ":")
for detail in details:
print("- " + detail)
age = 10
age == 10 # true
age == 200 # false
name = "Test"
name.lower() == "test" # true
age = 100
if age >= 100:
print("You are older than 100 years old!")
else:
print("You are less than 100 years old!")
users = ['one', 'two', 'three', 'four']
'one' in users # true
'five' in users # false
banned_users = ['one', 'two', 'three']
user = 'who'
if user not in banned_users:
print("You can play!")
pets = ['dog', 'cat', 'dog', 'fish', 'cat', 'rabbit', 'cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
# reading from an entire file
filename = 'example.txt'
with open(filename) as f_obj:
contents = f_obj.read()
print(contents)
# reading line by line
filename = 'example.txt'
with open(filename) as f_obj:
for line in f_obj:
print(line.rstrip())
# storing lines as a list
filename = 'example.txt'
with open(filename) as f_obj:
lines = f.obj.readlines()
for line in lines:
print(line.rstrip())
# writing an empty file
filename = 'example.txt'
with open(filename, 'w') as f:
f.write("Example text")
# writing multiple lines to an empty file
filename = 'example.txt'
with open(filename, 'w') as f:
f.write("Here is some text!\n")
f.write("Here is another line of text.\n")
# appending to a file
filename = "example.txt"
with open(filename, 'a') as f:
f.write("There's more...\n")
f.write("See, I told you. \n")
# opening a file from a subfolder
f_path = 'text_files/example.txt'
with open(f_path) as f_obj:
lines = f_obj.readlines()
for line in lines:
print(line.rstrip())
# opening a file using an absolute path
f_path = 'home/user/text_files/example.txt'
with open(f_path) as f_obj:
lines = f_obj.readlines()
# store data with json
""Store some numbers.""
import json
numbers = [1, 2, 3, 4, 5]
filename = 'numbers.json'
with open(filename, 'w') as f_obj:
json.dump(numbers, f_obj)
# read json file
""Load previously stored numbers""
import json
filename = 'numbers.json'
with open(filename) as f_obj:
numbers = json.load(f_obj)
print(numbers )