diff --git a/.nojekyll b/.nojekyll new file mode 100644 index 0000000..e69de29 diff --git a/404.html b/404.html new file mode 100644 index 0000000..151072c --- /dev/null +++ b/404.html @@ -0,0 +1,594 @@ + + + +
+ + + + + + + + + + + + + +In python, there are 6 different types of arguments that a function can take. They are:
+These are arguments that MUST ALWAYS be passed to the function.
+1 +2 +3 +4 +5 +6 |
|
These are arguments that may not be passed to the function.
+1 +2 +3 +4 +5 +6 +7 +8 +9 |
|
Note: All optional arguments are always written after the positional arguments in the function prototype
+These are arguments that are passed using their position to the function.
+1 +2 +3 +4 +5 +6 +7 |
|
Note: In the example in point 2, the variable c
is a positional argument that is optional!
These are arguments that are passed using their name to the function.
+1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 +10 +11 +12 +13 |
|
Note1: Keyword arguments are always passed to the function after positional arguments!
+Thus, simple_interest(15, time = 5, 1000)
isn't allowed, but simple_interest(15, 5, principle = 1000)
is
Note2: An argument cannot be called as both a positonal and a keyword argument IN THE SAME function call! simple_interest(15, 5, rate = 15)
would not be valid since it calls rate as both a positional and a keyword argument
When an unknown or "arbitrary" number of arguments are passed to a function, they are known as Arbitrary Arguments
+1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 +10 +11 +12 +13 +14 +15 |
|
Note1: Other arguments may follow an arbitrary argument but then that argument MUST ALWAYS be called as a keyword argument
+Note2: Other positional arguments may preceed an arbitrary argument
+Note3: An arbitrary argument CANNOT be called as a keyword argument!
+When an unknown or "arbitrary" number of keyword arguments are passed to a function, they are known as Arbitrary Keyword Arguments
+1 +2 +3 +4 +5 +6 +7 +8 |
|
Note1: No arguments can follow arbitrary keyword arguments.
+Note2: Any number of keyword or positional arguments can preceed arbitrary keyword arguments.
+1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 +10 +11 +12 +13 +14 +15 |
|
We come across a lot of different objects in our daily life. Each object has its own properties, some features that define it.
+Lets take a pen for example. What are the properties of a pen? Its colour, its size, its kind (ball-point, fountain-point, gel-ink) and maybe the name of its owner.
+Another example is a textbook. A textbook has a size, it has a subject, it has a length (the number of pages) and it has some information inside of it. Now the information inside a textbook is organised into named chapters.
+For example, a maths text book might contain chapters like "sets", "trigonometery", "calculus" and so on, and if you want someone to read or go through a chapter, you'd say something like "go through the chapter on calculus".
+Now imagine that you are a programmer who wants to write code that describes a pen, or a textbook... how could you go about writing code that expresses these properties discussed above?
+You might try writing code that looks similar to this:
+1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 +10 +11 +12 +13 +14 |
|
This is where classes come into the picture. So far we have learnt about the primitive data types in python, primitive meaning that they are in-built, simple data types which python provides to us. Now we are moving on to custom data types, data types that are defined by you, the programmer!
+So now, we want to create our own data types, a data type that would allow us to describe a pen, or any other object effectively, using code. This is exactly what a class allows us to do!
+A class is basically a blue-print for creating an object, it tells us the defining properties of the object, and it also tells us what functions the object can perform. Following the class blue-print allows us to create "instances" of that class.
+An object of a class, the realisation of the blueprint, is known as an instance of the class.
+1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46 +47 +48 +49 +50 +51 +52 +53 |
|
All programmers mutually agree to follow some rules, called conventions that are not necessary, but nice to follow while writing classes and make your code more readable to a usual programmer:
+1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 +10 +11 +12 +13 +14 +15 +16 |
|
Write a class that describes a bicycle object
+Which properties should a bicycle object have?
+What functions should a bicycle have?
+Write a class that describes a bicycle object
+Which properties should a bicycle object have?
+What functions should a bicycle have?
+1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 |
|
Data Abstraction: This is the process of hiding the implementation details from the user, allowing them to focus on the functionality instead.
+Example: you don't need to know a smartphone works internally to be able to use it. The details about its circuits, its workings are hidden from you, the user! Instead, the smartphone provides you with functions (call, message, surf the internet) only.
+Example in python:
+The functions like math.sin()
and math.cos()
can be used to find out the sine or cosine of an angle, but they do not tell you how the calcualtion is actually done. Those implementation details are hidden from you, the user and you only need to focus on the functionality!
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 |
|
There are two types of flow control statements supported by Python:
+There are times in life when you need to make decisions, and these decisions depend on certain conditions. For example, suppose that you are in a class, then a decision that you might have to make would be:
+\(\color{red} \text{if} \; \color{yellow} \text{you have a pen,} \; \color{red} \text{then} \; \color{white} \text{you can write on a piece of paper,} \; \color{red} \text{else} \; \color{white} \text{you borrow a pen}\)
+Similarly, when writing a program, you might need to make decisions at some points in your code. Conditionals are decision making statements that can be used to chose which set of instructions to execute depending on given conditions.
+if else if
statement¶An if else
statement is used whenever you need your program to make decisions. It executes one set of instructions if
a conditon is true or else
it executes another set of instructions.
Syntax: +
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 +10 +11 |
|
when writing if else statements, an indentation, usually 4 spaces, is required. Python uses these indentations to understand what part of the code is inside the if/else.
+An if
statement does not need to be followed by an else
statement everytime
1 +2 +3 +4 |
|
What if you need to check multiple conditions and do separate things for each case? this is when you use an if else if
statement!
1 +2 +3 +4 +5 +6 +7 +8 |
|
Note that in the above example, both the (b > a)
and (b == 20)
conditions are true. However, in an if else if
statement, only one branch of instructions is ever executed. Which condition takes proiority is decided by what order you write them in. So in this case, "b > 20"
will be printed to the screen because that is the first condition which is true.
Technically, whenever a condition becomes true and its branch of instructions are executed, all of the remaining conditions are skipped, and not even evaluated.
+Now that you are armed with the power of if else if
, can you:
Write a program that would print the maximum of 3 given variables.
+When you're ready, click the "Answer" to view the solution.
+Now that you are armed with the power of if else if
, can you:
Write a program that would print the maximum of 3 given variables.
+When you're ready, click the "Answer" to view the solution. +
1 +2 +3 +4 +5 +6 +7 +8 +9 |
|
There are times in life when you need to repeatedly keep doing something under certain conditions. For example, suppose that you are playing a game and you are stuck on a boss fight where you keep dying, something that you are doing might be:
+\(\color{red} \text{while} \; \color{yellow} \text{you have not defeated the boss,} \; \color{white} \text{try again}\)
+If you wanted to write out the times two table, you might do:
+\(\color{red} \text{for} \; \color{yellow} \text{every} \; \color{green} \text{number} \; \color{red} \text{between 1 and 10} \; \color{white} \text{write }2\times \color{green} \text{number}\)
+Similarly, when writing a program, it might be needed to repeat certain parts of your code multiple times. Loops are statements that can be used to repeatedly execute a block of code given a condition is true.
+Sometimes the need arises to repeatedly execute the same statement or a statement where only a few things are changing. +Loops are statements that allow us to do exactly that! There are two types of loops suported by Python:
+while
loop¶A while
statement repeatedly executes a block of code as long as (while) something is True
. This process of repeatedly executing the same block of code is known as iteration!
+For example:
1 +2 +3 +4 |
|
Now that you are armed with the power of while
, can you:
Write a program that would print the following pattern:
+1, 2, 4, 7, 11, 16... up to 15 terms?
If you need help, but don't want to see the full solution immediately, click "Hint"
+When you're ready, click "Answer" to view the solution.
+Now that you are armed with the power of while
, can you:
Write a program that would print the following pattern:
+1, 2, 4, 7, 11, 16... up to 15 terms?
If you need help, but don't want to see the full solution immediately, click "Hint"
+When you're ready, click "Answer" to view the solution.
+Hint: Notice that the pattern here is that each time, the increase of the terms is also going up by one. The 2nd term is the first term + 1, the 3rd term is the 2nd term + 2, and so on.
+Now that you are armed with the power of while
, can you:
Write a program that would print the following pattern:
+1, 2, 4, 7, 11, 16... up to 15 terms?
If you need help, but don't want to see the full solution immediately, click "Hint"
+When you're ready, click "Answer" to view the solution.
+Hint: Notice that the pattern here is that each time, the increase of the terms is also going up by one. The 2nd term is the first term + 1, the 3rd term is the 2nd term + 2, and so on.
+1 +2 +3 +4 +5 +6 |
|
for
loop¶A for
statement is specifically used to loop over a range of values, say 5
to 23
For example: +
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 +10 +11 +12 +13 |
|
For loops can also be used to loop through all the elements of a list, tuple or a dict:
+With lists: +
1 +2 +3 +4 |
|
With tuples: +
1 +2 +3 +4 |
|
With dicts: +
1 +2 +3 +4 |
|
Lets say that you are watching TV. Every time you want to change the channel, you will use the same remote control. It would be quite inconvenient if you had to make a new remote control each time you wanted to change the channel. Similarly, in programming, you might want to write a piece of code that you need to re-use multiple times in different parts of your program.
+For example, lets say that you write a program to find the largest number in a list: +
1 +2 +3 +4 +5 +6 +7 |
|
But what if you need to find the largest value in 10 different lists? Would it be feasable to rewrite the same code again 10 different times? This is where functions come into the picture. They allow you to re-use the same piece of code again and again, however many times you might want.
+More formally, A function is a block of code that allows you to to perform a specific action. It is modular, and re-usable as many times as you want. Some functions might even give you back a value.
+For example, the same code written using functions would look something like:
+1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 |
|
A function does not have to necessarily return a value:
+1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 +10 +11 |
|
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 |
|
Why does it print a None
between the elements of the lists? Remember, these functions don't return any values! Thus, print(displayElementsOf(list1))
doesn't actually have something to print!
Note: A function does not execute the rest of its code if a return statement is encountered
+1 +2 +3 +4 +5 |
|
1 |
|
Write a function to calculate the factorial of a number. +Use the function to then find the factorials of all the numbers from 1 to 20
+Note: The factorial of a number n, represented by n! is given by: \(n! = n\cdot(n-1)\cdot(n-2)...1\). For example, \(5! = 5\cdot4\cdot3\cdot2\cdot1 = 120\) and \(0! = 1\).
+Write a function to calculate the factorial of a number. +Use the function to then find the factorials of all the numbers from 1 to 20
+Note: The factorial of a number n, represented by n! is given by: \(n! = n\cdot(n-1)\cdot(n-2)...1\). For example, \(5! = 5\cdot4\cdot3\cdot2\cdot1 = 120\) and \(0! = 1\).
+1 +2 +3 +4 +5 +6 +7 +8 |
|
When writing functions with a lot of parameters and variable names that might be unintuitive, it is a good idea to use type hints! type hints allow the person writing the function to tell the user what the expected data types of all the arguments being passed into it are
+For example:
+1 +2 +3 +4 +5 +6 |
|
Lets take the factorial from the previous excersie as an example.
+We have learnt that n! = n*(n-1)*(n-2)*...*1
+Similarly, (n-1)! = (n-1)*(n-2)*...*1
+But, notice that from these two equations we can actually write that n! = n*(n-1)!
+So if you were being introduced to the factorial for the first time, and you were just told that n! = n*(n-1)! would this be enough information to find out the factorial of any number? Try computing 3! just by using the definition that n! = n*(n-1)!.
+If you actually tried to do that, you would realise that its actually not possible because with that definition, you don't know when to stop!
+3! = 3*2!
+2! = 2*1!
+1! = 1*0!
+0! = 0*(-1)!
+...
+This means that other than the fact that n! = n*(n-1)! we also need a point to stop at. Lets say that you are now told that 0! = 1. With that information in mind, we can actually compute 3!
+3! = 3*2!
+2! = 2*1!
+1! = 1*0!
+and now, we know that 0! = 1, so now we use that in the last equation and work our way back up!
+1! = 1 and then using this, 2! = 2, and then using this, it is found that 3! = 6
+This process of defining a process in its own terms is known as recursion! The "stopping point" at which we stop going down and start to work back up is known as the base case! So can we do something like this with functions? Yes!
+1 +2 +3 +4 +5 +6 +7 +8 +9 |
|
What does the following piece of code output? You are not allowed to type this into an IDE and run the code. Try to work it out by hand!
+1 +2 +3 +4 +5 +6 +7 |
|
If you need help, but don't want to see the full solution immediately, click "Hint"
+What does the following piece of code output? You are not allowed to type this into an IDE and run the code. Try to work it out by hand!
+1 +2 +3 +4 +5 +6 +7 |
|
If you need help, but don't want to see the full solution immediately, click "Hint"
+Hint: A function will always execute ALL of its code UNLESS a return statement is encountered. If another function call is encountered inside a function, it will first complete the code of that function before continuing with the rest of its own code.
+What does the following piece of code output? You are not allowed to type this into an IDE and run the code. Try to work it out by hand!
+1 +2 +3 +4 +5 +6 +7 |
|
If you need help, but don't want to see the full solution immediately, click "Hint"
+Hint: A function will always execute ALL of its code UNLESS a return statement is encountered. If another function call is encountered inside a function, it will first complete the code of that function before continuing with the rest of its own code.
+Output:
+1 +2 +3 +4 +5 +6 +7 |
|
When you open a chrome window, or play a game, or click a button on your computer, how does the computer know what to do? Who tells the computer when you click the google chrome icon "hey, open up chrome!"? Everytime you perform an action on your computer, a set of instructions associated with that action are followed by the computer. Every single thing, ranging from pressing a key on your keyboard to playing a game, watching a video, has a set of instructions associated with it that the computer follows. A computer is a dumb machine, and it must be told exactly what to do! A program is the way to do exactly this. It is a set of instructions that the computer follows to perform a certain task
+Remember, a computer is a dumb machine. We can't just simply say to a computer in english "whats 3+6". A Computer does not understand instructions written in english. Instead, we actually need to communicate with it in a language that the computer understands. A programming language is thus used to write instructions which a computer can understand. There are many programming languages that you can write instructions in, like Java, C++, JavaScript, Python. We will be learning about python today!
+Lets say that there is a Person. Now each person has some defining properties, like their name, age, sex, height, weight. A person could be a student and in that case, they would have some additional defining properties, for example the school they attend, their id number, their year, their section and their seat number.
+Now imagine that you are a programmer trying to describe a student using code... how could you go about writing code that expresses these properties discussed above? Keep in mind that a class Person
with the properties name, age, sex, height and weight already exists.
You might think of a few different things that can be done here:
+One option is to have a person
object as a part of the student
object, like so:
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 |
|
Another option might be to declare all of the properties of a person
again along with the additional properties of a student
+
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46 +47 +48 +49 +50 +51 +52 +53 +54 +55 +56 +57 +58 |
|
This is because to create a student object, you have to first make a Person object and then provide that person object to the student constructor, like so A = Student1(Person("John", 15, "male", 170, 70), "SUTD", 1024, 32, 2, "A")
Also, to access a student's name and age, you have to do A.person.name
and A.person.age
... wouldn't A.name
and A.age
make more sense?
The 2nd approach fixes this issue but it is also a bit tedious because you have to manually declare all properties of a person inside the student constructor... What if there were not 5, but 100 different properties associated with a person? It would be too unfeasable to manually rewrite them.
+This is where inheritance comes into the picture. Inheritance literally allows us to "inherit" the properties of one class (called the super or base class) into another class (called the sub or child class)
+1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46 +47 +48 +49 +50 |
|
Best practice
+The following usages of super class methods in the above example: +
1 +2 +3 |
|
1 +2 +3 +4 |
|
super()
in python does the work of figuring out which super class's function to call and if you end up changing the superclass, you don't have to change all your code everywhere (Also there can be multiple super classes, but that's a story for another day)
+Given a class computer, Write a subclass laptop and desktop with the given additional properties:
+A computer object has the following properties:
+Write a class for laptop and desktop objects that have the above properties, and the additional properties listed below:
+Desktop:
+Laptop:
+Also write a function that displays all this information
+1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 |
|
Given a class computer, Write a subclass laptop and desktop with the given additional properties:
+A computer object has the following properties:
+Write a class for laptop and desktop objects that have the above properties, and the additional properties listed below:
+Desktop:
+Laptop:
+Also write a function that displays all this information
+1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 |
|
Required Classes:
+1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46 +47 +48 +49 +50 +51 +52 +53 +54 +55 +56 +57 +58 +59 +60 +61 +62 +63 +64 +65 +66 +67 +68 +69 |
|
Now that we know how to store and change the values of a variable, what can we actually do with them?
+The most obvious thing that we can do with numbers, is do arithmetic with them. Python supports the following arithmetic operations:
+Operator | +Name | +Example | +
---|---|---|
+ |
+Addition | +a+b |
+
- |
+Subtraction | +a-b |
+
* |
+Multiplication | +a*b |
+
/ |
+Division | +a/b |
+
// |
+Integer Division | +a//b |
+
% |
+Modulo | +a%b |
+
** |
+Exponentiation | +a**b |
+
Note: Integer division gives you the quotient of the division. For example: 17/6 = 2.833
but 17//6 = 2
. Modulo on the other hand, gives you the remainder of a division.
Relational operations allow us to compare variables with one another. With these, you can find out if one variable is greater than another, if two variables are equal, and much more.
+If you have two numbers +\(\color{yellow} \text{A}\) and \(\color{yellow}\text{B}\), +and are asked +"\(\text{if} \; \color{yellow}\text{A} \; \color{red} \text{is greater than} \; \color{yellow}\text{B} \color{white}\)?" +then you can have only two possible answers, it will either be yes or no. Similarly, if you are asked +"\(\text{if} \; \color{yellow}\text{A} \; \color{red} \text{is equal to} \; \color{yellow}\text{B} \color{white}\)?" +then this question also has only two answers, yes or no.
+Whenever you use a relational operator, it is like asking one of these questions above. Then how does a computer answer a question like this? Do you remember the data type that can only store one of two different values?
+A boolean
data type can either be True
or False
, it does exactly this! Thus, the answers to all relational operations give you boolean values.
Operator | +Name | +Example | +
---|---|---|
< |
+Less Than | +a<b |
+
> |
+Greater Than | +a>b |
+
<= |
+Less Than or Equal to | +a<=b |
+
>= |
+Greater Than or Equal to | +a>=b |
+
== |
+Equal to | +a==b |
+
!= |
+Not Equal to | +a!=b |
+
a < b
This checks if the number a
is lesser than b
. If it is, then the expression evaluates to True
, else it evaluates to False
.a > b
This checks if the number a
is greater than b
. If it is, then the expression evaluates to True
, else it evaluates to False
.a <= b
This checks if the number a
is lesser than or equal to b
. If it is, then the expression evaluates to True
, else it evaluates to False
.a >= b
This checks if the number a
is greater than or equal to b
. If it is, then the expression evaluates to True
, else it evaluates to False
.a == b
This checks if the number a
is equal to b
. If it is, then the expression evaluates to True
, else it evaluates to False
.a != b
This checks if the number a
is not equal to b
. If it is, then the expression evaluates to True
, else it evaluates to False
.Note: These relational operators also work on String
values, for example a < b
checks if a
would alphabetically preceed b
.
For Example:
+1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 |
|
If two or more things are required to do a task, we can say that "this AND that are required to do the task". For example:
+To write an email to someone, you must +"\(\color{yellow} \text{have a computer} \; \color{red} \text{and} \; \color{yellow} \text{have active internet}\)" +To paint something, you must +"\(\color{yellow} \text{have a paper} \; \color{red} \text{and} \; \color{yellow} \text{have paint} \; \color{red} \text{and} \; \color{yellow} \text{have a paint brush}\)"
+Similarly, if only one, or more things are required to do a task we say that "this OR that is needed to do the task". For example:
+To play a video game, you need to +"\(\color{yellow} \text{own a computer} \; \color{red} \text{or} \; \color{yellow} \text{own a gaming console}\)" +Note that you can still play video games if you own both!
+To draw something you must +"\(\color{yellow} \text{have a pencil} \; \color{red} \text{or} \; \color{yellow} \text{have a pen} \; \color{red} \text{and} \; \color{yellow} \text{have a paper}\)"
+Boolean operations allow us to ask these sorts of questions but with boolean values instead. For example, if you wanted to ask "is A greater than B and C?" then you require boolean operations.
+Boolean AND: This is used to check if two or more boolean values are simultaneously True
.
Usage: a and b
(Here, a
and b
are boolean variables)
This checks if both a
AND b
are True
. If they are, the expression evaluates to True
, otherwise it evaluates to False
.
Every combination of inputs and outputs for a and b
can be written in a table:
a | +b | +a and b | +
---|---|---|
False | +False | +False | +
False | +True | +False | +
True | +False | +False | +
True | +True | +True | +
Note that an AND is not limited to just two variables. Any number of variables may be AND-ed together.
+For Example: a and b and c and d
. For this expression to evaluate to True, ALL of a
, b
, c
and d
must be True.
Can you write a table for all possible combinations of inputs and output for this expression?
+Boolean OR: This is used to check if one or more booleans are True
.
Usage: a or b
(Here, a
and b
are boolean variables)
This checks if either a
or b
is True
. If one of them is, then the expression evaluates to True
, else it evaluates to False
.
Every combination of inputs and outputs for a or b
can be written in a table:
a | +b | +a || b | +
---|---|---|
False | +False | +False | +
False | +True | +True | +
True | +False | +True | +
True | +True | +True | +
Note that an OR is not limited to just two variables. Any number of variables may be OR-ed together.
+For Example: a or b or c or d
. For this expression to evaluate to True, only one of a
, b
, c
and d
needs to be True.
Can you write a table for all possible combinations of inputs and output for this expression?
+ANDs and ORs can be used together in the same expression. For example:
+(a or b) and c
: for this expression to be True
, either a
or b
and c
must be True
.
a or (b and c)
: for this expression to be True
, either a
must be True
or b
and c
must be True
simultaneously.
Note that if no brackets are used when writing these expressions the expression is evaluated left to right. This means that a or b and c or d
is the same as ((a or b) and c) or d
. Thus, to make it absolutely clear as to what you mean when writing a boolean expression, you should ALWAYS use brackets appropriately for clarity, even though it is not necessary to do so.
For example: +
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 |
|
These are used to test if a certain sequence is present in an object. For example:
+1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 +10 +11 +12 +13 +14 +15 +16 |
|
When we use the =
sign in programming, it is not a mathematical equality statement. It actually tells us that we are assigning a value to a variable. So when you see something like a = a+1;
, this means that you are simply adding 1
to the value of a
. you are assigning the value a+1
to a
. Once again, it is not a mathematical equality statement, it is an assignment.
Shorthand assignment operators allow us to assign values to variables:
+Operator | +Name | +Example | +Non Short Hand Equivalent | +
---|---|---|---|
+= |
+Addition | +a+=b |
+a = a+b |
+
-= |
+Subtraction | +a-=b |
+a = a-b |
+
*= |
+Multiplication | +a*=b |
+a = a*b |
+
/= |
+Division | +a/=b |
+a = a/b |
+
//= |
+Integer Division | +a//=b |
+a = a//b |
+
%= |
+Modulo | +a%=b |
+a = a%b |
+
**= |
+Exponentiation | +a**=b |
+a = a**b |
+
Note: There are two more types of operators, Identity Operators and Bitwise Operators. Bitwise Operators are out of the scope of today's session, and we will be taking a look at Identity Operators at a later point.
+ + + + + + +When you open a chrome window, or play a game, or click a button on your computer, how does the computer know what to do? Who tells the computer when you click the google chrome icon \"hey, open up chrome!\"? Everytime you perform an action on your computer, a set of instructions associated with that action are followed by the computer. Every single thing, ranging from pressing a key on your keyboard to playing a game, watching a video, has a set of instructions associated with it that the computer follows. A computer is a dumb machine, and it must be told exactly what to do! A program is the way to do exactly this. It is a set of instructions that the computer follows to perform a certain task
"},{"location":"#2-how-do-we-write-a-program","title":"2. How do we Write a Program?","text":"Remember, a computer is a dumb machine. We can't just simply say to a computer in english \"whats 3+6\". A Computer does not understand instructions written in english. Instead, we actually need to communicate with it in a language that the computer understands. A programming language is thus used to write instructions which a computer can understand. There are many programming languages that you can write instructions in, like Java, C++, JavaScript, Python. We will be learning about python today!
"},{"location":"#3-requirements","title":"3. Requirements","text":"Python:
To use python, you must install it first. Find the download here
A text editor/IDE of choice:
To write python code, we need a text editor or an IDE. I will be using VS Code for today which can be found here
In python, there are 6 different types of arguments that a function can take. They are:
"},{"location":"arguments/#1-required-arguments","title":"1. Required Arguments","text":"These are arguments that MUST ALWAYS be passed to the function.
def add(a, b):\n # a and b are required arguments\n return a+b\n\nprint(add(3, 5))\n# prints 8\n
"},{"location":"arguments/#2-optional-arguments","title":"2. Optional Arguments","text":"These are arguments that may not be passed to the function.
def add(a, b, c = 0):\n # a and b are required arguments while c is an optional argument. All arguments initialised with a default value are optional\n return a+b+c\n\nprint(add(3, 5))\n# prints 8\n\nprint(add(3, 5, 5))\n# prints 13\n
Note: All optional arguments are always written after the positional arguments in the function prototype
"},{"location":"arguments/#3-positional-arguments","title":"3. Positional Arguments","text":"These are arguments that are passed using their position to the function.
def simple_interest(principle, rate, time):\n # principle, rate and time are all required arguments\n return principle*rate/100*time\n\n# since they are passed to the function by their position, i.e. principle is 1000, rate is 15 and time is 5 \nprint(simple_interest(1000, 15, 5))\n# prints 750.0\n
Note: In the example in point 2, the variable c
is a positional argument that is optional!
These are arguments that are passed using their name to the function.
def simple_interest(rate, time, principle = 100):\n # rate and time are all required arguments while principle is an optional argument with a default value of 100\n return principle*rate/100*time\n\n# since they are passed to the function \nprint(simple_interest(rate = 15, principle = 1000, time = 5))\n# prints 750.0\n\nprint(simple_interest(15, 5))\n# prints 75.0\n\nprint(simple_interest(15, principle = 1000, time = 5))\n# prints 750.0\n
Note1: Keyword arguments are always passed to the function after positional arguments!
Thus, simple_interest(15, time = 5, 1000)
isn't allowed, but simple_interest(15, 5, principle = 1000)
is
Note2: An argument cannot be called as both a positonal and a keyword argument IN THE SAME function call! simple_interest(15, 5, rate = 15)
would not be valid since it calls rate as both a positional and a keyword argument
When an unknown or \"arbitrary\" number of arguments are passed to a function, they are known as Arbitrary Arguments
def add_multiply(*nums, multiply = 1):\n # nums is a required argument. the * denotes that it will accept an arbitrary number of arguments.\n # nums will be a list of all the arguments provided\n sum = 0\n for num in nums:\n sum+=num\n return sum*multiply\n\n# add up all these numbers\nprint(add_multiply(5, 6, 2, 4, 2))\n# prints 19\n\n# add up all these numbers and also multiply by 2\nprint(add_multiply(5, 6, 2, 4, 2, 3, 5, multiply = 2))\n# prints 54\n
Note1: Other arguments may follow an arbitrary argument but then that argument MUST ALWAYS be called as a keyword argument
Note2: Other positional arguments may preceed an arbitrary argument
Note3: An arbitrary argument CANNOT be called as a keyword argument!
"},{"location":"arguments/#6-arbitrary-keyword-argumentskwargs","title":"6. Arbitrary Keyword Arguments(**kwargs)","text":"When an unknown or \"arbitrary\" number of keyword arguments are passed to a function, they are known as Arbitrary Keyword Arguments
def display_works(author, **works):\n # works is a required argument. the ** denotes that it will accept an arbitrary number of keyword arguments.\n # works will be a dictionary of all the keyword arguments and their values provided.\n for key in works:\n print(f\"({key}, {works[key]})\")\n print(author)\n\ndisplay_works(\"Roald Dahl\", book1=\"Charlie and the Chocolate Factory\", book2=\"Matilda\")\n
Note1: No arguments can follow arbitrary keyword arguments.
Note2: Any number of keyword or positional arguments can preceed arbitrary keyword arguments.
def add_multiply(*nums, multiply = 1):\n # nums is a required argument. the * denotes that it will accept an arbitrary number of arguments.\n # nums will be a list of all the arguments provided\n sum = 0\n for num in nums:\n sum+=num\n return sum*multiply\n\n# add up all these numbers\nprint(add_multiply(5, 6, 2, 4, 2))\n# prints 19\n\n# add up all these numbers and also multiply by 2\nprint(add_multiply(5, 6, 2, 4, 2, 3, 5, multiply = 2))\n# prints 54\n
"},{"location":"classes_objects/","title":"Classes and Objects","text":""},{"location":"classes_objects/#1-what-is-object-oriented-programming-and-why-do-we-need-it","title":"1. What is Object Oriented Programming, and why do we need it?","text":"We come across a lot of different objects in our daily life. Each object has its own properties, some features that define it.
Lets take a pen for example. What are the properties of a pen? Its colour, its size, its kind (ball-point, fountain-point, gel-ink) and maybe the name of its owner.
Another example is a textbook. A textbook has a size, it has a subject, it has a length (the number of pages) and it has some information inside of it. Now the information inside a textbook is organised into named chapters.
For example, a maths text book might contain chapters like \"sets\", \"trigonometery\", \"calculus\" and so on, and if you want someone to read or go through a chapter, you'd say something like \"go through the chapter on calculus\".
Now imagine that you are a programmer who wants to write code that describes a pen, or a textbook... how could you go about writing code that expresses these properties discussed above?
You might try writing code that looks similar to this:
pen_colour = \"red\"\npen_size = 0.5\npen_kind = \"ball\"\npen_owner = \"John\"\n\n# wouldn't you want a way to see the info about your pen? Lets write a function to do that!\ndef display_information(colour, size, kind, owner):\n print(\"Colour : \" + colour)\n print(\"Size : \" + str(size))\n print(\"Kind : \" + kind)\n print(\"Owner : \" + owner)\n print()\n\ndisplay_information(pen_colour, pen_size, pen_kind, pen_owner)\n
Sure, that would work for one pen, but some questions one might have are: This is where classes come into the picture. So far we have learnt about the primitive data types in python, primitive meaning that they are in-built, simple data types which python provides to us. Now we are moving on to custom data types, data types that are defined by you, the programmer!
"},{"location":"classes_objects/#2-what-are-classes-and-why-do-we-need-them","title":"2. What are classes, and why do we need them?","text":"So now, we want to create our own data types, a data type that would allow us to describe a pen, or any other object effectively, using code. This is exactly what a class allows us to do!
A class is basically a blue-print for creating an object, it tells us the defining properties of the object, and it also tells us what functions the object can perform. Following the class blue-print allows us to create \"instances\" of that class.
An object of a class, the realisation of the blueprint, is known as an instance of the class.
class Pen:\n\n # remember the properties of the pen we discussed? A colour, a size, a kind, an owner\n\n def __init__(pen, col, sz, knd, own):\n pen.colour = col\n pen.size = sz\n pen.kind = knd\n pen.owner = own\n\n # This special function __init__ is known as a constructor, this is the \"method\" by which the object will be \"constructed\",\n # this is the essence of the blue-print!\n\n\n # wouldn't you want a way to see the properties of a pen you made as well?\n # you can write functions in a class that can work with the instances of the class. These functions are known as 'member\n # functions' of the class or 'methods'.\n\n # methods are always functions that work on objects of a specific class. A method cannot be used without an object\n\n # All methods of a class are unique to that class, and cannot be used on objects from other classes!\n # for example, you could have a method called read() that reads the contents of a text book but you\n # cannot use that method on a pen, because it doesn't make sense to read a pen!\n def display_information(pen):\n print(\"Colour : \" + pen.colour)\n print(\"Size : \" + str(pen.size))\n print(\"Kind : \" + pen.kind)\n print(\"Owner : \" + pen.owner)\n print()\n\n# But a class is just a blue-print for creating a pen, it tells us which properties a pen is supposed to have\n# But it is NOT the pen itself!\n# To actually create a pen, we need to use the blue-print and specify all the properties of the specifc pen we want to create:\n\nA = Pen(\"red\", 0.5, \"marker\", \"John\")\n# When we do this, python calls the constructor and says, hey constructor,\n# construct me a Pen with its colour as \"red\", its size as 0.5, its kind as \"marker\" and let its owner be \"John\"\n# this process of creating an object from its class is known as instantiation\n\nA.display_information()\n# display this marker's information\n\n# And now that we actually have a pen class, remember that we can make AS MANY pens as we want!\nB = Pen(\"blue\", 0.1, \"ball\", \"John\")\nC = Pen(\"black\", 0.2, \"fountain\", \"Robin\")\nD = Pen(\"red\", 0.1, \"gel\", \"Joe\")\nE = Pen(\"green\", 0.1, \"gel\", \"Robert\")\n\n# since a method works on a particular instance of a class, it must be called by using the dot operator, on that specific object.\nB.display_information()\nC.display_information()\nD.display_information()\nE.display_information()\n
"},{"location":"classes_objects/#3-classes-conventionally","title":"3. Classes, conventionally","text":"All programmers mutually agree to follow some rules, called conventions that are not necessary, but nice to follow while writing classes and make your code more readable to a usual programmer:
class Pen:\n\n # typically, the object is called \"self\" in the functions that work with it\n # it is also common to give the same names to the function parameters as the properties of the object itself\n def __init__(self, colour, size, kind, owner):\n self.colour = colour\n self.size = size\n self.kind = kind\n self.owner = owner\n\n def display_information(self):\n print(\"Colour : \" + self.colour)\n print(\"Size : \" + str(self.size))\n print(\"Kind : \" + self.kind)\n print(\"Owner : \" + self.owner)\n print()\n
PractiseAnswer Write a class that describes a bicycle object
Which properties should a bicycle object have?
What functions should a bicycle have?
Write a class that describes a bicycle object
Which properties should a bicycle object have?
What functions should a bicycle have?
class Bicycle:\n def __init__(self,\n colour,\n mat,\n size,\n height,\n gear_ratio,\n diameter,\n has_basket,\n has_bell):\n self.colour = colour\n self.mat = mat\n self.size = size\n self.height = height\n self.gear_ratio = gear_ratio\n self.diameter = diameter\n self.has_basket = has_basket\n self.has_bell = has_bell\n\n def change_gear(self, new_ratio):\n self.gear_ratio = new_ratio\n\n def change_height(self, new_height):\n self.height = new_ratio\n
"},{"location":"classes_objects/#4-what-makes-classes-so-good","title":"4. What makes classes so good?","text":"Data Abstraction: This is the process of hiding the implementation details from the user, allowing them to focus on the functionality instead.
Example: you don't need to know a smartphone works internally to be able to use it. The details about its circuits, its workings are hidden from you, the user! Instead, the smartphone provides you with functions (call, message, surf the internet) only.
Example in python: The functions like math.sin()
and math.cos()
can be used to find out the sine or cosine of an angle, but they do not tell you how the calcualtion is actually done. Those implementation details are hidden from you, the user and you only need to focus on the functionality!
class Pen:\n def __init__(self, colour, size, kind, owner):\n self.colour = colour\n self.size = size\n self.kind = kind\n self.owner = owner\n def display_information(self):\n print(\"Colour : \" + self.colour)\n print(\"Size : \" + str(self.size))\n print(\"Kind : \" + self.kind)\n print(\"Owner : \" + self.owner)\n print()\nclass Pencil:\n def __init__(self, colour, shade, owner):\n self.colour = colour\n self.shade = shade\n self.owner = owner\n def display_information(self):\n print(\"Colour : \" + self.colour)\n print(\"Shade : \" + str(self.shade))\n print(\"Owner : \" + self.owner)\n print()\n\nclass Stationary:\n def __init__(self, pen, pencil):\n self.pen = pen\n self.pencil = pencil\n def display_information(self):\n print(\"The Pen: \")\n self.pen.display_information()\n print(\"The Pencil: \")\n self.pencil.display_information()\n\nA = Stationary(Pen(\"blue\", 0.1, \"ball\", \"John\"), Pencil(\"black\", \"HB\", \"John\"))\nA.display_information()\n
"},{"location":"flow_control/","title":"Flow Control","text":"There are two types of flow control statements supported by Python:
"},{"location":"flow_control/#1-conditionals","title":"1. Conditionals","text":"There are times in life when you need to make decisions, and these decisions depend on certain conditions. For example, suppose that you are in a class, then a decision that you might have to make would be:
\\(\\color{red} \\text{if} \\; \\color{yellow} \\text{you have a pen,} \\; \\color{red} \\text{then} \\; \\color{white} \\text{you can write on a piece of paper,} \\; \\color{red} \\text{else} \\; \\color{white} \\text{you borrow a pen}\\)
Similarly, when writing a program, you might need to make decisions at some points in your code. Conditionals are decision making statements that can be used to chose which set of instructions to execute depending on given conditions.
"},{"location":"flow_control/#11-the-if-else-if-statement","title":"1.1. Theif else if
statement","text":"An if else
statement is used whenever you need your program to make decisions. It executes one set of instructions if
a conditon is true or else
it executes another set of instructions.
Syntax:
a = 10\nb = 20\n# if(boolean expression / variable / constant)\nif b > a:\n # if the above condition is true do:\n print(\"does one thing\")\n print(\"b > a confirmed!\")\nelse:\n # if the above condition is not true do:\n print(\"does another thing\")\n print(\"b <= a confirmed!\")\n
when writing if else statements, an indentation, usually 4 spaces, is required. Python uses these indentations to understand what part of the code is inside the if/else.
An if
statement does not need to be followed by an else
statement everytime
a = 10\nb = 20\nif b > a:\n print(\"doesn't do anything if the conditon is false\")\n
What if you need to check multiple conditions and do separate things for each case? this is when you use an if else if
statement!
a = 10\nb = 20\nif b > a:\n print(\"b > 20\")\nelif b == 20: # elif is short for else if\n print(\"b == 20\")\nelse:\n print(\"no condition is true\")\n
Note that in the above example, both the (b > a)
and (b == 20)
conditions are true. However, in an if else if
statement, only one branch of instructions is ever executed. Which condition takes proiority is decided by what order you write them in. So in this case, \"b > 20\"
will be printed to the screen because that is the first condition which is true.
Technically, whenever a condition becomes true and its branch of instructions are executed, all of the remaining conditions are skipped, and not even evaluated.
PractiseAnswerNow that you are armed with the power of if else if
, can you:
Write a program that would print the maximum of 3 given variables.
When you're ready, click the \"Answer\" to view the solution.
Now that you are armed with the power of if else if
, can you:
Write a program that would print the maximum of 3 given variables.
When you're ready, click the \"Answer\" to view the solution.
a = 10\nb = 20\nc = 30\nif a > b and a > c:\n print(\"the maximum is a: \"+a)\nelse if b > c and b > a:\n print(\"the maximum is b: \"+b)\nelse:\n print(\"the maximum is c: \"+c)\n
"},{"location":"flow_control/#2-loops","title":"2. Loops","text":"There are times in life when you need to repeatedly keep doing something under certain conditions. For example, suppose that you are playing a game and you are stuck on a boss fight where you keep dying, something that you are doing might be:
\\(\\color{red} \\text{while} \\; \\color{yellow} \\text{you have not defeated the boss,} \\; \\color{white} \\text{try again}\\)
If you wanted to write out the times two table, you might do:
\\(\\color{red} \\text{for} \\; \\color{yellow} \\text{every} \\; \\color{green} \\text{number} \\; \\color{red} \\text{between 1 and 10} \\; \\color{white} \\text{write }2\\times \\color{green} \\text{number}\\)
Similarly, when writing a program, it might be needed to repeat certain parts of your code multiple times. Loops are statements that can be used to repeatedly execute a block of code given a condition is true.
Sometimes the need arises to repeatedly execute the same statement or a statement where only a few things are changing. Loops are statements that allow us to do exactly that! There are two types of loops suported by Python:
"},{"location":"flow_control/#21-the-while-loop","title":"2.1. Thewhile
loop","text":"A while
statement repeatedly executes a block of code as long as (while) something is True
. This process of repeatedly executing the same block of code is known as iteration! For example:
a = 0\nwhile a < 10:\n print(\"a = \"+a)\n a+=1\n
PractiseHintAnswer Now that you are armed with the power of while
, can you:
Write a program that would print the following pattern:
1, 2, 4, 7, 11, 16... up to 15 terms?
If you need help, but don't want to see the full solution immediately, click \"Hint\"
When you're ready, click \"Answer\" to view the solution.
Now that you are armed with the power of while
, can you:
Write a program that would print the following pattern:
1, 2, 4, 7, 11, 16... up to 15 terms?
If you need help, but don't want to see the full solution immediately, click \"Hint\"
When you're ready, click \"Answer\" to view the solution.
Hint: Notice that the pattern here is that each time, the increase of the terms is also going up by one. The 2nd term is the first term + 1, the 3rd term is the 2nd term + 2, and so on.
Now that you are armed with the power of while
, can you:
Write a program that would print the following pattern:
1, 2, 4, 7, 11, 16... up to 15 terms?
If you need help, but don't want to see the full solution immediately, click \"Hint\"
When you're ready, click \"Answer\" to view the solution.
Hint: Notice that the pattern here is that each time, the increase of the terms is also going up by one. The 2nd term is the first term + 1, the 3rd term is the 2nd term + 2, and so on.
number = 1\nincrease = 1\nwhile increase <= 15:\n print(\"number = \"+number)\n number = number + increase\n increase+=1\n
"},{"location":"flow_control/#22-the-for-loop","title":"2.2. The for
loop","text":"A for
statement is specifically used to loop over a range of values, say 5
to 23
For example:
for a in range(2, 23):\n print(\"a = \"+a)\n# prints numbers from 3 to 22\n\n# what if you wanted to go down from 10 to 0?\n# that is also possible:\nfor a in range(10, 0):\n print(\"a = \"+a)\n\n# you can also define a step size:\nfor a in range(10, 0, 3):\n print(\"a = \"+a)\n# similar to slicing\n
For loops can also be used to loop through all the elements of a list, tuple or a dict:
With lists:
ls = [5, 3, 56, 23]\n\nfor number in ls:\n print(number)\n
With tuples:
my_tuple = (17, 32, 11, 64)\n\nfor number in my_tuple:\n print(number)\n
With dicts:
my_dict = {3.14: \"pi\", \"pie\": \"is tasty!\", \"spongebob\": \"squarepants\"}\n\nfor key in my_dict:\n print(key, my_dict[key])\n
"},{"location":"functions/","title":"Functions","text":""},{"location":"functions/#1-what-are-functions-and-why-do-we-need-them","title":"1. What are functions and why do we need them?","text":"Lets say that you are watching TV. Every time you want to change the channel, you will use the same remote control. It would be quite inconvenient if you had to make a new remote control each time you wanted to change the channel. Similarly, in programming, you might want to write a piece of code that you need to re-use multiple times in different parts of your program.
For example, lets say that you write a program to find the largest number in a list:
list_of_numbers = [32, 88, 3, 48, 87, 22]\nmaximum = list_of_numbers[0]\n\nfor number in list_of_numbers:\n if maximum < number:\n maximum = number\nprint(maximum)\n
But what if you need to find the largest value in 10 different lists? Would it be feasable to rewrite the same code again 10 different times? This is where functions come into the picture. They allow you to re-use the same piece of code again and again, however many times you might want.
More formally, A function is a block of code that allows you to to perform a specific action. It is modular, and re-usable as many times as you want. Some functions might even give you back a value.
For example, the same code written using functions would look something like:
# this line is known as the function prototype.\n# the variables inside the brackets are known as formal parameters or formal arguments\ndef max_value(list_of_numbers):\n\n# the word 'def' is short for define. It means you are defining a function called 'max_value'\n\n# In python, it is a convention to write function names in 'snake case'\n# snake case means that the each word is in lower case, and separated by underscores.\n# Example: this_is_snake_case\n\n maximum = list_of_numbers[0]\n\n for number in list_of_numbers:\n if maximum < number:\n maximum = number\n\n # the word 'return' here tells python that this function needs to give you back the value of 'maximum'\n return maximum\nlist1 = [32, 88, 3, 48, 87, 22]\nlist2 = [44, 26, 56, 90, 12, 35]\nlist3 = [96, 43, 30, 12, 37, 26]\n\n\n# this is known as a function call and the variables passed to the function are called actual parameters or actual arguments\nmax1 = max_value(list1)\nmax2 = max_value(list2)\nmax3 = max_value(list3)\n\nprint(max1)\nprint(max2)\nprint(max3)\n
A function does not have to necessarily return a value:
def display_elements(a_list):\n for element in a_list:\n print(element)\n\nlist1 = [32, 88, 3, 48, 87, 22]\nlist2 = [44, 26, 56, 90, 12, 35]\nlist3 = [96, 43, 30, 12, 37, 26]\n\nprint(display_elements(list1))\nprint(display_elements(list2))\nprint(display_elements(list3))\n
Output: 32\n88\n3\n48\n87\n22\nNone\n44\n26\n56\n90\n12\n35\nNone\n96\n43\n30\n12\n37\n26\nNone\n
Why does it print a None
between the elements of the lists? Remember, these functions don't return any values! Thus, print(displayElementsOf(list1))
doesn't actually have something to print!
Note: A function does not execute the rest of its code if a return statement is encountered
def function(number):\n return number*2\n print(number/2)\n\nprint(function(5))\n
Output: 10\n
PractiseAnswer Write a function to calculate the factorial of a number. Use the function to then find the factorials of all the numbers from 1 to 20
Note: The factorial of a number n, represented by n! is given by: \\(n! = n\\cdot(n-1)\\cdot(n-2)...1\\). For example, \\(5! = 5\\cdot4\\cdot3\\cdot2\\cdot1 = 120\\) and \\(0! = 1\\).
Write a function to calculate the factorial of a number. Use the function to then find the factorials of all the numbers from 1 to 20
Note: The factorial of a number n, represented by n! is given by: \\(n! = n\\cdot(n-1)\\cdot(n-2)...1\\). For example, \\(5! = 5\\cdot4\\cdot3\\cdot2\\cdot1 = 120\\) and \\(0! = 1\\).
def factorial(a):\n facto = 1\n for i in range(1, a+1):\n facto*=i\n return facto\n\nfor number in range(1, 21):\n print(\"the factorial of\", number, \"=\", factorial(number))\n
"},{"location":"functions/#2-type-hints","title":"2. Type Hints","text":"When writing functions with a lot of parameters and variable names that might be unintuitive, it is a good idea to use type hints! type hints allow the person writing the function to tell the user what the expected data types of all the arguments being passed into it are
For example:
# this tells the user than height is a float, weight\n# is an int and that this function is meant to return a float as well\ndef calculateBMI(height: float, weight: int) -> float:\n return weight/((height/100)**2)\n\nprint(calculateBMI(182, 80))\n
"},{"location":"functions/#3-what-is-recursion-and-why-do-we-need-it","title":"3. What is recursion, and why do we need it?","text":"Lets take the factorial from the previous excersie as an example.
We have learnt that n! = n*(n-1)*(n-2)*...*1
Similarly, (n-1)! = (n-1)*(n-2)*...*1
But, notice that from these two equations we can actually write that n! = n*(n-1)!
So if you were being introduced to the factorial for the first time, and you were just told that n! = n*(n-1)! would this be enough information to find out the factorial of any number? Try computing 3! just by using the definition that n! = n*(n-1)!.
If you actually tried to do that, you would realise that its actually not possible because with that definition, you don't know when to stop!
3! = 3*2!
2! = 2*1!
1! = 1*0!
0! = 0*(-1)!
...
This means that other than the fact that n! = n*(n-1)! we also need a point to stop at. Lets say that you are now told that 0! = 1. With that information in mind, we can actually compute 3!
3! = 3*2!
2! = 2*1!
1! = 1*0!
and now, we know that 0! = 1, so now we use that in the last equation and work our way back up!
1! = 1 and then using this, 2! = 2, and then using this, it is found that 3! = 6
This process of defining a process in its own terms is known as recursion! The \"stopping point\" at which we stop going down and start to work back up is known as the base case! So can we do something like this with functions? Yes!
def factorial(number):\n\n # remember to write a base case!\n # If you forget, you're program will be stuck\n # in an infinite loop of recursion!\n if number == 0:\n return 1\n # the recursive case:\n return number*factorial(number-1)\n
PractiseHintAnswer What does the following piece of code output? You are not allowed to type this into an IDE and run the code. Try to work it out by hand!
def function(number):\n if number >= 1:\n print(number)\n function(number-1)\n print(number)\n\nfunction(3)\n
If you need help, but don't want to see the full solution immediately, click \"Hint\"
What does the following piece of code output? You are not allowed to type this into an IDE and run the code. Try to work it out by hand!
def function(number):\n if number >= 1:\n print(number)\n function(number-1)\n print(number)\n\nfunction(3)\n
If you need help, but don't want to see the full solution immediately, click \"Hint\"
Hint: A function will always execute ALL of its code UNLESS a return statement is encountered. If another function call is encountered inside a function, it will first complete the code of that function before continuing with the rest of its own code.
What does the following piece of code output? You are not allowed to type this into an IDE and run the code. Try to work it out by hand!
def function(number):\n if number >= 1:\n print(number)\n function(number-1)\n print(number)\n\nfunction(3)\n
If you need help, but don't want to see the full solution immediately, click \"Hint\"
Hint: A function will always execute ALL of its code UNLESS a return statement is encountered. If another function call is encountered inside a function, it will first complete the code of that function before continuing with the rest of its own code.
Output:
3\n2\n1\n0\n1\n2\n3\n
"},{"location":"inheritance/","title":"Inheritance","text":""},{"location":"inheritance/#1-what-is-inheritance-and-why-do-we-need-it","title":"1. What is inheritance, and why do we need it?","text":"Lets say that there is a Person. Now each person has some defining properties, like their name, age, sex, height, weight. A person could be a student and in that case, they would have some additional defining properties, for example the school they attend, their id number, their year, their section and their seat number.
Now imagine that you are a programmer trying to describe a student using code... how could you go about writing code that expresses these properties discussed above? Keep in mind that a class Person
with the properties name, age, sex, height and weight already exists.
You might think of a few different things that can be done here:
One option is to have a person
object as a part of the student
object, like so:
class Person:\n def __init__(self, name, age, sex, height, weight):\n self.name = name\n self.age = age\n self.sex = sex\n self.height = height\n self.weight = weight\n\n def display_information(self):\n print(\"Name : \" + self.name)\n print(\"Age : \" + str(self.age))\n print(\"Sex : \" + self.sex)\n print(\"Height : \" + str(self.height))\n print(\"Weight : \" + str(self.weight))\n\nclass Student1:\n def __init__(self, person, school, id_no, seat_no, year, section):\n self.person = person\n self.school = school\n self.id_no = id_no\n self.seat_no = seat_no\n self.year = year\n self.section = section\n\n def display_information(self):\n self.person.display_information()\n print(\"School : \" + self.school)\n print(\"ID : \" + str(self.id_no))\n print(\"Seat : \" + str(self.seat_no))\n print(\"Year : \" + str(self.year))\n print(\"Section : \" + self.section)\n print()\n\n\nA = Student1(Person(\"John\", 15, \"male\", 160, 60), \"SUTD\", 1024, 32, 2, \"A\")\n\nprint(A.person.name+\"'s age: \"+str(A.person.age))\nA.display_information()\n
Another option might be to declare all of the properties of a person
again along with the additional properties of a student
# class Person here is unused, basically making the already existing class redundant\nclass Person:\n def __init__(self, name, age, sex, height, weight):\n self.name = name\n self.age = age\n self.sex = sex\n self.height = height\n self.weight = weight\n\n def display_information(self):\n print(\"Name : \" + self.name)\n print(\"Age : \" + str(self.age))\n print(\"Sex : \" + self.sex)\n print(\"Height : \" + str(self.height))\n print(\"Weight : \" + str(self.weight))\n\nclass Student2:\n def __init__(self, name, age, sex, height, weight, school, id_no, seat_no, year, section):\n self.name = name\n self.age = age\n self.sex = sex\n self.height = height\n self.weight = weight\n self.school = school\n self.id_no = id_no\n self.seat_no = seat_no\n self.year = year\n self.section = section\n\n def display_information(self):\n print(\"Name : \" + self.name)\n print(\"Age : \" + str(self.age))\n print(\"Sex : \" + self.sex)\n print(\"Height : \" + str(self.height))\n print(\"Weight : \" + str(self.weight))\n print(\"School : \" + self.school)\n print(\"ID : \" + str(self.id_no))\n print(\"Seat : \" + str(self.seat_no))\n print(\"Year : \" + str(self.year))\n print(\"Section : \" + self.section)\n print()\n\n# when there are a lot of function parameters, it is nice to specify which parameters correspond to what\n# values for better readability and clarity and put them each on their own line\nB = Student2(\n name = \"Robert\", \n age = 14, \n sex = \"male\", \n height = 160, \n weight = 65, \n school = \"SUTD\", \n id_no = 1025, \n seat_no = 12, \n year = 1, \n section = \"A\",\n)\nprint(B.name+\"'s age: \"+str(B.age))\nB.display_information()\n
The first approach works, but the syntax looks a bit unintuitive, doesn't it? This is because to create a student object, you have to first make a Person object and then provide that person object to the student constructor, like so A = Student1(Person(\"John\", 15, \"male\", 170, 70), \"SUTD\", 1024, 32, 2, \"A\")
Also, to access a student's name and age, you have to do A.person.name
and A.person.age
... wouldn't A.name
and A.age
make more sense?
The 2nd approach fixes this issue but it is also a bit tedious because you have to manually declare all properties of a person inside the student constructor... What if there were not 5, but 100 different properties associated with a person? It would be too unfeasable to manually rewrite them.
This is where inheritance comes into the picture. Inheritance literally allows us to \"inherit\" the properties of one class (called the super or base class) into another class (called the sub or child class)
# Super/Parent class\nclass Person:\n def __init__(self, name, age, sex, height, weight):\n self.name = name\n self.age = age\n self.sex = sex\n self.height = height\n self.weight = weight\n\n def display_information(self):\n print(\"Name : \" + self.name)\n print(\"Age : \" + str(self.age))\n print(\"Sex : \" + self.sex)\n print(\"Height : \" + str(self.height))\n print(\"Weight : \" + str(self.weight))\n\n# Base/Sub class\nclass Student(Person):\n def __init__(self, name, age, sex, height, weight, school, id_no, seat_no, year, section):\n Person.__init__(self, name, age, sex, height, weight) # we can re-use functionality from the super class!\n self.school = school\n self.id_no = id_no\n self.seat_no = seat_no\n self.year = year\n self.section = section\n\n def display_information(self):\n Person.display_information(self) # we can re-use functionality from the super class!\n print(\"School : \" + self.school)\n print(\"ID : \" + str(self.id_no))\n print(\"Seat : \" + str(self.seat_no))\n print(\"Year : \" + str(self.year))\n print(\"Section : \" + self.section)\n\n# when there are a lot of function parameters, it is nice to specify which parameters correspond to what\n# values for better readability and clarity and put them each on their own line\nA = Student(\n name = \"Robin\", \n age = 16, \n sex = \"male\", \n height = 180, \n weight = 75, \n school = \"SUTD\", \n id_no = 1023, \n seat_no = 3, \n year = 3, \n section = \"A\",\n)\nprint(A.name+\"'s age: \"+str(A.age))\nA.display_information()\n
Best practice
The following usages of super class methods in the above example:
Person.__init__(self, name, age, sex, height, weight)\n\nPerson.display_information(self)\n
Are for educational purposes only, in real python programs, we should make use of the following syntax instead: # notice that the self parameter has been omitted\nsuper().__init__(name, age, sex, height, weight)\n\nsuper().display_information()\n
The reason for doing so is that super()
in python does the work of figuring out which super class's function to call and if you end up changing the superclass, you don't have to change all your code everywhere (Also there can be multiple super classes, but that's a story for another day) PractiseAnswer Given a class computer, Write a subclass laptop and desktop with the given additional properties:
A computer object has the following properties:
Write a class for laptop and desktop objects that have the above properties, and the additional properties listed below:
Desktop:
Laptop:
Also write a function that displays all this information
class Computer:\n def __init__(\n self,\n cpu: str,\n storage_type: str,\n storage: float,\n ram: float,\n gpu: str,\n ):\n\n # type hints can also be given to a class' data members\n self.cpu: str = cpu\n self.storage_type: str = storage_type\n self.storage: float = storage\n self.ram: float = ram\n self.gpu: str = gpu\n\n def display_information(self):\n print(\"The CPU type is : \"+self.cpu)\n print(\"The Storage type is : \"+self.storage_type)\n print(\"The Stroage is : \"+str(self.storage))\n print(\"The RAM is : \"+str(self.ram))\n print(\"The GPU is : \"+self.gpu)\n
Given a class computer, Write a subclass laptop and desktop with the given additional properties:
A computer object has the following properties:
Write a class for laptop and desktop objects that have the above properties, and the additional properties listed below:
Desktop:
Laptop:
Also write a function that displays all this information
class Computer:\n def __init__(\n self,\n cpu: str,\n storage_type: str,\n storage: float,\n ram: float,\n gpu: str,\n ):\n\n # type hints can also be given to a class' data members\n self.cpu: str = cpu\n self.storage_type: str = storage_type\n self.storage: float = storage\n self.ram: float = ram\n self.gpu: str = gpu\n\n def display_information(self):\n print(\"The CPU type is : \"+self.cpu)\n print(\"The Storage type is : \"+self.storage_type)\n print(\"The Stroage is : \"+str(self.storage))\n print(\"The RAM is : \"+str(self.ram))\n print(\"The GPU is : \"+self.gpu)\n
Required Classes:
class Computer:\n def __init__(\n self,\n cpu: str,\n storage_type: str,\n storage: float,\n ram: float,\n gpu: str,\n ):\n\n # type hints can also be given to a class' data members\n self.cpu: str = cpu\n self.storage_type: str = storage_type\n self.storage: float = storage\n self.ram: float = ram\n self.gpu: str = gpu\n\n def display_information(self):\n print(\"The CPU type is : \"+self.cpu)\n print(\"The Storage type is : \"+self.storage_type)\n print(\"The Stroage is : \"+str(self.storage))\n print(\"The RAM is : \"+str(self.ram))\n print(\"The GPU is : \"+self.gpu)\n\nclass Laptop(Computer):\n def __init__(\n self,\n cpu: str,\n storage_type: str,\n storage: float,\n ram: float,\n gpu: str,\n resolution: str,\n is_touchscreen: bool,\n ):\n super().__init__(cpu, storage_type, storage, ram, gpu)\n self.resolution = resolution\n self.is_touchscreen = is_touchscreen\n\n def display_information(self):\n super().display_information()\n print(\"The resolution is : \"+self.resolution)\n print(\"Is it a touchscreen : \"+str(self.is_touchscreen))\n\nclass Desktop(Computer):\n def __init__(\n self,\n cpu: str,\n storage_type: str,\n storage: float,\n ram: float,\n gpu: str,\n monitor: str,\n resolution: str,\n keyboard: str,\n mouse: str,\n ):\n super().__init__(cpu, storage_type, storage, ram, gpu)\n self.monitor = monitor\n self.resolution = resolution\n self.keyboard = keyboard\n self.mouse = mouse\n\n def display_information(self):\n super().display_information()\n print(\"The monitor is : \"+self.monitor)\n print(\"The resolution is : \"+self.resolution)\n print(\"The keyboard is : \"+self.keyboard)\n print(\"The mouse is : \"+self.mouse)\n
"},{"location":"operations/","title":"Operators","text":"Now that we know how to store and change the values of a variable, what can we actually do with them?
"},{"location":"operations/#1-arithmetic-operators","title":"1. Arithmetic Operators","text":"The most obvious thing that we can do with numbers, is do arithmetic with them. Python supports the following arithmetic operations:
Operator Name Example+
Addition a+b
-
Subtraction a-b
*
Multiplication a*b
/
Division a/b
//
Integer Division a//b
%
Modulo a%b
**
Exponentiation a**b
Note: Integer division gives you the quotient of the division. For example: 17/6 = 2.833
but 17//6 = 2
. Modulo on the other hand, gives you the remainder of a division.
Relational operations allow us to compare variables with one another. With these, you can find out if one variable is greater than another, if two variables are equal, and much more.
If you have two numbers \\(\\color{yellow} \\text{A}\\) and \\(\\color{yellow}\\text{B}\\), and are asked \"\\(\\text{if} \\; \\color{yellow}\\text{A} \\; \\color{red} \\text{is greater than} \\; \\color{yellow}\\text{B} \\color{white}\\)?\" then you can have only two possible answers, it will either be yes or no. Similarly, if you are asked \"\\(\\text{if} \\; \\color{yellow}\\text{A} \\; \\color{red} \\text{is equal to} \\; \\color{yellow}\\text{B} \\color{white}\\)?\" then this question also has only two answers, yes or no.
Whenever you use a relational operator, it is like asking one of these questions above. Then how does a computer answer a question like this? Do you remember the data type that can only store one of two different values?
A boolean
data type can either be True
or False
, it does exactly this! Thus, the answers to all relational operations give you boolean values.
<
Less Than a<b
>
Greater Than a>b
<=
Less Than or Equal to a<=b
>=
Greater Than or Equal to a>=b
==
Equal to a==b
!=
Not Equal to a!=b
a < b
This checks if the number a
is lesser than b
. If it is, then the expression evaluates to True
, else it evaluates to False
.a > b
This checks if the number a
is greater than b
. If it is, then the expression evaluates to True
, else it evaluates to False
.a <= b
This checks if the number a
is lesser than or equal to b
. If it is, then the expression evaluates to True
, else it evaluates to False
.a >= b
This checks if the number a
is greater than or equal to b
. If it is, then the expression evaluates to True
, else it evaluates to False
.a == b
This checks if the number a
is equal to b
. If it is, then the expression evaluates to True
, else it evaluates to False
.a != b
This checks if the number a
is not equal to b
. If it is, then the expression evaluates to True
, else it evaluates to False
.Note: These relational operators also work on String
values, for example a < b
checks if a
would alphabetically preceed b
.
For Example:
# with numbers:\n a = 10\n b = 20.0\n c = 30\n\n# this would print True\nprint(\"a < b is\", a < b)\n\n# this would print False\nprint(\"b > c is\", b > c)\n\n# this would print True\nprint(\"(a+b) == b is\", (a+b) == b)\n\n# this would print True\nprint(\"(a+b) >= c is\", (a+b) >= c)\n\n# this would print True\nprint(\"b <= c is\", b <= c)\n\n\n# With Strings:\nstr1 = \"ball\"\nstr2 = \"apple\"\nstr3 = \"cat\"\nstr4 = \"cat\"\n\n# this would print False\n# this is because alphabetically, str1 does not come before str2\nprint(\"str1 < str2 is\", str1 < str2)\n\n# this would print False\n# this is because alphabetically, str2 comes before str3\nprint(\"str3 > str2 is\", str3 > str2)\n\n# this would print True\nprint(\"str3 == str4 is\", str3 == str4)\n\n# this would print True\nprint(\"str1 != str2 is\", str1 != str2)\n
"},{"location":"operations/#3-boolean-operators","title":"3. Boolean Operators","text":"If two or more things are required to do a task, we can say that \"this AND that are required to do the task\". For example:
To write an email to someone, you must \"\\(\\color{yellow} \\text{have a computer} \\; \\color{red} \\text{and} \\; \\color{yellow} \\text{have active internet}\\)\" To paint something, you must \"\\(\\color{yellow} \\text{have a paper} \\; \\color{red} \\text{and} \\; \\color{yellow} \\text{have paint} \\; \\color{red} \\text{and} \\; \\color{yellow} \\text{have a paint brush}\\)\"
Similarly, if only one, or more things are required to do a task we say that \"this OR that is needed to do the task\". For example:
To play a video game, you need to \"\\(\\color{yellow} \\text{own a computer} \\; \\color{red} \\text{or} \\; \\color{yellow} \\text{own a gaming console}\\)\" Note that you can still play video games if you own both!
To draw something you must \"\\(\\color{yellow} \\text{have a pencil} \\; \\color{red} \\text{or} \\; \\color{yellow} \\text{have a pen} \\; \\color{red} \\text{and} \\; \\color{yellow} \\text{have a paper}\\)\"
Boolean operations allow us to ask these sorts of questions but with boolean values instead. For example, if you wanted to ask \"is A greater than B and C?\" then you require boolean operations.
"},{"location":"operations/#31-the-boolean-and","title":"3.1. The Boolean AND","text":"Boolean AND: This is used to check if two or more boolean values are simultaneously True
.
Usage: a and b
(Here, a
and b
are boolean variables)
This checks if both a
AND b
are True
. If they are, the expression evaluates to True
, otherwise it evaluates to False
.
Every combination of inputs and outputs for a and b
can be written in a table:
Note that an AND is not limited to just two variables. Any number of variables may be AND-ed together. For Example: a and b and c and d
. For this expression to evaluate to True, ALL of a
, b
, c
and d
must be True.
Can you write a table for all possible combinations of inputs and output for this expression?
"},{"location":"operations/#32-the-boolean-or","title":"3.2. The Boolean OR","text":"Boolean OR: This is used to check if one or more booleans are True
.
Usage: a or b
(Here, a
and b
are boolean variables)
This checks if either a
or b
is True
. If one of them is, then the expression evaluates to True
, else it evaluates to False
.
Every combination of inputs and outputs for a or b
can be written in a table:
Note that an OR is not limited to just two variables. Any number of variables may be OR-ed together. For Example: a or b or c or d
. For this expression to evaluate to True, only one of a
, b
, c
and d
needs to be True.
Can you write a table for all possible combinations of inputs and output for this expression?
ANDs and ORs can be used together in the same expression. For example:
(a or b) and c
: for this expression to be True
, either a
or b
and c
must be True
.
a or (b and c)
: for this expression to be True
, either a
must be True
or b
and c
must be True
simultaneously.
Note that if no brackets are used when writing these expressions the expression is evaluated left to right. This means that a or b and c or d
is the same as ((a or b) and c) or d
. Thus, to make it absolutely clear as to what you mean when writing a boolean expression, you should ALWAYS use brackets appropriately for clarity, even though it is not necessary to do so.
For example:
a = 10\nb = 20\nc = 30\n\n# this would print True on the screen\n# because both a < b and c > d are True\nprint((a < b) and (c > b))\n\n# this would print False on the screen\n# because c < b is False\nprint((a < b) and (c < b))\n\n# this would print True on the screen\n# because a < b is True\nprint((a < b) or (c < b))\n\n# this would print False on the screen\n# because neither a > b nor c < b is True\nprint((a > b) or (c < b))\n
"},{"location":"operations/#4-membership-operators","title":"4. Membership Operators","text":"These are used to test if a certain sequence is present in an object. For example:
print(\"water\" in \"this is a waterbottle\")\nprint(\"water\" not in \"this is a waterbottle\")\nprint(\"spongebob\" in \"squarepants\")\nprint(\"spongebob\" not in \"squarepants\")\n\n# they also work on lists, tuples and dicts:\n\nprint(5 in [5, 3, 1, 2, 7])\nprint(11 not in [1, 2, 6, 7])\n\nprint(17 in (15, 12, 16, 19, 17))\nprint(16 not in (14, 17, 11, 21))\n\n# for dicts, it checks if a certain key is present in the dict\nprint(3.14 in {3.14: \"pi\"})\nprint(5 in {3.14: \"pi\"})\n
"},{"location":"operations/#5-the-assignment-operation","title":"5. The Assignment Operation","text":"When we use the =
sign in programming, it is not a mathematical equality statement. It actually tells us that we are assigning a value to a variable. So when you see something like a = a+1;
, this means that you are simply adding 1
to the value of a
. you are assigning the value a+1
to a
. Once again, it is not a mathematical equality statement, it is an assignment.
Shorthand assignment operators allow us to assign values to variables:
Operator Name Example Non Short Hand Equivalent+=
Addition a+=b
a = a+b
-=
Subtraction a-=b
a = a-b
*=
Multiplication a*=b
a = a*b
/=
Division a/=b
a = a/b
//=
Integer Division a//=b
a = a//b
%=
Modulo a%=b
a = a%b
**=
Exponentiation a**=b
a = a**b
Note: There are two more types of operators, Identity Operators and Bitwise Operators. Bitwise Operators are out of the scope of today's session, and we will be taking a look at Identity Operators at a later point.
"},{"location":"vars/","title":"Python Basics","text":""},{"location":"vars/#1-constants","title":"1. Constants","text":"To do anything in a program, we need constants. Any value that remains the same throughout the execution of the program is known as a constant. Quite literally, it is a constant. For example, 10
is a constant. Every number is a constant.
Variables are like boxes that are used to store constants. Variables are values that can change during the execution of the program! Think about it this way, if a variable is a box that stores a constant, that constant can be taken out and another one can be put in. Quite literally, it is a variable (it may change!). For example:
# creating and storing a value in a variable\n# is known as variable initialisation\n\na = 10\nb = 20.5\nc = a+b\n\n# a, b and c are the names of the variables here.\n\n# to be able to see the value of a variable,\n# we need to print it to the screen\nprint(c)\n\n# you can change a variable simply by re-assigning another value to it:\nc = a-b\nprint(c)\n
You can also store sentences, words:
a = \"this is a string\"\nprint(a)\n
You can store lists as well:
ls = [1, 4.5, \"python is awesome!\"]\nprint(ls)\n
"},{"location":"vars/#3-data-types","title":"3. Data Types","text":"Remember, variables are like boxes/containers that are used to store constants. For every different kind of constant, a different type of contanier/box is required! Think about it this way, you cannot store water in a paper bag. you need a water bottle to store water. Similarly, in python, each different kind of constant must be stored in a different type of variable. The type of the variable is known as its data type. So how many kinds of boxes, or data types are there? The following are the most commonly used data types in python:
"},{"location":"vars/#31-integer-int","title":"3.1. Integer (int
)","text":"An int
quantity may be negative, positive, or zero. It never has any fractional or decimal parts (for example, an integer never has 0.5
). Syntax: a = 10
This declares a variable of type int
called a
with a value of 10
float
)","text":"A float
is a data type that can store values with fractional parts or decimals. For example 1.5
is a floating point value.
Syntax: a = 3.14159
This declares a variable of type float
called a
with a value of 3.14159
bool
)","text":"A bool
is a data type, that can only store one of two different values, True
or False
. Any yes or no question is a boolean question in some sense, because there are only two answers, yes or no (true or false). Boolean variables are super important for conditions, which we will be looking at later.
Syntax: a = True
This declares a variable of type bool
called a
with a value of True
Note: A value of True
can also be indicated by 1
and a value of False
can also be indicated by 0
.
str
)","text":"An str
is a word, a phrase or a sentence. A string is always enclosed by double quotes.
Syntax: a = \"this is a string! yay\"
This declares a variable of type str
called a
with a value of \"this is a string! yay\"
Note that you can also use single quotes for declaring strings: a = 'this is a string! yay'
What if you want to use a string that has multiple lines, can you do that? Yes you can! Syntax:
a = \"\"\"this is\na multiple line\nstring\"\"\"\n\nprint(a)\n\nb = '''this is\nanother multiple line\nstring'''\n\nprint(b)\n
what if you want to obtain the letter in a particular position in a string?
a = \"python is awesome\"\nprint(a[0])\n# this will give you the first letter of the string\n# in any programming language in general,\n# when we number items, we always start at 0 and not 1\n\n\n# in python, you can actually use a negative index:\nprint(a[-1])\n# and this gives you the last character of a.\n
What if you want to obtain a particular part of the string?
b = \"this is known as slicing\"\nprint(b[4:8])\n# this will give you a string that starts from the\n# 5th character of b and ends at the 9th character.\n# Note that the 9th letter is not included in this new sliced string\n# result: \" is k\"\n\nprint(b[3:])\n# this will give you a string that starts from the 4th character of b\n# result: \"s is known as slicing\"\n\nprint(b[:5])\n# this will give you a string that ends at the 6th character of b.\n# Note that the 6th character is not included in this new sliced string\n# result: \"s is known as slicing\"\n\nprint(b[2:10:3])\n# this will give you a string that starts from the \n# 3rd character of b and ends at the 11th character.\n# Note Only the every 3rd character is selected, starting from the first.\n# result: \"iik\"\n\nprint(b[::-1])\n# this will give you a string that is the reverse of the original!\n# result: \"gnicils sa nwonk si siht\"\n\nprint(len(b))\n# gives you the length of the string\n
You can also join two or more strings togethere:
a = \"this is \"\nb = \"known as string\"\nc = \" concatenation!\"\nprint(a+b+c)\n
What would happen if you tried to access a poition of the string that is greater than its length?
a = \"this is a string\"\nprint(a[20])\n# the string does not have a 21st character,\n# you will get an error if you try this!\n
"},{"location":"vars/#35-list-list","title":"3.5. List (list
)","text":"A list
is an ordered collection of different constants. Each member of a list is formally called an element of that list.
Example:
a = [2, 3.4, \"this is a list\", True, [\"this list is inside the first one\", \":O\"]]\n
This declares a variable of type list
called a
with the following values:
2
1 3.4
2 \"this is a list\"
3 True
4 [\"this list is inside the first one\", \":O\"]
Also, in general when initialising a list, if the list is too long to fit in one line, it is common to break it up over multiple lines to increase visibility, like so:
a = [\n 2,\n 3.4,\n \"this is a list\",\n True,\n [\"this list is inside the first one\", \":O\"]\n ]\n
To obtain an element from a list, the same syntax as a string is used:
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, [10, 20, 30]]\nprint(a[0])\n# this will give you the first element of the list\n\nprint(a[-1])\n# and this gives you the last element of this (this is a list in itself)\n\nprint(a[4:8])\n# slicing also works exactly like strings.\n# this will give you a list starting from the\n# 5th element all the way to the 9th element.\n\nprint(len(a))\n# this gives you the number of elements in a list.\n\n# you can change any element of the list like so:\na[2] = 55\n\n# change the 2nd element of the last element of the list\na[-1][1] = 22\n
you can combine lists as follows:
a = [1, 2]\nb = [3, 4]\nc = [5, 6]\n\nprint(a+b+c)\n
you can add an element to a list using the append function:
a = [1, 2]\na.append(3)\nprint(a)\n
you can extend a list using another list by using the extend function:
a = [1, 2]\nb = [3, 4]\na.extend(b)\nprint(a)\n
What would happen if you tried to access an element of the list whoes index is greater than the length?
a = \"this is a string\"\nprint(a[20])\n# the string does not have a 21st character,\n# you will get an error if you try this!\n
"},{"location":"vars/#36-tuple-tuple","title":"3.6. Tuple (tuple
)","text":"A tuple
is exactly like a list. The only difference is that once a tuple is initialised, its elements cannot be altered. Technically, we say that a tuple is immutable.
Example:
a = (2, 3.4, \"this is a tuple\", True, (\"this tuple is inside the first one\", \":O\"), [\"this is a list inside the tuple\", \"o.O\"])\n
Similar to a list, it is common to break up a long tuple over multiple lines:
a = (\n 2,\n 3.4,\n \"this is a tuple\",\n True,\n (\"this tuple is inside the first one\", \":O\"),\n [\"this is a list inside the tuple\", \"o.O\"]\n )\n
This declares a variable of type tuple
called a
with the following values:
2
1 3.4
2 \"this is a tuple\"
3 True
4 (\"this tuple is inside the first one\", \":O\")
5 [\"this is a list inside the tuple\", \"o.O\"]
To obtain an element from a tuple, the same syntax as a list/string is used:
a = (1, 2, (3, 4, 5), [1, 2, 3])\nprint(a[0])\n# this will give you the first element of the tuple\n\nprint(a[-1])\n# and this gives you the last element of this tuple\n\nprint(a[0:3])\n# slicing also works on tuples.\n# this will give you a tuple starting from the \n# first element all the way to the 3rd element.\n\n# note that you cannot change the elements of a tuple.\n# trying to do that will get you an error\n\n# however, you CAN change a list inside a tuple.\na[-1][2] = 10\n
"},{"location":"vars/#37-dictionary-dict","title":"3.7. Dictionary (dict
)","text":"A dict
is a data type that can store \"key-value\" pairs. It essentially creates a map between specifed values.
The constants to the left are called keys, and the constants to the right are called values.
Example:
a = {\n \"this is a key\": \"this is it's value\",\n 3.14: \"pie\",\n 4: \"2x2\",\n (2, 3): \"a tuple!\"\n }\n
Note: like a list or a tuple, you can write the above out in one line, but dicts are almost always never written like that! its always a good idea to write each key-value pair of a dict out on a separate line
So how do you actually use a dictionary?
a = {\n \"this is a key\": \"this is it's value\",\n 3.14: \"pie\",\n 4: \"2x2\",\n (2, 3): \"a tuple!\"\n }\nprint(a[\"this is a key\"])\nprint(a[3.14])\nprint(a[4])\nprint(a[(2, 3)])\n\n# Similar to a list or tuple, you will get an\n# error from python if you try to access a key\n# that is not present in a dictionary\n\n# you can also use the get function to get values:\nprint(a.get(3.14))\n\n# you can actually specify a default value when using get\n# this is, in case the key is not in the dictionary,\n# then use the default value instead!\n\nprint(a.get(22, \"not found\"))\n
a = \"this is a string\"\nprint(type(a))\n\na = 2.2\nprint(type(a))\n\na = [1, 2]\nprint(type(a))\n\na = 2\nprint(type(a))\n\na = (4, 5)\nprint(type(a))\n\na = True\nprint(type(a))\n
Remember that your variable names can be almost anything! However, this does not mean that you should just use single letters or alphabets for variable names. Variable names should be chosen such that they represent, or hint to what the purpose of the variable is. Naming your variables such that they make intuitive sense is a good programming practise.
"},{"location":"vars/#4-variable-naming-rules-and-conventions","title":"4. Variable Naming Rules and Conventions:","text":"There are some rules that must be followed when naming a variable. They are:
You can only use letters, numbers and underscores to name your variables.
A variable name cannot start with a number.
Variable names are CaSe SeNsItIvE
. This means that a
and A
are two different variable names!
Variable names must not be keywords. A keyword is a reserved word in any programming language that has a special meaning! For example, int
is a keyword in Python because it is the name of a data type.
While these are the only laws that you absolutely must follow, there are some conventions or unwritten rules that all programmers agree to follow to make their code more readable, and more clear.
When you are writing a variable name that is just one word, it is conventional to write it in all small letters. For example radius = 10
or name = \"John Cena\"
.
When you are writing a variable name that consists of more than one word, then it is conventional to write it in a special case known as \"snake case\". Snake case is where the every word is written in small letters separated by underscores. For Example: gear_ratio = 2.2
or first_name = \"Bruce\"
or last_name = \"Wayne\"
.
When you are writing a variable that is supposed to just store the value of a constant, one which you never intend to change, it is conventional to use capital letters and words are separated by underscores. For example: PI = 3.14159
or GOLDEN_RATIO = 1.61803
.
Variable names should be precise and mnemonic. That is, they should indicate to a casual programmer their purpose. Usage of single letter variable names is discouraged unless it is a throwaway or temporary variable.
To do anything in a program, we need constants. Any value that remains the same throughout the execution of the program is known as a constant. Quite literally, it is a constant. For example, 10
is a constant. Every number is a constant.
Variables are like boxes that are used to store constants. Variables are values that can change during the execution of the program! Think about it this way, if a variable is a box that stores a constant, that constant can be taken out and another one can be put in. Quite literally, it is a variable (it may change!). For example:
+1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 +10 +11 +12 +13 +14 +15 +16 |
|
You can also store sentences, words:
+1 +2 |
|
You can store lists as well:
+1 +2 |
|
Remember, variables are like boxes/containers that are used to store constants. For every different kind of constant, a different type of contanier/box is required! Think about it this way, you cannot store water in a paper bag. you need a water bottle to store water. Similarly, in python, each different kind of constant must be stored in a different type of variable. The type of the variable is known as its data type. So how many kinds of boxes, or data types are there? The following are the most commonly used data types in python:
+int
)¶An int
quantity may be negative, positive, or zero. It never has any fractional or decimal parts (for example, an integer never has 0.5
).
+Syntax: a = 10
This declares a variable of type int
called a
with a value of 10
float
)¶A float
is a data type that can store values with fractional parts or decimals. For example 1.5
is a floating point value.
Syntax: a = 3.14159
This declares a variable of type float
called a
with a value of 3.14159
bool
)¶A bool
is a data type, that can only store one of two different values, True
or False
. Any yes or no question is a boolean question in some sense, because there are only two answers, yes or no (true or false). Boolean variables are super important for conditions, which we will be looking at later.
Syntax: a = True
This declares a variable of type bool
called a
with a value of True
Note: A value of True
can also be indicated by 1
and a value of False
can also be indicated by 0
.
str
)¶An str
is a word, a phrase or a sentence. A string is always enclosed by double quotes.
Syntax: a = "this is a string! yay"
This declares a variable of type str
called a
with a value of "this is a string! yay"
+Note that you can also use single quotes for declaring strings:
+a = 'this is a string! yay'
What if you want to use a string that has multiple lines, can you do that? +Yes you can! Syntax:
+1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 +10 +11 |
|
what if you want to obtain the letter in a particular position in a string?
+1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 +10 |
|
What if you want to obtain a particular part of the string?
+1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 |
|
You can also join two or more strings togethere: +
1 +2 +3 +4 |
|
What would happen if you tried to access a poition of the string that is greater than its length?
+1 +2 +3 +4 |
|
list
)¶A list
is an ordered collection of different constants. Each member of a list is formally called an element of that list.
Example: +
1 |
|
This declares a variable of type list
called a
with the following values:
Index | +Value | +
---|---|
0 | +2 |
+
1 | +3.4 |
+
2 | +"this is a list" |
+
3 | +True |
+
4 | +["this list is inside the first one", ":O"] |
+
Also, in general when initialising a list, if the list is too long to fit in one line, it is common to break it up over multiple lines to increase visibility, like so:
+1 +2 +3 +4 +5 +6 +7 |
|
To obtain an element from a list, the same syntax as a string is used: +
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 |
|
you can combine lists as follows:
+1 +2 +3 +4 +5 |
|
you can add an element to a list using the append function:
+1 +2 +3 |
|
you can extend a list using another list by using the extend function:
+1 +2 +3 +4 |
|
What would happen if you tried to access an element of the list whoes index is greater than the length?
+1 +2 +3 +4 |
|
tuple
)¶A tuple
is exactly like a list. The only difference is that once a tuple is initialised, its elements cannot be altered. Technically, we say that a tuple is immutable.
Example: +
1 |
|
Similar to a list, it is common to break up a long tuple over multiple lines:
+1 +2 +3 +4 +5 +6 +7 +8 |
|
This declares a variable of type tuple
called a
with the following values:
Index | +Value | +
---|---|
0 | +2 |
+
1 | +3.4 |
+
2 | +"this is a tuple" |
+
3 | +True |
+
4 | +("this tuple is inside the first one", ":O") |
+
5 | +["this is a list inside the tuple", "o.O"] |
+
To obtain an element from a tuple, the same syntax as a list/string is used:
+1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 +10 +11 +12 +13 +14 +15 +16 +17 |
|
dict
)¶A dict
is a data type that can store "key-value" pairs. It essentially creates a map between specifed values.
The constants to the left are called keys, and the constants to the right are called values.
+Example: +
1 +2 +3 +4 +5 +6 |
|
Note: like a list or a tuple, you can write the above out in one line, but dicts are almost always never written like that! its always a good idea to write each key-value pair of a dict out on a separate line
+So how do you actually use a dictionary?
+1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 |
|
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 +10 +11 +12 +13 +14 +15 +16 +17 |
|
Remember that your variable names can be almost anything! However, this does not mean that you should just use single letters or alphabets for variable names. Variable names should be chosen such that they represent, or hint to what the purpose of the variable is. Naming your variables such that they make intuitive sense is a good programming practise.
+There are some rules that must be followed when naming a variable. They are:
+You can only use letters, numbers and underscores to name your variables.
+A variable name cannot start with a number.
+Variable names are CaSe SeNsItIvE
. This means that a
and A
are two different variable names!
Variable names must not be keywords. A keyword is a reserved word in any programming language that has a special meaning! For example, int
is a keyword in Python because it is the name of a data type.
While these are the only laws that you absolutely must follow, there are some conventions or unwritten rules that all programmers agree to follow to make their code more readable, and more clear.
+When you are writing a variable name that is just one word, it is conventional to write it in all small letters. For example radius = 10
or name = "John Cena"
.
When you are writing a variable name that consists of more than one word, then it is conventional to write it in a special case known as "snake case". Snake case is where the every word is written in small letters separated by underscores. For Example: gear_ratio = 2.2
or first_name = "Bruce"
or last_name = "Wayne"
.
When you are writing a variable that is supposed to just store the value of a constant, one which you never intend to change, it is conventional to use capital letters and words are separated by underscores. For example: PI = 3.14159
or GOLDEN_RATIO = 1.61803
.
Variable names should be precise and mnemonic. That is, they should indicate to a casual programmer their purpose. Usage of single letter variable names is discouraged unless it is a throwaway or temporary variable.
+