In [1]: 1 class Example(object):
2 def output(self, value):
3 if isinstance(value, str):
4 return value
5 else:
6 return "ERROR: String expected!"
7
8 my_example = Example()
9
10 print(my_example.output(5))
executed in 13ms, finished 08:23:39 2020-04-29
In [2]: 1 # The None type
2 something = None
3
4 # The Boolean type
5 is_tired = True
6
7 #The Integer type
8 age = 35
9 print(1+1*2/5)
10
11 #The Float type
12 half = 0.5
13
14 #The String type
15 message = "Hello World"
16
17 #The List type
18 numbers = [1,2,3,4]
19 mixed_list = ['Hello',1,True,None]
20 matrix = [[1,2],[3,4]]
21
22 #The Dictionary type
23 person = {
24 'name':'Ali',
25 'age':18,
26 'address':{
27 'country':'Singapore',
28 'zip': '123456'
29 }
30 }
31
32 print(type(something))
33 print(type(is_tired))
34 print(type(age))
35 print(type(half))
36 print(type(message))
37 print(type(numbers))
38 print(type(person))
executed in 17ms, finished 08:23:39 2020-04-29
In [3]: 1 something = None
2 print(something)
3 print(type(something))
executed in 8ms, finished 08:23:39 2020-04-29
In [4]: 1 print(is_tired)
executed in 6ms, finished 08:23:39 2020-04-29
In [5]: 1 age = 35
2 print(age)
executed in 6ms, finished 08:23:39 2020-04-29
In [6]: 1 print(5+5)
2 print(10-5-5)
3 print(2*2)
executed in 7ms, finished 08:23:39 2020-04-29
In [7]: 1 # Careful when you divide integers!
2 # In Python 2.7, when you divide 2 integers, the result is a whole number.
3 # In Python 3.x, the result will be a float.
4
5 print(22/10)
executed in 7ms, finished 08:23:39 2020-04-29
2.2
In [8]: 1 half = 0.5
2
3 print(half)
4 print(1/2)
5 print(1/2.0)
executed in 5ms, finished 08:23:39 2020-04-29
0.5
0.5
0.5
In [9]: 1 name = "Ali"
2 name = 'Ali'
3
4 message = 'He said:\n"Let\'s do this"'
5 print(message)
executed in 6ms, finished 08:23:39 2020-04-29
He said:
"Let's do this"
In [10]: 1 string1 = 'Hello'
2 string2 = 'World'
3
4 print(string1 + " " + string2)
executed in 4ms, finished 08:23:39 2020-04-29
Hello World
In [11]: 1 address = 'Tampines Str 21'
2 address = address.replace('Str', 'Street')
3 print(address)
executed in 7ms, finished 08:23:39 2020-04-29
Tampines Street 21
In [12]: 1 age = 35
2 message = 'I am {} years old'.format(age)
3 print(message)
executed in 6ms, finished 08:23:39 2020-04-29
I am 35 years old
In [13]: 1 empty = []
2 colours = ['blue','red']
3 print(colours)
4 print(colours[0])
executed in 5ms, finished 08:23:39 2020-04-29
['blue', 'red']
blue
In [14]: 1 # You can add items to a list
2
3 colours = ['blue','red'] #already defined above
4
5 colours.append('green')
6 print(colours)
7
8 colours.insert(0,'black')
9 print(colours)
executed in 7ms, finished 08:23:39 2020-04-29
['blue', 'red', 'green']
['black', 'blue', 'red', 'green']
In [16]: 1 colours = ('blue','red')
2 print(colours)
3
4 # This line will crash, cause an error
5 colours.append('green')
executed in 13ms, finished 08:23:54 2020-04-29
('blue', 'red')
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-16-942432b7d3ec> in <module>
3
4 # This line will crash, cause an error
----> 5 colours.append('green')
AttributeError: 'tuple' object has no attribute 'append'
In [44]: 1 person = {
2 'name':'Ali',
3 'age':18,
4 'address':{
5 'country':'Singapore',
6 'zip': '123456'
7 }
8 }
9
10 print(person)
11 print(person['name'])
12 print(person['address']['country'])
executed in 8ms, finished 08:24:10 2020-04-29
{'name': 'Ali', 'age': 18, 'address': {'country': 'Singapore', 'zip': '123456'}}
Ali
Singapore
In [45]: 1 person = {
2 'name':'Ali'
3 }
4
5 person['age'] = 35
6
7
8 print(person)
executed in 7ms, finished 08:24:10 2020-04-29
{'name': 'Ali', 'age': 35}
In [46]: 1 print(person.keys())
executed in 5ms, finished 08:24:10 2020-04-29
dict_keys(['name', 'age'])
1 Functions
In [47]: 1 def squared(value):
2 return value * value
3
4 #anything that has not been idented to the right is not part of the function.
5 results = squared(2)
6
7 print(results)
executed in 7ms, finished 08:24:10 2020-04-29
4
In [48]: 1 def concat(string1, string2):
2 return string1 + ' ' + string2
3
4 result = concat('Hello', 'World')
5
6 print(result)
executed in 7ms, finished 08:24:10 2020-04-29
Hello World
In [49]: 1 def address(name, country, city, street, postcode):
2 return '{}\n{}\n{} {}\n{}'.format(name, street, city, postcode, country)
3
4 result = address('John', 'Singapore', 'Singapore', '8 Claymore Hill', 229572)
5 print(result)
executed in 7ms, finished 08:24:10 2020-04-29
John
8 Claymore Hill
Singapore 229572
Singapore
In [50]: 1 def address(name=None,
2 country='Singapore',
3 city='Singapore',
4 street=None,
5 postcode=None):
6 return '{}\n{}\n{} {}\n{}'.format(name, street, city, postcode, country)
7
8 result = address(name='John', street='8 Claymore Hill', postcode=229572)
9 '''
10 there is no need to input 'Singapore' because
11 they were already specified as default values
12 for the 2 arguments city and country.
13 '''
14
15 print(result)
executed in 9ms, finished 08:24:10 2020-04-29
John
8 Claymore Hill
Singapore 229572
Singapore
2 Classes
In [51]: 1 class Animal(object): #it is convention to capitalize class names
2 legs=4
3 speed=0
4
5 def run(self):
6 self.speed=10
7
8 # for explanation of self, refer to:
9 # https://pythontips.com/2013/08/07/the-self-variable-in-python-explained/
executed in 6ms, finished 08:24:10 2020-04-29
In [52]: 1 my_pet = Animal()
2 my_pet.run()
3
4 print(my_pet.speed)
executed in 5ms, finished 08:24:10 2020-04-29
10
In [53]: 1 class Dog(Animal):
2 def bark(self):
3 print('WOOF! WOOF!')
4
executed in 5ms, finished 08:24:10 2020-04-29
In [54]: 1 my_terrier = Dog()
2
3
4 my_terrier.bark()
5
6 my_terrier.legs
executed in 7ms, finished 08:24:10 2020-04-29
WOOF! WOOF!
Out[54]: 4
In [55]: 1 my_terrier.speed
2 #speed of dog before running
3 #note that speed was defined in the parent/super class named Animal
executed in 6ms, finished 08:24:10 2020-04-29
Out[55]: 0
In [56]: 1 my_terrier.run()
2 my_terrier.speed
3 #speed of dog after running
4 #note that the method run() was defined in the parent/super class named Animal
executed in 7ms, finished 08:24:10 2020-04-29
Out[56]: 10
In [57]: 1 import datetime
2
3 my_date = datetime.datetime(2018,12, 24)
4 #my_date is an instance of the datetime class
5
6 print(my_date.isoweekday()) # isoweekday is a function of the datetime class
7 print(my_date.year) # year is an attribute of the datetime class
executed in 6ms, finished 08:24:10 2020-04-29
1
2018
3 The if statement
In [58]: 1 age=35
2
3 if age>18: #the other comparisons are >=, <=, <, ==
4 print("You are older than 18.")
executed in 5ms, finished 08:24:10 2020-04-29
You are older than 18.
In [59]: 1 age=17
2
3 if age>18:
4 print("You are older than 18.")
5 else:
6 print('You are not older than 18.')
executed in 5ms, finished 08:24:10 2020-04-29
You are not older than 18.
In [60]: 1 age=100
2
3 if age>18:
4 print('You are older than 18.')
5 elif age==100:
6 print('You are really old!')
7 else:
8 print('You are not older than 18.')
executed in 5ms, finished 08:24:10 2020-04-29
You are older than 18.
In [61]: 1 age=100
2
3 if age==100:
4 print('You are really old!')
5 elif age>18:
6 print('You are older than 18.')
7 else:
8 print('You are not older than 18.')
executed in 5ms, finished 08:24:10 2020-04-29
You are really old!
In [62]: 1 this=1
2 that=3
3 something=4
4
5 if (this==1 or that>2) and something<5:
6 print("WOW!")
executed in 8ms, finished 08:24:10 2020-04-29
WOW!
4 The for loop
In [63]: 1 people = ['Bob', 'Eve', 'Steve', 'Tim']
2
3 for person in people:
4 print(person)
5
6 print(person) #this line prints Tim since it is the final item.
executed in 7ms, finished 08:24:10 2020-04-29
Bob
Eve
Steve
Tim
Tim
In [64]: 1 for person in people:
2 if person =='Eve':
3 print(person)
4
5 print(person)
executed in 30ms, finished 08:24:10 2020-04-29
Bob
Eve
Eve
Steve
Tim
In [65]: 1 for person in people:
2 if person =='Eve':
3 print(person)
4 break
5 print(person)
executed in 14ms, finished 08:24:10 2020-04-29
Bob
Eve
In [66]: 1 for person in people:
2 if person =='Eve':
3 print(person)
executed in 10ms, finished 08:24:11 2020-04-29
Eve
In [67]: 1 for person in people:
2 if person =='Eve':
3 continue
4 print(person)
executed in 7ms, finished 08:24:11 2020-04-29
Bob
Steve
Tim
5 The while loop
In [68]: 1 counter = 0
2
3 while counter<10:
4 print(counter)
5 counter+=1 # this is the same as counter = counter + 1
executed in 10ms, finished 08:24:11 2020-04-29
0
1
2
3
4
5
6
7
8
9
In [69]: 1 text = 'This is some text'
2
3 print(text[5:])
executed in 12ms, finished 08:24:11 2020-04-29
is some text
In [70]: 1 print(text[:5])
executed in 5ms, finished 08:24:11 2020-04-29
This
In [71]: 1 print(text[:-5])
executed in 5ms, finished 08:24:11 2020-04-29
This is some
In [72]: 1 print(text[5:-5])
executed in 7ms, finished 08:24:11 2020-04-29
is some