Defining variables

In [1]:
My_Name = 'Netshock'    #String Variable
My_Age = 25             #Integer Variable
Likes_Pie = True        #Boolean Variable
In [2]:
#We can check if something is an integer - in this case, it's not:
isinstance(My_Name, int)
Out[2]:
False
In [3]:
#Let's say we have a variable like below. It's stored as a string, but should be an int. We can cast to int:
My_Number = '22'
My_Number_Int = int(My_Number)

print(My_Number)
print(My_Number_Int)
22
22
In [4]:
#above we can see the variable is seemingly unchanged. Let's check the types
type(My_Number_Int)
Out[4]:
int
In [5]:
type(My_Number)
Out[5]:
str

Mathematical functions

In [6]:
number1 = 10
number2 = 20
In [11]:
#add
add = number1 + number2
print('Add:' + str(add))

#subtract
subtract = number1 - number2
print('Subtract:' + str(subtract))

#divide
divide = number1 / number2
print('Divide:' + str(divide))

#multiply
multiply = number1 * number2
print('Multiply:' + str(multiply))
Add:30
Subtract:-10
Divide:0.5
Multiply:200
In [12]:
#We could also use powers; 2 to the power of 2 is 4
2**2 
Out[12]:
4

String functions

In [13]:
#Apostrophies can cause us issues. If I'm writing a string with an apostrophie in it, Python may think it's the end of the string, so we use escape characters
print('There\'s no need to worry about apostrophies')
There's no need to worry about apostrophies
In [14]:
#Imagine I want to know, for some reason, what the 4th letter of a word was? The index starts at zero, so letter 4 is index 3
word = 'netshock'
word[3]
Out[14]:
's'
In [15]:
#finding the length of a string is easy:
len(word)
Out[15]:
8
In [17]:
#chaning string cases to be all upper or lower case:
print(word.upper())
print(word.lower())
NETSHOCK
netshock
In [19]:
#String concatenation is nice and easy too
name = 'Netshock'
country = 'England'

print('Your name is %s, your country is %s' %(name, country))
Your name is Netshock, your country is England
In [21]:
#we can do the same like this:
print('Your name is ' + name + ', your country is ' + country)
Your name is Netshock, your country is England

Working with lists

In [24]:
'''
Lists are a comma separated list of values stored within a variable. Lists are mutable, which means, we can modify, add or remove items at any time. We use lists when we need an ordered set of items to iterate over – where the items need to be modifiable.
'''#create a list
location = ["surrey", "london", "berkshire"]

#create a list from the list
counties = location

#append something to that list
location.append("liverpool")

#add something to the beginning of the list
location.insert(0, "Manchester")

#print a list
print(counties)
['Manchester', 'surrey', 'london', 'berkshire', 'liverpool']
In [25]:
#remove item 3 from the list
location.pop(3)
print(counties)
['Manchester', 'surrey', 'london', 'liverpool']
In [26]:
#or another way to remove, if we don't know the location of the item within the list
location.remove("london")
print(counties)
['Manchester', 'surrey', 'liverpool']
In [68]:
newlist = [2001,1090,2004,2006,2009,2002,2010,2014,2019]
for x in newlist:
    print (x ** 3)
8012006001
1295029000
8048096064
8072216216
8108486729
8024024008
8120601000
8169178744
8230172859
In [70]:
#we can also create a list, from a list, using calculations
now_minus_then = [ 2019 - x for x in newlist ]
then_plus_two = [ x+2 for x in newlist ]
then_modulo_two = [ x%2 for x in newlist ]
print(now_minus_then)
print(then_plus_two)
print(then_modulo_two)
[18, 929, 15, 13, 10, 17, 9, 5, 0]
[2003, 1092, 2006, 2008, 2011, 2004, 2012, 2016, 2021]
[1, 0, 0, 0, 1, 0, 0, 0, 1]

Sets

In [27]:
'''
A set is not ordered & hence you cannot select an item from a particular index. 
We define a set as below, using curly brackets. Note that we use the add, rather than the append function to add an item to the set


Do I need a set or a list?
---------------------------
I need an ordered sequence of objects – you need a list
I need to lookup to see if a value exists in a sequence of objects. However, I do not need the sequence to be ordered and I don’t need to store duplicate values – you need a set

'''
location = {"surrey", "london", "berkshire"}
location.add("liverpool")
print(location)
{'liverpool', 'berkshire', 'surrey', 'london'}

Tuples

In [32]:
'''
Tuples are very similar to lists. They’re a comma separated list of values stored within a variable. Tuples are immutable, which means, once created they cannot be edited (nothing can be added or removed), but, we can search for elements within a tuple.

So, when do we use a tuple over a list?

Tuples are more efficient (faster) than a list. If we have a constant set of values that we need to iterate through, we should use a tuple, rather than a list. If those values are not static, then we need to use a list.
If the data does not need to be changed, then we should write protect it by using a tuple, to protect our applications from problems arising from an incorrectly altered list.
'''

tuplez = (1,2,3,4,5)
print(tuplez)
(1, 2, 3, 4, 5)
In [33]:
#access an item within a tuple
print(tuple[4])
5
In [36]:
#We can create a list within a tuple. The list within is mutable while the tuple is not
newtuple = ("kieran", [1,2,3], "London")
newtuple[1].append(4)
print(newtuple)
('kieran', [1, 2, 3, 4], 'London')
In [38]:
#tuple concatenation
longtuple = newtuple + tuplez
print(longtuple)
('kieran', [1, 2, 3, 4], 'London', 1, 2, 3, 4, 5)
In [41]:
#We can also multiply tuples
multiplytuple = tuplez * 10
print(multiplytuple)
(1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5)
In [42]:
#count number of times a number / letter appears
multiplytuple.count(1)
Out[42]:
10

Dictionaries

In [43]:
'''
A dictionary is a key value store in Python. An example usecase for this could be an address book. Where the key is the customer name & the value is their phone number. We could therefore look up against thousands of customers names to retrieve their contact details.
'''
dictionary = {
    'Domain': 'netshock.co.uk',
    'server': 'nginx',
    'list': [location]
}
In [44]:
print(dictionary)
{'Domain': 'netshock.co.uk', 'server': 'nginx', 'list': [{'liverpool', 'berkshire', 'surrey', 'london'}]}
In [48]:
domain = dictionary["Domain"]
print(domain)
netshock.co.uk
In [49]:
for x in dictionary:
    print(x)
Domain
server
list
In [50]:
for x in dictionary:
    print(dictionary[x])
netshock.co.uk
nginx
[{'liverpool', 'berkshire', 'surrey', 'london'}]
In [52]:
for x, y in dictionary.items():
    print(x,y)
Domain netshock.co.uk
server nginx
list [{'liverpool', 'berkshire', 'surrey', 'london'}]
In [53]:
#check if a key exists
if 'Domain' in dictionary:
    print('yes')
yes

Functions

In [54]:
'''
Using functions enables you to re-use code, without typing the same thing in several places. It gives you one function, which can be called in a variety of scenarios. The below, shows an example of a function, which prints the name provided by the user.
'''
def error(var1, var2):
    return(var1 - var2) ** 2

#call the function
error (1, 2)
Out[54]:
1

if statements

In [58]:
name = 'netshock'

if name == 'netshock':
    print('It\'s Netshock')
elif name == 'bob':
     print('hello bob')
else:
     print('unknown')
    
It's Netshock

For loops

In [59]:
cities = ["london", "Manchester", "Bristol"]
for x in cities:
    print(x)
london
Manchester
Bristol
In [60]:
home = 'london'

for x in home:
    print(x)
l
o
n
d
o
n
In [65]:
for x in home:
    print(x)
    if x == "n":
        break
        
l
o
n

While Loops

In [67]:
age = 1
while age < 10:
    print("child" + str(age))
    age +=1
child1
child2
child3
child4
child5
child6
child7
child8
child9
In [ ]: