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 @@ + + + + + + + + + + + + + + + + + + Introduction to Python Programming + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+
+ +
+ + + + +
+ + +
+ +
+ + + + + + + + + +
+
+ + + +
+
+
+ + + + + + +
+
+
+ + + +
+
+
+ + + +
+
+
+ + + +
+
+ +

404 - Not found

+ +
+
+ + +
+ + + +
+ + + +
+
+
+
+ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/arguments/index.html b/arguments/index.html new file mode 100644 index 0000000..ac22b48 --- /dev/null +++ b/arguments/index.html @@ -0,0 +1,914 @@ + + + + + + + + + + + + + + + + + + + + + + Different Types of Arguments - Introduction to Python Programming + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + Skip to content + + +
+
+ +
+ + + + +
+ + +
+ +
+ + + + + + + + + +
+
+ + + +
+
+
+ + + + + + +
+
+
+ + + + + + + +
+
+ + + + + + + + +

Different types of arguments

+

In python, there are 6 different types of arguments that a function can take. They are:

+

1. Required Arguments

+

These are arguments that MUST ALWAYS be passed to the function.

+
1
+2
+3
+4
+5
+6
def add(a, b):
+    # a and b are required arguments
+    return a+b
+
+print(add(3, 5))
+# prints 8
+
+

2. Optional Arguments

+

These are arguments that may not be passed to the function.

+
1
+2
+3
+4
+5
+6
+7
+8
+9
def add(a, b, c = 0):
+    # a and b are required arguments while c is an optional argument. All arguments initialised with a default value are optional
+    return a+b+c
+
+print(add(3, 5))
+# prints 8
+
+print(add(3, 5, 5))
+# prints 13
+
+

Note: All optional arguments are always written after the positional arguments in the function prototype

+

3. Positional Arguments

+

These are arguments that are passed using their position to the function.

+
1
+2
+3
+4
+5
+6
+7
def simple_interest(principle, rate, time):
+    # principle, rate and time are all required arguments
+    return principle*rate/100*time
+
+# since they are passed to the function by their position, i.e. principle is 1000, rate is 15 and time is 5 
+print(simple_interest(1000, 15, 5))
+# prints 750.0
+
+

Note: In the example in point 2, the variable c is a positional argument that is optional!

+

4. Keword Arguments

+

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
def simple_interest(rate, time, principle = 100):
+    # rate and time are all required arguments while principle is an optional argument with a default value of 100
+    return principle*rate/100*time
+
+# since they are passed to the function 
+print(simple_interest(rate = 15, principle = 1000, time = 5))
+# prints 750.0
+
+print(simple_interest(15, 5))
+# prints 75.0
+
+print(simple_interest(15, principle = 1000, time = 5))
+# prints 750.0
+
+

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

+

5. Arbitrary Arguments(*args)

+

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
def add_multiply(*nums, multiply = 1):
+    # nums is a required argument. the * denotes that it will accept an arbitrary number of arguments.
+    # nums will be a list of all the arguments provided
+    sum = 0
+    for num in nums:
+        sum+=num
+    return sum*multiply
+
+# add up all these numbers
+print(add_multiply(5, 6, 2, 4, 2))
+# prints 19
+
+# add up all these numbers and also multiply by 2
+print(add_multiply(5, 6, 2, 4, 2, 3, 5, multiply = 2))
+# prints 54
+
+

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!

+

6. Arbitrary Keyword Arguments(**kwargs)

+

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
def display_works(author, **works):
+    # works is a required argument. the ** denotes that it will accept an arbitrary number of keyword arguments.
+    # works will be a dictionary of all the keyword arguments and their values provided.
+    for key in works:
+        print(f"({key}, {works[key]})")
+    print(author)
+
+display_works("Roald Dahl", book1="Charlie and the Chocolate Factory", book2="Matilda")
+
+

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
def add_multiply(*nums, multiply = 1):
+    # nums is a required argument. the * denotes that it will accept an arbitrary number of arguments.
+    # nums will be a list of all the arguments provided
+    sum = 0
+    for num in nums:
+        sum+=num
+    return sum*multiply
+
+# add up all these numbers
+print(add_multiply(5, 6, 2, 4, 2))
+# prints 19
+
+# add up all these numbers and also multiply by 2
+print(add_multiply(5, 6, 2, 4, 2, 3, 5, multiply = 2))
+# prints 54
+
+ + + + + + +
+
+ + +
+ + + +
+ + + +
+
+
+
+ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/assets/images/favicon.png b/assets/images/favicon.png new file mode 100644 index 0000000..1cf13b9 Binary files /dev/null and b/assets/images/favicon.png differ diff --git a/assets/javascripts/bundle.51d95adb.min.js b/assets/javascripts/bundle.51d95adb.min.js new file mode 100644 index 0000000..b20ec68 --- /dev/null +++ b/assets/javascripts/bundle.51d95adb.min.js @@ -0,0 +1,29 @@ +"use strict";(()=>{var Hi=Object.create;var xr=Object.defineProperty;var Pi=Object.getOwnPropertyDescriptor;var $i=Object.getOwnPropertyNames,kt=Object.getOwnPropertySymbols,Ii=Object.getPrototypeOf,Er=Object.prototype.hasOwnProperty,an=Object.prototype.propertyIsEnumerable;var on=(e,t,r)=>t in e?xr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,P=(e,t)=>{for(var r in t||(t={}))Er.call(t,r)&&on(e,r,t[r]);if(kt)for(var r of kt(t))an.call(t,r)&&on(e,r,t[r]);return e};var sn=(e,t)=>{var r={};for(var n in e)Er.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(e!=null&&kt)for(var n of kt(e))t.indexOf(n)<0&&an.call(e,n)&&(r[n]=e[n]);return r};var Ht=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Fi=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of $i(t))!Er.call(e,o)&&o!==r&&xr(e,o,{get:()=>t[o],enumerable:!(n=Pi(t,o))||n.enumerable});return e};var yt=(e,t,r)=>(r=e!=null?Hi(Ii(e)):{},Fi(t||!e||!e.__esModule?xr(r,"default",{value:e,enumerable:!0}):r,e));var fn=Ht((wr,cn)=>{(function(e,t){typeof wr=="object"&&typeof cn!="undefined"?t():typeof define=="function"&&define.amd?define(t):t()})(wr,function(){"use strict";function e(r){var n=!0,o=!1,i=null,a={text:!0,search:!0,url:!0,tel:!0,email:!0,password:!0,number:!0,date:!0,month:!0,week:!0,time:!0,datetime:!0,"datetime-local":!0};function s(T){return!!(T&&T!==document&&T.nodeName!=="HTML"&&T.nodeName!=="BODY"&&"classList"in T&&"contains"in T.classList)}function f(T){var Ke=T.type,We=T.tagName;return!!(We==="INPUT"&&a[Ke]&&!T.readOnly||We==="TEXTAREA"&&!T.readOnly||T.isContentEditable)}function c(T){T.classList.contains("focus-visible")||(T.classList.add("focus-visible"),T.setAttribute("data-focus-visible-added",""))}function u(T){T.hasAttribute("data-focus-visible-added")&&(T.classList.remove("focus-visible"),T.removeAttribute("data-focus-visible-added"))}function p(T){T.metaKey||T.altKey||T.ctrlKey||(s(r.activeElement)&&c(r.activeElement),n=!0)}function m(T){n=!1}function d(T){s(T.target)&&(n||f(T.target))&&c(T.target)}function h(T){s(T.target)&&(T.target.classList.contains("focus-visible")||T.target.hasAttribute("data-focus-visible-added"))&&(o=!0,window.clearTimeout(i),i=window.setTimeout(function(){o=!1},100),u(T.target))}function v(T){document.visibilityState==="hidden"&&(o&&(n=!0),B())}function B(){document.addEventListener("mousemove",z),document.addEventListener("mousedown",z),document.addEventListener("mouseup",z),document.addEventListener("pointermove",z),document.addEventListener("pointerdown",z),document.addEventListener("pointerup",z),document.addEventListener("touchmove",z),document.addEventListener("touchstart",z),document.addEventListener("touchend",z)}function re(){document.removeEventListener("mousemove",z),document.removeEventListener("mousedown",z),document.removeEventListener("mouseup",z),document.removeEventListener("pointermove",z),document.removeEventListener("pointerdown",z),document.removeEventListener("pointerup",z),document.removeEventListener("touchmove",z),document.removeEventListener("touchstart",z),document.removeEventListener("touchend",z)}function z(T){T.target.nodeName&&T.target.nodeName.toLowerCase()==="html"||(n=!1,re())}document.addEventListener("keydown",p,!0),document.addEventListener("mousedown",m,!0),document.addEventListener("pointerdown",m,!0),document.addEventListener("touchstart",m,!0),document.addEventListener("visibilitychange",v,!0),B(),r.addEventListener("focus",d,!0),r.addEventListener("blur",h,!0),r.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&r.host?r.host.setAttribute("data-js-focus-visible",""):r.nodeType===Node.DOCUMENT_NODE&&(document.documentElement.classList.add("js-focus-visible"),document.documentElement.setAttribute("data-js-focus-visible",""))}if(typeof window!="undefined"&&typeof document!="undefined"){window.applyFocusVisiblePolyfill=e;var t;try{t=new CustomEvent("focus-visible-polyfill-ready")}catch(r){t=document.createEvent("CustomEvent"),t.initCustomEvent("focus-visible-polyfill-ready",!1,!1,{})}window.dispatchEvent(t)}typeof document!="undefined"&&e(document)})});var un=Ht(Sr=>{(function(e){var t=function(){try{return!!Symbol.iterator}catch(c){return!1}},r=t(),n=function(c){var u={next:function(){var p=c.shift();return{done:p===void 0,value:p}}};return r&&(u[Symbol.iterator]=function(){return u}),u},o=function(c){return encodeURIComponent(c).replace(/%20/g,"+")},i=function(c){return decodeURIComponent(String(c).replace(/\+/g," "))},a=function(){var c=function(p){Object.defineProperty(this,"_entries",{writable:!0,value:{}});var m=typeof p;if(m!=="undefined")if(m==="string")p!==""&&this._fromString(p);else if(p instanceof c){var d=this;p.forEach(function(re,z){d.append(z,re)})}else if(p!==null&&m==="object")if(Object.prototype.toString.call(p)==="[object Array]")for(var h=0;hd[0]?1:0}),c._entries&&(c._entries={});for(var p=0;p1?i(d[1]):"")}})})(typeof global!="undefined"?global:typeof window!="undefined"?window:typeof self!="undefined"?self:Sr);(function(e){var t=function(){try{var o=new e.URL("b","http://a");return o.pathname="c d",o.href==="http://a/c%20d"&&o.searchParams}catch(i){return!1}},r=function(){var o=e.URL,i=function(f,c){typeof f!="string"&&(f=String(f)),c&&typeof c!="string"&&(c=String(c));var u=document,p;if(c&&(e.location===void 0||c!==e.location.href)){c=c.toLowerCase(),u=document.implementation.createHTMLDocument(""),p=u.createElement("base"),p.href=c,u.head.appendChild(p);try{if(p.href.indexOf(c)!==0)throw new Error(p.href)}catch(T){throw new Error("URL unable to set base "+c+" due to "+T)}}var m=u.createElement("a");m.href=f,p&&(u.body.appendChild(m),m.href=m.href);var d=u.createElement("input");if(d.type="url",d.value=f,m.protocol===":"||!/:/.test(m.href)||!d.checkValidity()&&!c)throw new TypeError("Invalid URL");Object.defineProperty(this,"_anchorElement",{value:m});var h=new e.URLSearchParams(this.search),v=!0,B=!0,re=this;["append","delete","set"].forEach(function(T){var Ke=h[T];h[T]=function(){Ke.apply(h,arguments),v&&(B=!1,re.search=h.toString(),B=!0)}}),Object.defineProperty(this,"searchParams",{value:h,enumerable:!0});var z=void 0;Object.defineProperty(this,"_updateSearchParams",{enumerable:!1,configurable:!1,writable:!1,value:function(){this.search!==z&&(z=this.search,B&&(v=!1,this.searchParams._fromString(this.search),v=!0))}})},a=i.prototype,s=function(f){Object.defineProperty(a,f,{get:function(){return this._anchorElement[f]},set:function(c){this._anchorElement[f]=c},enumerable:!0})};["hash","host","hostname","port","protocol"].forEach(function(f){s(f)}),Object.defineProperty(a,"search",{get:function(){return this._anchorElement.search},set:function(f){this._anchorElement.search=f,this._updateSearchParams()},enumerable:!0}),Object.defineProperties(a,{toString:{get:function(){var f=this;return function(){return f.href}}},href:{get:function(){return this._anchorElement.href.replace(/\?$/,"")},set:function(f){this._anchorElement.href=f,this._updateSearchParams()},enumerable:!0},pathname:{get:function(){return this._anchorElement.pathname.replace(/(^\/?)/,"/")},set:function(f){this._anchorElement.pathname=f},enumerable:!0},origin:{get:function(){var f={"http:":80,"https:":443,"ftp:":21}[this._anchorElement.protocol],c=this._anchorElement.port!=f&&this._anchorElement.port!=="";return this._anchorElement.protocol+"//"+this._anchorElement.hostname+(c?":"+this._anchorElement.port:"")},enumerable:!0},password:{get:function(){return""},set:function(f){},enumerable:!0},username:{get:function(){return""},set:function(f){},enumerable:!0}}),i.createObjectURL=function(f){return o.createObjectURL.apply(o,arguments)},i.revokeObjectURL=function(f){return o.revokeObjectURL.apply(o,arguments)},e.URL=i};if(t()||r(),e.location!==void 0&&!("origin"in e.location)){var n=function(){return e.location.protocol+"//"+e.location.hostname+(e.location.port?":"+e.location.port:"")};try{Object.defineProperty(e.location,"origin",{get:n,enumerable:!0})}catch(o){setInterval(function(){e.location.origin=n()},100)}}})(typeof global!="undefined"?global:typeof window!="undefined"?window:typeof self!="undefined"?self:Sr)});var Qr=Ht((Lt,Kr)=>{/*! + * clipboard.js v2.0.11 + * https://clipboardjs.com/ + * + * Licensed MIT © Zeno Rocha + */(function(t,r){typeof Lt=="object"&&typeof Kr=="object"?Kr.exports=r():typeof define=="function"&&define.amd?define([],r):typeof Lt=="object"?Lt.ClipboardJS=r():t.ClipboardJS=r()})(Lt,function(){return function(){var e={686:function(n,o,i){"use strict";i.d(o,{default:function(){return ki}});var a=i(279),s=i.n(a),f=i(370),c=i.n(f),u=i(817),p=i.n(u);function m(j){try{return document.execCommand(j)}catch(O){return!1}}var d=function(O){var w=p()(O);return m("cut"),w},h=d;function v(j){var O=document.documentElement.getAttribute("dir")==="rtl",w=document.createElement("textarea");w.style.fontSize="12pt",w.style.border="0",w.style.padding="0",w.style.margin="0",w.style.position="absolute",w.style[O?"right":"left"]="-9999px";var k=window.pageYOffset||document.documentElement.scrollTop;return w.style.top="".concat(k,"px"),w.setAttribute("readonly",""),w.value=j,w}var B=function(O,w){var k=v(O);w.container.appendChild(k);var F=p()(k);return m("copy"),k.remove(),F},re=function(O){var w=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{container:document.body},k="";return typeof O=="string"?k=B(O,w):O instanceof HTMLInputElement&&!["text","search","url","tel","password"].includes(O==null?void 0:O.type)?k=B(O.value,w):(k=p()(O),m("copy")),k},z=re;function T(j){return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?T=function(w){return typeof w}:T=function(w){return w&&typeof Symbol=="function"&&w.constructor===Symbol&&w!==Symbol.prototype?"symbol":typeof w},T(j)}var Ke=function(){var O=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},w=O.action,k=w===void 0?"copy":w,F=O.container,q=O.target,Le=O.text;if(k!=="copy"&&k!=="cut")throw new Error('Invalid "action" value, use either "copy" or "cut"');if(q!==void 0)if(q&&T(q)==="object"&&q.nodeType===1){if(k==="copy"&&q.hasAttribute("disabled"))throw new Error('Invalid "target" attribute. Please use "readonly" instead of "disabled" attribute');if(k==="cut"&&(q.hasAttribute("readonly")||q.hasAttribute("disabled")))throw new Error(`Invalid "target" attribute. You can't cut text from elements with "readonly" or "disabled" attributes`)}else throw new Error('Invalid "target" value, use a valid Element');if(Le)return z(Le,{container:F});if(q)return k==="cut"?h(q):z(q,{container:F})},We=Ke;function Ie(j){return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Ie=function(w){return typeof w}:Ie=function(w){return w&&typeof Symbol=="function"&&w.constructor===Symbol&&w!==Symbol.prototype?"symbol":typeof w},Ie(j)}function Ti(j,O){if(!(j instanceof O))throw new TypeError("Cannot call a class as a function")}function nn(j,O){for(var w=0;w0&&arguments[0]!==void 0?arguments[0]:{};this.action=typeof F.action=="function"?F.action:this.defaultAction,this.target=typeof F.target=="function"?F.target:this.defaultTarget,this.text=typeof F.text=="function"?F.text:this.defaultText,this.container=Ie(F.container)==="object"?F.container:document.body}},{key:"listenClick",value:function(F){var q=this;this.listener=c()(F,"click",function(Le){return q.onClick(Le)})}},{key:"onClick",value:function(F){var q=F.delegateTarget||F.currentTarget,Le=this.action(q)||"copy",Rt=We({action:Le,container:this.container,target:this.target(q),text:this.text(q)});this.emit(Rt?"success":"error",{action:Le,text:Rt,trigger:q,clearSelection:function(){q&&q.focus(),window.getSelection().removeAllRanges()}})}},{key:"defaultAction",value:function(F){return yr("action",F)}},{key:"defaultTarget",value:function(F){var q=yr("target",F);if(q)return document.querySelector(q)}},{key:"defaultText",value:function(F){return yr("text",F)}},{key:"destroy",value:function(){this.listener.destroy()}}],[{key:"copy",value:function(F){var q=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{container:document.body};return z(F,q)}},{key:"cut",value:function(F){return h(F)}},{key:"isSupported",value:function(){var F=arguments.length>0&&arguments[0]!==void 0?arguments[0]:["copy","cut"],q=typeof F=="string"?[F]:F,Le=!!document.queryCommandSupported;return q.forEach(function(Rt){Le=Le&&!!document.queryCommandSupported(Rt)}),Le}}]),w}(s()),ki=Ri},828:function(n){var o=9;if(typeof Element!="undefined"&&!Element.prototype.matches){var i=Element.prototype;i.matches=i.matchesSelector||i.mozMatchesSelector||i.msMatchesSelector||i.oMatchesSelector||i.webkitMatchesSelector}function a(s,f){for(;s&&s.nodeType!==o;){if(typeof s.matches=="function"&&s.matches(f))return s;s=s.parentNode}}n.exports=a},438:function(n,o,i){var a=i(828);function s(u,p,m,d,h){var v=c.apply(this,arguments);return u.addEventListener(m,v,h),{destroy:function(){u.removeEventListener(m,v,h)}}}function f(u,p,m,d,h){return typeof u.addEventListener=="function"?s.apply(null,arguments):typeof m=="function"?s.bind(null,document).apply(null,arguments):(typeof u=="string"&&(u=document.querySelectorAll(u)),Array.prototype.map.call(u,function(v){return s(v,p,m,d,h)}))}function c(u,p,m,d){return function(h){h.delegateTarget=a(h.target,p),h.delegateTarget&&d.call(u,h)}}n.exports=f},879:function(n,o){o.node=function(i){return i!==void 0&&i instanceof HTMLElement&&i.nodeType===1},o.nodeList=function(i){var a=Object.prototype.toString.call(i);return i!==void 0&&(a==="[object NodeList]"||a==="[object HTMLCollection]")&&"length"in i&&(i.length===0||o.node(i[0]))},o.string=function(i){return typeof i=="string"||i instanceof String},o.fn=function(i){var a=Object.prototype.toString.call(i);return a==="[object Function]"}},370:function(n,o,i){var a=i(879),s=i(438);function f(m,d,h){if(!m&&!d&&!h)throw new Error("Missing required arguments");if(!a.string(d))throw new TypeError("Second argument must be a String");if(!a.fn(h))throw new TypeError("Third argument must be a Function");if(a.node(m))return c(m,d,h);if(a.nodeList(m))return u(m,d,h);if(a.string(m))return p(m,d,h);throw new TypeError("First argument must be a String, HTMLElement, HTMLCollection, or NodeList")}function c(m,d,h){return m.addEventListener(d,h),{destroy:function(){m.removeEventListener(d,h)}}}function u(m,d,h){return Array.prototype.forEach.call(m,function(v){v.addEventListener(d,h)}),{destroy:function(){Array.prototype.forEach.call(m,function(v){v.removeEventListener(d,h)})}}}function p(m,d,h){return s(document.body,m,d,h)}n.exports=f},817:function(n){function o(i){var a;if(i.nodeName==="SELECT")i.focus(),a=i.value;else if(i.nodeName==="INPUT"||i.nodeName==="TEXTAREA"){var s=i.hasAttribute("readonly");s||i.setAttribute("readonly",""),i.select(),i.setSelectionRange(0,i.value.length),s||i.removeAttribute("readonly"),a=i.value}else{i.hasAttribute("contenteditable")&&i.focus();var f=window.getSelection(),c=document.createRange();c.selectNodeContents(i),f.removeAllRanges(),f.addRange(c),a=f.toString()}return a}n.exports=o},279:function(n){function o(){}o.prototype={on:function(i,a,s){var f=this.e||(this.e={});return(f[i]||(f[i]=[])).push({fn:a,ctx:s}),this},once:function(i,a,s){var f=this;function c(){f.off(i,c),a.apply(s,arguments)}return c._=a,this.on(i,c,s)},emit:function(i){var a=[].slice.call(arguments,1),s=((this.e||(this.e={}))[i]||[]).slice(),f=0,c=s.length;for(f;f{"use strict";/*! + * escape-html + * Copyright(c) 2012-2013 TJ Holowaychuk + * Copyright(c) 2015 Andreas Lubbe + * Copyright(c) 2015 Tiancheng "Timothy" Gu + * MIT Licensed + */var is=/["'&<>]/;Jo.exports=as;function as(e){var t=""+e,r=is.exec(t);if(!r)return t;var n,o="",i=0,a=0;for(i=r.index;i0&&i[i.length-1])&&(c[0]===6||c[0]===2)){r=0;continue}if(c[0]===3&&(!i||c[1]>i[0]&&c[1]=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function W(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),o,i=[],a;try{for(;(t===void 0||t-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i}function D(e,t,r){if(r||arguments.length===2)for(var n=0,o=t.length,i;n1||s(m,d)})})}function s(m,d){try{f(n[m](d))}catch(h){p(i[0][3],h)}}function f(m){m.value instanceof Xe?Promise.resolve(m.value.v).then(c,u):p(i[0][2],m)}function c(m){s("next",m)}function u(m){s("throw",m)}function p(m,d){m(d),i.shift(),i.length&&s(i[0][0],i[0][1])}}function mn(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t=e[Symbol.asyncIterator],r;return t?t.call(e):(e=typeof xe=="function"?xe(e):e[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(i){r[i]=e[i]&&function(a){return new Promise(function(s,f){a=e[i](a),o(s,f,a.done,a.value)})}}function o(i,a,s,f){Promise.resolve(f).then(function(c){i({value:c,done:s})},a)}}function A(e){return typeof e=="function"}function at(e){var t=function(n){Error.call(n),n.stack=new Error().stack},r=e(t);return r.prototype=Object.create(Error.prototype),r.prototype.constructor=r,r}var $t=at(function(e){return function(r){e(this),this.message=r?r.length+` errors occurred during unsubscription: +`+r.map(function(n,o){return o+1+") "+n.toString()}).join(` + `):"",this.name="UnsubscriptionError",this.errors=r}});function De(e,t){if(e){var r=e.indexOf(t);0<=r&&e.splice(r,1)}}var Fe=function(){function e(t){this.initialTeardown=t,this.closed=!1,this._parentage=null,this._finalizers=null}return e.prototype.unsubscribe=function(){var t,r,n,o,i;if(!this.closed){this.closed=!0;var a=this._parentage;if(a)if(this._parentage=null,Array.isArray(a))try{for(var s=xe(a),f=s.next();!f.done;f=s.next()){var c=f.value;c.remove(this)}}catch(v){t={error:v}}finally{try{f&&!f.done&&(r=s.return)&&r.call(s)}finally{if(t)throw t.error}}else a.remove(this);var u=this.initialTeardown;if(A(u))try{u()}catch(v){i=v instanceof $t?v.errors:[v]}var p=this._finalizers;if(p){this._finalizers=null;try{for(var m=xe(p),d=m.next();!d.done;d=m.next()){var h=d.value;try{dn(h)}catch(v){i=i!=null?i:[],v instanceof $t?i=D(D([],W(i)),W(v.errors)):i.push(v)}}}catch(v){n={error:v}}finally{try{d&&!d.done&&(o=m.return)&&o.call(m)}finally{if(n)throw n.error}}}if(i)throw new $t(i)}},e.prototype.add=function(t){var r;if(t&&t!==this)if(this.closed)dn(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=(r=this._finalizers)!==null&&r!==void 0?r:[]).push(t)}},e.prototype._hasParent=function(t){var r=this._parentage;return r===t||Array.isArray(r)&&r.includes(t)},e.prototype._addParent=function(t){var r=this._parentage;this._parentage=Array.isArray(r)?(r.push(t),r):r?[r,t]:t},e.prototype._removeParent=function(t){var r=this._parentage;r===t?this._parentage=null:Array.isArray(r)&&De(r,t)},e.prototype.remove=function(t){var r=this._finalizers;r&&De(r,t),t instanceof e&&t._removeParent(this)},e.EMPTY=function(){var t=new e;return t.closed=!0,t}(),e}();var Or=Fe.EMPTY;function It(e){return e instanceof Fe||e&&"closed"in e&&A(e.remove)&&A(e.add)&&A(e.unsubscribe)}function dn(e){A(e)?e():e.unsubscribe()}var Ae={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1};var st={setTimeout:function(e,t){for(var r=[],n=2;n0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(r){return this._throwIfClosed(),e.prototype._trySubscribe.call(this,r)},t.prototype._subscribe=function(r){return this._throwIfClosed(),this._checkFinalizedStatuses(r),this._innerSubscribe(r)},t.prototype._innerSubscribe=function(r){var n=this,o=this,i=o.hasError,a=o.isStopped,s=o.observers;return i||a?Or:(this.currentObservers=null,s.push(r),new Fe(function(){n.currentObservers=null,De(s,r)}))},t.prototype._checkFinalizedStatuses=function(r){var n=this,o=n.hasError,i=n.thrownError,a=n.isStopped;o?r.error(i):a&&r.complete()},t.prototype.asObservable=function(){var r=new U;return r.source=this,r},t.create=function(r,n){return new wn(r,n)},t}(U);var wn=function(e){ne(t,e);function t(r,n){var o=e.call(this)||this;return o.destination=r,o.source=n,o}return t.prototype.next=function(r){var n,o;(o=(n=this.destination)===null||n===void 0?void 0:n.next)===null||o===void 0||o.call(n,r)},t.prototype.error=function(r){var n,o;(o=(n=this.destination)===null||n===void 0?void 0:n.error)===null||o===void 0||o.call(n,r)},t.prototype.complete=function(){var r,n;(n=(r=this.destination)===null||r===void 0?void 0:r.complete)===null||n===void 0||n.call(r)},t.prototype._subscribe=function(r){var n,o;return(o=(n=this.source)===null||n===void 0?void 0:n.subscribe(r))!==null&&o!==void 0?o:Or},t}(E);var Et={now:function(){return(Et.delegate||Date).now()},delegate:void 0};var wt=function(e){ne(t,e);function t(r,n,o){r===void 0&&(r=1/0),n===void 0&&(n=1/0),o===void 0&&(o=Et);var i=e.call(this)||this;return i._bufferSize=r,i._windowTime=n,i._timestampProvider=o,i._buffer=[],i._infiniteTimeWindow=!0,i._infiniteTimeWindow=n===1/0,i._bufferSize=Math.max(1,r),i._windowTime=Math.max(1,n),i}return t.prototype.next=function(r){var n=this,o=n.isStopped,i=n._buffer,a=n._infiniteTimeWindow,s=n._timestampProvider,f=n._windowTime;o||(i.push(r),!a&&i.push(s.now()+f)),this._trimBuffer(),e.prototype.next.call(this,r)},t.prototype._subscribe=function(r){this._throwIfClosed(),this._trimBuffer();for(var n=this._innerSubscribe(r),o=this,i=o._infiniteTimeWindow,a=o._buffer,s=a.slice(),f=0;f0?e.prototype.requestAsyncId.call(this,r,n,o):(r.actions.push(this),r._scheduled||(r._scheduled=ut.requestAnimationFrame(function(){return r.flush(void 0)})))},t.prototype.recycleAsyncId=function(r,n,o){var i;if(o===void 0&&(o=0),o!=null?o>0:this.delay>0)return e.prototype.recycleAsyncId.call(this,r,n,o);var a=r.actions;n!=null&&((i=a[a.length-1])===null||i===void 0?void 0:i.id)!==n&&(ut.cancelAnimationFrame(n),r._scheduled=void 0)},t}(Ut);var On=function(e){ne(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.flush=function(r){this._active=!0;var n=this._scheduled;this._scheduled=void 0;var o=this.actions,i;r=r||o.shift();do if(i=r.execute(r.state,r.delay))break;while((r=o[0])&&r.id===n&&o.shift());if(this._active=!1,i){for(;(r=o[0])&&r.id===n&&o.shift();)r.unsubscribe();throw i}},t}(Wt);var we=new On(Tn);var R=new U(function(e){return e.complete()});function Dt(e){return e&&A(e.schedule)}function kr(e){return e[e.length-1]}function Qe(e){return A(kr(e))?e.pop():void 0}function Se(e){return Dt(kr(e))?e.pop():void 0}function Vt(e,t){return typeof kr(e)=="number"?e.pop():t}var pt=function(e){return e&&typeof e.length=="number"&&typeof e!="function"};function zt(e){return A(e==null?void 0:e.then)}function Nt(e){return A(e[ft])}function qt(e){return Symbol.asyncIterator&&A(e==null?void 0:e[Symbol.asyncIterator])}function Kt(e){return new TypeError("You provided "+(e!==null&&typeof e=="object"?"an invalid object":"'"+e+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function Ki(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var Qt=Ki();function Yt(e){return A(e==null?void 0:e[Qt])}function Gt(e){return ln(this,arguments,function(){var r,n,o,i;return Pt(this,function(a){switch(a.label){case 0:r=e.getReader(),a.label=1;case 1:a.trys.push([1,,9,10]),a.label=2;case 2:return[4,Xe(r.read())];case 3:return n=a.sent(),o=n.value,i=n.done,i?[4,Xe(void 0)]:[3,5];case 4:return[2,a.sent()];case 5:return[4,Xe(o)];case 6:return[4,a.sent()];case 7:return a.sent(),[3,2];case 8:return[3,10];case 9:return r.releaseLock(),[7];case 10:return[2]}})})}function Bt(e){return A(e==null?void 0:e.getReader)}function $(e){if(e instanceof U)return e;if(e!=null){if(Nt(e))return Qi(e);if(pt(e))return Yi(e);if(zt(e))return Gi(e);if(qt(e))return _n(e);if(Yt(e))return Bi(e);if(Bt(e))return Ji(e)}throw Kt(e)}function Qi(e){return new U(function(t){var r=e[ft]();if(A(r.subscribe))return r.subscribe(t);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function Yi(e){return new U(function(t){for(var r=0;r=2;return function(n){return n.pipe(e?_(function(o,i){return e(o,i,n)}):me,Oe(1),r?He(t):zn(function(){return new Xt}))}}function Nn(){for(var e=[],t=0;t=2,!0))}function fe(e){e===void 0&&(e={});var t=e.connector,r=t===void 0?function(){return new E}:t,n=e.resetOnError,o=n===void 0?!0:n,i=e.resetOnComplete,a=i===void 0?!0:i,s=e.resetOnRefCountZero,f=s===void 0?!0:s;return function(c){var u,p,m,d=0,h=!1,v=!1,B=function(){p==null||p.unsubscribe(),p=void 0},re=function(){B(),u=m=void 0,h=v=!1},z=function(){var T=u;re(),T==null||T.unsubscribe()};return g(function(T,Ke){d++,!v&&!h&&B();var We=m=m!=null?m:r();Ke.add(function(){d--,d===0&&!v&&!h&&(p=jr(z,f))}),We.subscribe(Ke),!u&&d>0&&(u=new et({next:function(Ie){return We.next(Ie)},error:function(Ie){v=!0,B(),p=jr(re,o,Ie),We.error(Ie)},complete:function(){h=!0,B(),p=jr(re,a),We.complete()}}),$(T).subscribe(u))})(c)}}function jr(e,t){for(var r=[],n=2;ne.next(document)),e}function K(e,t=document){return Array.from(t.querySelectorAll(e))}function V(e,t=document){let r=se(e,t);if(typeof r=="undefined")throw new ReferenceError(`Missing element: expected "${e}" to be present`);return r}function se(e,t=document){return t.querySelector(e)||void 0}function _e(){return document.activeElement instanceof HTMLElement&&document.activeElement||void 0}function tr(e){return L(b(document.body,"focusin"),b(document.body,"focusout")).pipe(ke(1),l(()=>{let t=_e();return typeof t!="undefined"?e.contains(t):!1}),N(e===_e()),Y())}function Be(e){return{x:e.offsetLeft,y:e.offsetTop}}function Yn(e){return L(b(window,"load"),b(window,"resize")).pipe(Ce(0,we),l(()=>Be(e)),N(Be(e)))}function rr(e){return{x:e.scrollLeft,y:e.scrollTop}}function dt(e){return L(b(e,"scroll"),b(window,"resize")).pipe(Ce(0,we),l(()=>rr(e)),N(rr(e)))}var Bn=function(){if(typeof Map!="undefined")return Map;function e(t,r){var n=-1;return t.some(function(o,i){return o[0]===r?(n=i,!0):!1}),n}return function(){function t(){this.__entries__=[]}return Object.defineProperty(t.prototype,"size",{get:function(){return this.__entries__.length},enumerable:!0,configurable:!0}),t.prototype.get=function(r){var n=e(this.__entries__,r),o=this.__entries__[n];return o&&o[1]},t.prototype.set=function(r,n){var o=e(this.__entries__,r);~o?this.__entries__[o][1]=n:this.__entries__.push([r,n])},t.prototype.delete=function(r){var n=this.__entries__,o=e(n,r);~o&&n.splice(o,1)},t.prototype.has=function(r){return!!~e(this.__entries__,r)},t.prototype.clear=function(){this.__entries__.splice(0)},t.prototype.forEach=function(r,n){n===void 0&&(n=null);for(var o=0,i=this.__entries__;o0},e.prototype.connect_=function(){!zr||this.connected_||(document.addEventListener("transitionend",this.onTransitionEnd_),window.addEventListener("resize",this.refresh),xa?(this.mutationsObserver_=new MutationObserver(this.refresh),this.mutationsObserver_.observe(document,{attributes:!0,childList:!0,characterData:!0,subtree:!0})):(document.addEventListener("DOMSubtreeModified",this.refresh),this.mutationEventsAdded_=!0),this.connected_=!0)},e.prototype.disconnect_=function(){!zr||!this.connected_||(document.removeEventListener("transitionend",this.onTransitionEnd_),window.removeEventListener("resize",this.refresh),this.mutationsObserver_&&this.mutationsObserver_.disconnect(),this.mutationEventsAdded_&&document.removeEventListener("DOMSubtreeModified",this.refresh),this.mutationsObserver_=null,this.mutationEventsAdded_=!1,this.connected_=!1)},e.prototype.onTransitionEnd_=function(t){var r=t.propertyName,n=r===void 0?"":r,o=ya.some(function(i){return!!~n.indexOf(i)});o&&this.refresh()},e.getInstance=function(){return this.instance_||(this.instance_=new e),this.instance_},e.instance_=null,e}(),Jn=function(e,t){for(var r=0,n=Object.keys(t);r0},e}(),Zn=typeof WeakMap!="undefined"?new WeakMap:new Bn,eo=function(){function e(t){if(!(this instanceof e))throw new TypeError("Cannot call a class as a function.");if(!arguments.length)throw new TypeError("1 argument required, but only 0 present.");var r=Ea.getInstance(),n=new Ra(t,r,this);Zn.set(this,n)}return e}();["observe","unobserve","disconnect"].forEach(function(e){eo.prototype[e]=function(){var t;return(t=Zn.get(this))[e].apply(t,arguments)}});var ka=function(){return typeof nr.ResizeObserver!="undefined"?nr.ResizeObserver:eo}(),to=ka;var ro=new E,Ha=I(()=>H(new to(e=>{for(let t of e)ro.next(t)}))).pipe(x(e=>L(Te,H(e)).pipe(C(()=>e.disconnect()))),J(1));function de(e){return{width:e.offsetWidth,height:e.offsetHeight}}function ge(e){return Ha.pipe(S(t=>t.observe(e)),x(t=>ro.pipe(_(({target:r})=>r===e),C(()=>t.unobserve(e)),l(()=>de(e)))),N(de(e)))}function bt(e){return{width:e.scrollWidth,height:e.scrollHeight}}function ar(e){let t=e.parentElement;for(;t&&(e.scrollWidth<=t.scrollWidth&&e.scrollHeight<=t.scrollHeight);)t=(e=t).parentElement;return t?e:void 0}var no=new E,Pa=I(()=>H(new IntersectionObserver(e=>{for(let t of e)no.next(t)},{threshold:0}))).pipe(x(e=>L(Te,H(e)).pipe(C(()=>e.disconnect()))),J(1));function sr(e){return Pa.pipe(S(t=>t.observe(e)),x(t=>no.pipe(_(({target:r})=>r===e),C(()=>t.unobserve(e)),l(({isIntersecting:r})=>r))))}function oo(e,t=16){return dt(e).pipe(l(({y:r})=>{let n=de(e),o=bt(e);return r>=o.height-n.height-t}),Y())}var cr={drawer:V("[data-md-toggle=drawer]"),search:V("[data-md-toggle=search]")};function io(e){return cr[e].checked}function qe(e,t){cr[e].checked!==t&&cr[e].click()}function je(e){let t=cr[e];return b(t,"change").pipe(l(()=>t.checked),N(t.checked))}function $a(e,t){switch(e.constructor){case HTMLInputElement:return e.type==="radio"?/^Arrow/.test(t):!0;case HTMLSelectElement:case HTMLTextAreaElement:return!0;default:return e.isContentEditable}}function Ia(){return L(b(window,"compositionstart").pipe(l(()=>!0)),b(window,"compositionend").pipe(l(()=>!1))).pipe(N(!1))}function ao(){let e=b(window,"keydown").pipe(_(t=>!(t.metaKey||t.ctrlKey)),l(t=>({mode:io("search")?"search":"global",type:t.key,claim(){t.preventDefault(),t.stopPropagation()}})),_(({mode:t,type:r})=>{if(t==="global"){let n=_e();if(typeof n!="undefined")return!$a(n,r)}return!0}),fe());return Ia().pipe(x(t=>t?R:e))}function Me(){return new URL(location.href)}function ot(e){location.href=e.href}function so(){return new E}function co(e,t){if(typeof t=="string"||typeof t=="number")e.innerHTML+=t.toString();else if(t instanceof Node)e.appendChild(t);else if(Array.isArray(t))for(let r of t)co(e,r)}function M(e,t,...r){let n=document.createElement(e);if(t)for(let o of Object.keys(t))typeof t[o]!="undefined"&&(typeof t[o]!="boolean"?n.setAttribute(o,t[o]):n.setAttribute(o,""));for(let o of r)co(n,o);return n}function fr(e){if(e>999){let t=+((e-950)%1e3>99);return`${((e+1e-6)/1e3).toFixed(t)}k`}else return e.toString()}function fo(){return location.hash.substring(1)}function uo(e){let t=M("a",{href:e});t.addEventListener("click",r=>r.stopPropagation()),t.click()}function Fa(){return b(window,"hashchange").pipe(l(fo),N(fo()),_(e=>e.length>0),J(1))}function po(){return Fa().pipe(l(e=>se(`[id="${e}"]`)),_(e=>typeof e!="undefined"))}function Nr(e){let t=matchMedia(e);return Zt(r=>t.addListener(()=>r(t.matches))).pipe(N(t.matches))}function lo(){let e=matchMedia("print");return L(b(window,"beforeprint").pipe(l(()=>!0)),b(window,"afterprint").pipe(l(()=>!1))).pipe(N(e.matches))}function qr(e,t){return e.pipe(x(r=>r?t():R))}function ur(e,t={credentials:"same-origin"}){return ve(fetch(`${e}`,t)).pipe(ce(()=>R),x(r=>r.status!==200?Tt(()=>new Error(r.statusText)):H(r)))}function Ue(e,t){return ur(e,t).pipe(x(r=>r.json()),J(1))}function mo(e,t){let r=new DOMParser;return ur(e,t).pipe(x(n=>n.text()),l(n=>r.parseFromString(n,"text/xml")),J(1))}function pr(e){let t=M("script",{src:e});return I(()=>(document.head.appendChild(t),L(b(t,"load"),b(t,"error").pipe(x(()=>Tt(()=>new ReferenceError(`Invalid script: ${e}`))))).pipe(l(()=>{}),C(()=>document.head.removeChild(t)),Oe(1))))}function ho(){return{x:Math.max(0,scrollX),y:Math.max(0,scrollY)}}function bo(){return L(b(window,"scroll",{passive:!0}),b(window,"resize",{passive:!0})).pipe(l(ho),N(ho()))}function vo(){return{width:innerWidth,height:innerHeight}}function go(){return b(window,"resize",{passive:!0}).pipe(l(vo),N(vo()))}function yo(){return Q([bo(),go()]).pipe(l(([e,t])=>({offset:e,size:t})),J(1))}function lr(e,{viewport$:t,header$:r}){let n=t.pipe(X("size")),o=Q([n,r]).pipe(l(()=>Be(e)));return Q([r,t,o]).pipe(l(([{height:i},{offset:a,size:s},{x:f,y:c}])=>({offset:{x:a.x-f,y:a.y-c+i},size:s})))}(()=>{function e(n,o){parent.postMessage(n,o||"*")}function t(...n){return n.reduce((o,i)=>o.then(()=>new Promise(a=>{let s=document.createElement("script");s.src=i,s.onload=a,document.body.appendChild(s)})),Promise.resolve())}var r=class{constructor(n){this.url=n,this.onerror=null,this.onmessage=null,this.onmessageerror=null,this.m=a=>{a.source===this.w&&(a.stopImmediatePropagation(),this.dispatchEvent(new MessageEvent("message",{data:a.data})),this.onmessage&&this.onmessage(a))},this.e=(a,s,f,c,u)=>{if(s===this.url.toString()){let p=new ErrorEvent("error",{message:a,filename:s,lineno:f,colno:c,error:u});this.dispatchEvent(p),this.onerror&&this.onerror(p)}};let o=new EventTarget;this.addEventListener=o.addEventListener.bind(o),this.removeEventListener=o.removeEventListener.bind(o),this.dispatchEvent=o.dispatchEvent.bind(o);let i=document.createElement("iframe");i.width=i.height=i.frameBorder="0",document.body.appendChild(this.iframe=i),this.w.document.open(),this.w.document.write(` + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + + +
+ + +
+ +
+ + + + + + + + + +
+
+ + + +
+
+
+ + + + + + +
+
+
+ + + + + + + +
+
+ + + + + + + + +

Classes and Objects

+

1. What is Object Oriented Programming, and why do we need it?

+

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
pen_colour = "red"
+pen_size = 0.5
+pen_kind = "ball"
+pen_owner = "John"
+
+# wouldn't you want a way to see the info about your pen? Lets write a function to do that!
+def display_information(colour, size, kind, owner):
+    print("Colour : " + colour)
+    print("Size   : " + str(size))
+    print("Kind   : " + kind)
+    print("Owner  : " + owner)
+    print()
+
+display_information(pen_colour, pen_size, pen_kind, pen_owner)
+
+Sure, that would work for one pen, but some questions one might have are:

+
    +
  1. What if you wanted to make an unknown number of pens? How would someone know how many variables to declare?
  2. +
  3. What if you had a more complicated object with 100 properties? Would it be feasable to manually declare 100 variables for every object that you might need to create?
  4. +
+

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!

+

2. What are classes, and why do we need them?

+

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
class Pen:
+
+    # remember the properties of the pen we discussed? A colour, a size, a kind, an owner
+
+    def __init__(pen, col, sz, knd, own):
+        pen.colour = col
+        pen.size = sz
+        pen.kind = knd
+        pen.owner = own
+
+    # This special function __init__ is known as a constructor, this is the "method" by which the object will be "constructed",
+    # this is the essence of the blue-print!
+
+
+    # wouldn't you want a way to see the properties of a pen you made as well?
+    # you can write functions in a class that can work with the instances of the class. These functions are known as 'member
+    # functions' of the class or 'methods'.
+
+    # methods are always functions that work on objects of a specific class. A method cannot be used without an object
+
+    # All methods of a class are unique to that class, and cannot be used on objects from other classes!
+    # for example, you could have a method called read() that reads the contents of a text book but you
+    # cannot use that method on a pen, because it doesn't make sense to read a pen!
+    def display_information(pen):
+        print("Colour : " + pen.colour)
+        print("Size   : " + str(pen.size))
+        print("Kind   : " + pen.kind)
+        print("Owner  : " + pen.owner)
+        print()
+
+# But a class is just a blue-print for creating a pen, it tells us which properties a pen is supposed to have
+# But it is NOT the pen itself!
+# 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:
+
+A = Pen("red", 0.5, "marker", "John")
+# When we do this, python calls the constructor and says, hey constructor,
+# construct me a Pen with its colour as "red", its size as 0.5, its kind as "marker" and let its owner be "John"
+# this process of creating an object from its class is known as instantiation
+
+A.display_information()
+# display this marker's information
+
+# And now that we actually have a pen class, remember that we can make AS MANY pens as we want!
+B = Pen("blue", 0.1, "ball", "John")
+C = Pen("black", 0.2, "fountain", "Robin")
+D = Pen("red", 0.1, "gel", "Joe")
+E = Pen("green", 0.1, "gel", "Robert")
+
+# since a method works on a particular instance of a class, it must be called by using the dot operator, on that specific object.
+B.display_information()
+C.display_information()
+D.display_information()
+E.display_information()
+
+

3. Classes, conventionally

+

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
class Pen:
+
+    # typically, the object is called "self" in the functions that work with it
+    # it is also common to give the same names to the function parameters as the properties of the object itself
+    def __init__(self, colour, size, kind, owner):
+        self.colour = colour
+        self.size = size
+        self.kind = kind
+        self.owner = owner
+
+    def display_information(self):
+        print("Colour : " + self.colour)
+        print("Size   : " + str(self.size))
+        print("Kind   : " + self.kind)
+        print("Owner  : " + self.owner)
+        print()
+
+
+
+
+

Write a class that describes a bicycle object

+

Which properties should a bicycle object have?

+
    +
  1. Colour (red, blue, white, etc)
  2. +
  3. Material (steel, aluminum, plastic, wood, etc)
  4. +
  5. Size (small, medium, large)
  6. +
  7. Height of the seat (in m)
  8. +
  9. Gear ratio (1, 2.5, 4, etc)
  10. +
  11. Diameter of the wheels (in cm)
  12. +
  13. Does it have a basket
  14. +
  15. Does it have a Bell
  16. +
+

What functions should a bicycle have?

+
    +
  1. Change gear ratio
  2. +
  3. Adjust seat height
  4. +
+
+
+

Write a class that describes a bicycle object

+

Which properties should a bicycle object have?

+
    +
  1. Colour (red, blue, white, etc)
  2. +
  3. Material (steel, aluminum, plastic, wood, etc)
  4. +
  5. Size (small, medium, large)
  6. +
  7. Height of the seat (in m)
  8. +
  9. Gear ratio (1, 2.5, 4, etc)
  10. +
  11. Diameter of the wheels (in cm)
  12. +
  13. Does it have a basket
  14. +
  15. Does it have a Bell
  16. +
+

What functions should a bicycle have?

+
    +
  1. Change gear ratio
  2. +
  3. Adjust seat height
  4. +
+
 1
+ 2
+ 3
+ 4
+ 5
+ 6
+ 7
+ 8
+ 9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
class Bicycle:
+    def __init__(self,
+                 colour,
+                 mat,
+                 size,
+                 height,
+                 gear_ratio,
+                 diameter,
+                 has_basket,
+                 has_bell):
+        self.colour = colour
+        self.mat = mat
+        self.size = size
+        self.height = height
+        self.gear_ratio = gear_ratio
+        self.diameter = diameter
+        self.has_basket = has_basket
+        self.has_bell = has_bell
+
+    def change_gear(self, new_ratio):
+        self.gear_ratio = new_ratio
+
+    def change_height(self, new_height):
+        self.height = new_ratio
+
+
+
+
+

4. What makes classes so good?

+
    +
  1. Reusability: The same class can be used to make as many objects as you want
  2. +
  3. Modularity: The code becomes incredibly modular, and it is easy for a programmer to debug the code in case there are any bugs
  4. +
  5. Clarity of code: Due to the code being modular, it is easier for others to read and understand the code
  6. +
  7. Better organisation: The data can be clearly and neatly organised for more complex objects
  8. +
  9. +

    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!

    +
  10. +
+

5. An object can also have other objects as its properties

+
 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
class Pen:
+    def __init__(self, colour, size, kind, owner):
+        self.colour = colour
+        self.size = size
+        self.kind = kind
+        self.owner = owner
+    def display_information(self):
+        print("Colour : " + self.colour)
+        print("Size   : " + str(self.size))
+        print("Kind   : " + self.kind)
+        print("Owner  : " + self.owner)
+        print()
+class Pencil:
+    def __init__(self, colour, shade, owner):
+        self.colour = colour
+        self.shade = shade
+        self.owner = owner
+    def display_information(self):
+        print("Colour : " + self.colour)
+        print("Shade  : " + str(self.shade))
+        print("Owner  : " + self.owner)
+        print()
+
+class Stationary:
+    def __init__(self, pen, pencil):
+        self.pen = pen
+        self.pencil = pencil
+    def display_information(self):
+        print("The Pen: ")
+        self.pen.display_information()
+        print("The Pencil: ")
+        self.pencil.display_information()
+
+A = Stationary(Pen("blue", 0.1, "ball", "John"), Pencil("black", "HB", "John"))
+A.display_information()
+
+ + + + + + +
+
+ + +
+ + + +
+ + + +
+
+
+
+ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/css/style.css b/css/style.css new file mode 100644 index 0000000..080a274 --- /dev/null +++ b/css/style.css @@ -0,0 +1,110 @@ +.md-nav__link .md-nav__link--index, .md-nav--secondary .md-nav__title { background: unset !important; box-shadow: unset !important; } +.md-nav__link.md-nav__container { background: unset !important; box-shadow: unset !important; } + +@media screen { + [data-md-color-scheme=slate] { + --md-admonition-bg-color: #222222; + } +} + +.md-header { + box-shadow: 0px 0px 15px -5px #000000 !important; +} + +.md-tabs { + background-color: #bc4240 !important; + box-shadow: 0px 0px 15px -5px #000000 !important; +} + +h2 { + color: #BABABA !important; +} +h3, h4 { + color: #c0c0c0 !important; +} + +body { + background-color: #222222 !important; +} + +.highlighttable .linenos { + background-color: #111111 !important; +} + +.md-typeset code { + background-color: #111111 !important; +} + +.md-footer { + background-color: #111111; + z-index: 100; +} + +.md-footer-meta { + background-color: #000000; +} + +/* width */ +::-webkit-scrollbar { + width: 5px !important; +} + +/*Track */ +::-webkit-scrollbar-track { + background-color: transparent !important; +} + +/* Handle */ +::-webkit-scrollbar-thumb { + background: #5b5c67 !important; +} + +/* Handle on hover */ +::-webkit-scrollbar-thumb:hover { + background: #ff1947 !important; +} + +.admonition.abstract, +.admonition.bug, +.admonition.danger, +.admonition.example, +.admonition.failure, +.admonition.info, +.admonition.note, +.admonition.success, +.admonition.tip, +.admonition.question, +.admonition.quote, +.admonition.warning { + box-shadow: 3px 3px 5px 0px #111111; +} + +tr td, table { + border-width: 0 !important; +} + +tr th { + background-color:#ef5552 !important; + color: #000000; +} + +tr:nth-child(even) { + background-color: #2b2b2b !important; +} + +tr:nth-child(odd) { + background-color: #1E2021 !important; +} + +tr:hover { + background-color: #63696E !important; +} + + +table { + box-shadow: 3px 3px 5px 0px #111111; +} + +.arithmatex { + font-size: 1em; +} \ No newline at end of file diff --git a/flow_control/index.html b/flow_control/index.html new file mode 100644 index 0000000..1b6720c --- /dev/null +++ b/flow_control/index.html @@ -0,0 +1,961 @@ + + + + + + + + + + + + + + + + + + + + + + Flow Control - Introduction to Python Programming + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + + +
+ + +
+ +
+ + + + + + + + + +
+
+ + + +
+
+
+ + + + + + +
+
+
+ + + +
+
+
+ + + +
+
+
+ + + +
+
+ + + + + + + + +

Flow Control

+

There are two types of flow control statements supported by Python:

+

1. Conditionals

+

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.

+

1.1. The 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
a = 10
+b = 20
+# if(boolean expression / variable / constant)
+if b > a:
+    # if the above condition is true do:
+    print("does one thing")
+    print("b > a confirmed!")
+else:
+    # if the above condition is not true do:
+    print("does another thing")
+    print("b <= a confirmed!")
+

+

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
a = 10
+b = 20
+if b > a:
+    print("doesn't do anything if the conditon is false")
+
+

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
a = 10
+b = 20
+if b > a:
+    print("b > 20")
+elif b == 20: # elif is short for else if
+    print("b == 20")
+else:
+    print("no condition is true")
+
+

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
a = 10
+b = 20
+c = 30
+if a > b and a > c:
+    print("the maximum is a: "+a)
+else if b > c and b > a:
+    print("the maximum is b: "+b)
+else:
+    print("the maximum is c: "+c)
+

+
+
+
+

2. Loops

+

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:

+

2.1. The 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
a = 0
+while a < 10:
+    print("a = "+a)
+    a+=1
+
+
+
+
+

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
number = 1
+increase = 1
+while increase <= 15:
+    print("number = "+number)
+    number = number + increase
+    increase+=1
+
+
+
+
+

2.2. The 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 a in range(2, 23):
+    print("a = "+a)
+# prints numbers from 3 to 22
+
+# what if you wanted to go down from 10 to 0?
+# that is also possible:
+for a in range(10, 0):
+    print("a = "+a)
+
+# you can also define a step size:
+for a in range(10, 0, 3):
+    print("a = "+a)
+# similar to slicing
+

+

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
ls = [5, 3, 56, 23]
+
+for number in ls:
+    print(number)
+

+

With tuples: +

1
+2
+3
+4
my_tuple = (17, 32, 11, 64)
+
+for number in my_tuple:
+    print(number)
+

+

With dicts: +

1
+2
+3
+4
my_dict = {3.14: "pi", "pie": "is tasty!", "spongebob": "squarepants"}
+
+for key in my_dict:
+    print(key, my_dict[key])
+

+ + + + + + +
+
+ + +
+ + + +
+ + + +
+
+
+
+ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/functions/index.html b/functions/index.html new file mode 100644 index 0000000..9401946 --- /dev/null +++ b/functions/index.html @@ -0,0 +1,1023 @@ + + + + + + + + + + + + + + + + + + + + + + Functions - Introduction to Python Programming + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + + +
+ + +
+ +
+ + + + + + + + + +
+
+ + + +
+
+
+ + + + + + +
+
+
+ + + +
+
+
+ + + +
+
+
+ + + +
+
+ + + + + + + + +

Functions

+

1. What are functions and why do we need them?

+

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
list_of_numbers = [32, 88, 3, 48, 87, 22]
+maximum = list_of_numbers[0]
+
+for number in list_of_numbers:
+    if maximum < number:
+        maximum = number
+print(maximum)
+

+

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
# this line is known as the function prototype.
+# the variables inside the brackets are known as formal parameters or formal arguments
+def max_value(list_of_numbers):
+
+# the word 'def' is short for define. It means you are defining a function called 'max_value'
+
+# In python, it is a convention to write function names in 'snake case'
+# snake case means that the each word is in lower case, and separated by underscores.
+# Example: this_is_snake_case
+
+    maximum = list_of_numbers[0]
+
+    for number in list_of_numbers:
+        if maximum < number:
+            maximum = number
+
+    # the word 'return' here tells python that this function needs to give you back the value of 'maximum'
+    return maximum
+list1 = [32, 88, 3, 48, 87, 22]
+list2 = [44, 26, 56, 90, 12, 35]
+list3 = [96, 43, 30, 12, 37, 26]
+
+
+# this is known as a function call and the variables passed to the function are called actual parameters or actual arguments
+max1 = max_value(list1)
+max2 = max_value(list2)
+max3 = max_value(list3)
+
+print(max1)
+print(max2)
+print(max3)
+
+

A function does not have to necessarily return a value:

+

 1
+ 2
+ 3
+ 4
+ 5
+ 6
+ 7
+ 8
+ 9
+10
+11
def display_elements(a_list):
+    for element in a_list:
+        print(element)
+
+list1 = [32, 88, 3, 48, 87, 22]
+list2 = [44, 26, 56, 90, 12, 35]
+list3 = [96, 43, 30, 12, 37, 26]
+
+print(display_elements(list1))
+print(display_elements(list2))
+print(display_elements(list3))
+
+Output: +
 1
+ 2
+ 3
+ 4
+ 5
+ 6
+ 7
+ 8
+ 9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
32
+88
+3
+48
+87
+22
+None
+44
+26
+56
+90
+12
+35
+None
+96
+43
+30
+12
+37
+26
+None
+

+

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
def function(number):
+    return number*2
+    print(number/2)
+
+print(function(5))
+
+Output: +
1
10
+

+
+
+
+

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
def factorial(a):
+    facto = 1
+    for i in range(1, a+1):
+        facto*=i
+    return facto
+
+for number in range(1, 21):
+    print("the factorial of", number, "=", factorial(number))
+
+
+
+
+

2. Type Hints

+

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
# this tells the user than height is a float, weight
+# is an int and that this function is meant to return a float as well
+def calculateBMI(height: float, weight: int) -> float:
+    return weight/((height/100)**2)
+
+print(calculateBMI(182, 80))
+
+

3. What is recursion, and why do we need it?

+

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
def factorial(number):
+
+    # remember to write a base case!
+    # If you forget, you're program will be stuck
+    # in an infinite loop of recursion!
+    if number == 0:
+        return 1
+    # the recursive case:
+    return number*factorial(number-1)
+
+
+
+
+

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
def function(number):
+    if number >= 1:
+        print(number)
+        function(number-1)
+    print(number)
+
+function(3)
+
+

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
def function(number):
+    if number >= 1:
+        print(number)
+        function(number-1)
+    print(number)
+
+function(3)
+
+

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
def function(number):
+    if number >= 1:
+        print(number)
+        function(number-1)
+    print(number)
+
+function(3)
+
+

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
3
+2
+1
+0
+1
+2
+3
+
+
+
+
+ + + + + + +
+
+ + +
+ + + +
+ + + +
+
+
+
+ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/index.html b/index.html new file mode 100644 index 0000000..2b14c9b --- /dev/null +++ b/index.html @@ -0,0 +1,661 @@ + + + + + + + + + + + + + + + + + + + + What is Programming - Introduction to Python Programming + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + + +
+ + +
+ +
+ + + + + + + + + +
+
+ + + +
+
+
+ + + + + + +
+
+
+ + + +
+
+
+ + + +
+
+
+ + + +
+
+ + + + + + + + +

Introduction to Programming With Python

+

1. What is a program?

+

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

+

2. How do we Write a Program?

+

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!

+

3. Requirements

+
    +
  1. +

    Python:

    +

    To use python, you must install it first. Find the download here

    +
  2. +
  3. +

    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

    +
  4. +
+ + + + + + +
+
+ + +
+ + + +
+ + + +
+
+
+
+ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/inheritance/index.html b/inheritance/index.html new file mode 100644 index 0000000..01f2aac --- /dev/null +++ b/inheritance/index.html @@ -0,0 +1,1281 @@ + + + + + + + + + + + + + + + + + + + + Inheritance - Introduction to Python Programming + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + + +
+ + +
+ +
+ + + + + + + + + +
+
+ + + +
+
+
+ + + + + + +
+
+
+ + + +
+
+
+ + + +
+
+
+ + + +
+
+ + + + + + + + +

Inheritance

+

1. What is inheritance, and why do we need it?

+

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
class Person:
+    def __init__(self, name, age, sex, height, weight):
+        self.name = name
+        self.age = age
+        self.sex = sex
+        self.height = height
+        self.weight = weight
+
+    def display_information(self):
+        print("Name   : " + self.name)
+        print("Age    : " + str(self.age))
+        print("Sex    : " + self.sex)
+        print("Height : " + str(self.height))
+        print("Weight : " + str(self.weight))
+
+class Student1:
+    def __init__(self, person, school, id_no, seat_no, year, section):
+        self.person = person
+        self.school = school
+        self.id_no = id_no
+        self.seat_no = seat_no
+        self.year = year
+        self.section = section
+
+    def display_information(self):
+        self.person.display_information()
+        print("School  : " + self.school)
+        print("ID      : " + str(self.id_no))
+        print("Seat    : " + str(self.seat_no))
+        print("Year    : " + str(self.year))
+        print("Section : " + self.section)
+        print()
+
+
+A = Student1(Person("John", 15, "male", 160, 60), "SUTD", 1024, 32, 2, "A")
+
+print(A.person.name+"'s age: "+str(A.person.age))
+A.display_information()
+
+

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
# class Person here is unused, basically making the already existing class redundant
+class Person:
+    def __init__(self, name, age, sex, height, weight):
+        self.name = name
+        self.age = age
+        self.sex = sex
+        self.height = height
+        self.weight = weight
+
+    def display_information(self):
+        print("Name   : " + self.name)
+        print("Age    : " + str(self.age))
+        print("Sex    : " + self.sex)
+        print("Height : " + str(self.height))
+        print("Weight : " + str(self.weight))
+
+class Student2:
+    def __init__(self, name, age, sex, height, weight, school, id_no, seat_no, year, section):
+        self.name = name
+        self.age = age
+        self.sex = sex
+        self.height = height
+        self.weight = weight
+        self.school = school
+        self.id_no = id_no
+        self.seat_no = seat_no
+        self.year = year
+        self.section = section
+
+    def display_information(self):
+        print("Name   : " + self.name)
+        print("Age    : " + str(self.age))
+        print("Sex    : " + self.sex)
+        print("Height : " + str(self.height))
+        print("Weight : " + str(self.weight))
+        print("School  : " + self.school)
+        print("ID      : " + str(self.id_no))
+        print("Seat    : " + str(self.seat_no))
+        print("Year    : " + str(self.year))
+        print("Section : " + self.section)
+        print()
+
+# when there are a lot of function parameters, it is nice to specify which parameters correspond to what
+# values for better readability and clarity and put them each on their own line
+B = Student2(
+    name = "Robert", 
+    age = 14, 
+    sex = "male", 
+    height = 160, 
+    weight = 65, 
+    school = "SUTD", 
+    id_no = 1025, 
+    seat_no = 12, 
+    year = 1, 
+    section = "A",
+)
+print(B.name+"'s age: "+str(B.age))
+B.display_information()
+
+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)

+
 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
# Super/Parent class
+class Person:
+    def __init__(self, name, age, sex, height, weight):
+        self.name = name
+        self.age = age
+        self.sex = sex
+        self.height = height
+        self.weight = weight
+
+    def display_information(self):
+        print("Name   : " + self.name)
+        print("Age    : " + str(self.age))
+        print("Sex    : " + self.sex)
+        print("Height : " + str(self.height))
+        print("Weight : " + str(self.weight))
+
+# Base/Sub class
+class Student(Person):
+    def __init__(self, name, age, sex, height, weight, school, id_no, seat_no, year, section):
+        Person.__init__(self, name, age, sex, height, weight) # we can re-use functionality from the super class!
+        self.school = school
+        self.id_no = id_no
+        self.seat_no = seat_no
+        self.year = year
+        self.section = section
+
+    def display_information(self):
+        Person.display_information(self) # we can re-use functionality from the super class!
+        print("School  : " + self.school)
+        print("ID      : " + str(self.id_no))
+        print("Seat    : " + str(self.seat_no))
+        print("Year    : " + str(self.year))
+        print("Section : " + self.section)
+
+# when there are a lot of function parameters, it is nice to specify which parameters correspond to what
+# values for better readability and clarity and put them each on their own line
+A = Student(
+    name = "Robin", 
+    age = 16, 
+    sex = "male", 
+    height = 180, 
+    weight = 75, 
+    school = "SUTD", 
+    id_no = 1023, 
+    seat_no = 3, 
+    year = 3, 
+    section = "A",
+)
+print(A.name+"'s age: "+str(A.age))
+A.display_information()
+
+
+

Best practice

+

The following usages of super class methods in the above example: +

1
+2
+3
Person.__init__(self, name, age, sex, height, weight)
+
+Person.display_information(self)
+
+Are for educational purposes only, in real python programs, we should make use of the following syntax instead:

+

1
+2
+3
+4
# notice that the self parameter has been omitted
+super().__init__(name, age, sex, height, weight)
+
+super().display_information()
+
+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)

+
+
+
+
+

Given a class computer, Write a subclass laptop and desktop with the given additional properties:

+

A computer object has the following properties:

+
    +
  1. CPU Type
  2. +
  3. Storage Type
  4. +
  5. Storage Quantity (in GB)
  6. +
  7. RAM (in GB)
  8. +
  9. GPU Type
  10. +
+

Write a class for laptop and desktop objects that have the above properties, and the additional properties listed below:

+

Desktop:

+
    +
  1. Monitor
  2. +
  3. Monitor Resolution
  4. +
  5. Keyboard
  6. +
  7. Mouse
  8. +
+

Laptop:

+
    +
  1. Monitor Resolution
  2. +
  3. Is it a touchscreen?
  4. +
+

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
class Computer:
+    def __init__(
+        self,
+        cpu: str,
+        storage_type: str,
+        storage: float,
+        ram: float,
+        gpu: str,
+    ):
+
+        # type hints can also be given to a class' data members
+        self.cpu: str = cpu
+        self.storage_type: str = storage_type
+        self.storage: float = storage
+        self.ram: float = ram
+        self.gpu: str = gpu
+
+    def display_information(self):
+        print("The CPU type is     : "+self.cpu)
+        print("The Storage type is : "+self.storage_type)
+        print("The Stroage is      : "+str(self.storage))
+        print("The RAM is          : "+str(self.ram))
+        print("The GPU is          : "+self.gpu)
+
+
+
+

Given a class computer, Write a subclass laptop and desktop with the given additional properties:

+

A computer object has the following properties:

+
    +
  1. CPU Type
  2. +
  3. Storage Type
  4. +
  5. Storage Quantity (in GB)
  6. +
  7. RAM (in GB)
  8. +
  9. GPU Type
  10. +
+

Write a class for laptop and desktop objects that have the above properties, and the additional properties listed below:

+

Desktop:

+
    +
  1. Monitor
  2. +
  3. Monitor Resolution
  4. +
  5. Keyboard
  6. +
  7. Mouse
  8. +
+

Laptop:

+
    +
  1. Monitor Resolution
  2. +
  3. Is it a touchscreen?
  4. +
+

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
class Computer:
+    def __init__(
+        self,
+        cpu: str,
+        storage_type: str,
+        storage: float,
+        ram: float,
+        gpu: str,
+    ):
+
+        # type hints can also be given to a class' data members
+        self.cpu: str = cpu
+        self.storage_type: str = storage_type
+        self.storage: float = storage
+        self.ram: float = ram
+        self.gpu: str = gpu
+
+    def display_information(self):
+        print("The CPU type is     : "+self.cpu)
+        print("The Storage type is : "+self.storage_type)
+        print("The Stroage is      : "+str(self.storage))
+        print("The RAM is          : "+str(self.ram))
+        print("The GPU is          : "+self.gpu)
+
+

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
class Computer:
+    def __init__(
+        self,
+        cpu: str,
+        storage_type: str,
+        storage: float,
+        ram: float,
+        gpu: str,
+    ):
+
+        # type hints can also be given to a class' data members
+        self.cpu: str = cpu
+        self.storage_type: str = storage_type
+        self.storage: float = storage
+        self.ram: float = ram
+        self.gpu: str = gpu
+
+    def display_information(self):
+        print("The CPU type is     : "+self.cpu)
+        print("The Storage type is : "+self.storage_type)
+        print("The Stroage is      : "+str(self.storage))
+        print("The RAM is          : "+str(self.ram))
+        print("The GPU is          : "+self.gpu)
+
+class Laptop(Computer):
+    def __init__(
+        self,
+        cpu: str,
+        storage_type: str,
+        storage: float,
+        ram: float,
+        gpu: str,
+        resolution: str,
+        is_touchscreen: bool,
+    ):
+        super().__init__(cpu, storage_type, storage, ram, gpu)
+        self.resolution = resolution
+        self.is_touchscreen = is_touchscreen
+
+    def display_information(self):
+        super().display_information()
+        print("The resolution is   : "+self.resolution)
+        print("Is it a touchscreen : "+str(self.is_touchscreen))
+
+class Desktop(Computer):
+    def __init__(
+        self,
+        cpu: str,
+        storage_type: str,
+        storage: float,
+        ram: float,
+        gpu: str,
+        monitor: str,
+        resolution: str,
+        keyboard: str,
+        mouse: str,
+    ):
+        super().__init__(cpu, storage_type, storage, ram, gpu)
+        self.monitor = monitor
+        self.resolution = resolution
+        self.keyboard = keyboard
+        self.mouse = mouse
+
+    def display_information(self):
+        super().display_information()
+        print("The monitor is      : "+self.monitor)
+        print("The resolution is   : "+self.resolution)
+        print("The keyboard is     : "+self.keyboard)
+        print("The mouse is        : "+self.mouse)
+
+
+
+
+ + + + + + +
+
+ + +
+ + + +
+ + + +
+
+
+
+ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/js/maths.js b/js/maths.js new file mode 100644 index 0000000..8b1fc26 --- /dev/null +++ b/js/maths.js @@ -0,0 +1,12 @@ +window.MathJax = { + tex: { + inlineMath: [["\\(", "\\)"]], + displayMath: [["\\[", "\\]"]], + processEscapes: true, + processEnvironments: true, + }, + options: { + ignoreHtmlClass: ".*|", + processHtmlClass: "arithmatex", + }, +}; diff --git a/operations/index.html b/operations/index.html new file mode 100644 index 0000000..9874ce0 --- /dev/null +++ b/operations/index.html @@ -0,0 +1,1204 @@ + + + + + + + + + + + + + + + + + + + + + + Operations - Introduction to Python Programming + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + + +
+ + +
+ +
+ + + + + + + + + +
+
+ + + +
+
+
+ + + + + + +
+
+
+ + + + + + + +
+
+ + + + + + + + +

Operators

+

Now that we know how to store and change the values of a variable, what can we actually do with them?

+

1. Arithmetic Operators

+

The most obvious thing that we can do with numbers, is do arithmetic with them. Python supports the following arithmetic operations:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
OperatorNameExample
+Additiona+b
-Subtractiona-b
*Multiplicationa*b
/Divisiona/b
//Integer Divisiona//b
%Moduloa%b
**Exponentiationa**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.

+

2. Relational Operators

+

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.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
OperatorNameExample
<Less Thana<b
>Greater Thana>b
<=Less Than or Equal toa<=b
>=Greater Than or Equal toa>=b
==Equal toa==b
!=Not Equal toa!=b
+
    +
  1. 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.
  2. +
  3. 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.
  4. +
  5. 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.
  6. +
  7. 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.
  8. +
  9. 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.
  10. +
  11. 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.
  12. +
+

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
# with numbers:
+ a = 10
+ b = 20.0
+ c = 30
+
+# this would print True
+print("a < b is", a < b)
+
+# this would print False
+print("b > c is", b > c)
+
+# this would print True
+print("(a+b) == b is", (a+b) == b)
+
+# this would print True
+print("(a+b) >= c is", (a+b) >= c)
+
+# this would print True
+print("b <= c is", b <= c)
+
+
+# With Strings:
+str1 = "ball"
+str2 = "apple"
+str3 = "cat"
+str4 = "cat"
+
+# this would print False
+# this is because alphabetically, str1 does not come before str2
+print("str1 < str2 is", str1 < str2)
+
+# this would print False
+# this is because alphabetically, str2 comes before str3
+print("str3 > str2 is", str3 > str2)
+
+# this would print True
+print("str3 == str4 is", str3 == str4)
+
+# this would print True
+print("str1 != str2 is", str1 != str2)
+
+

3. Boolean Operators

+

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.

+

3.1. The Boolean AND

+

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:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
aba and b
FalseFalseFalse
FalseTrueFalse
TrueFalseFalse
TrueTrueTrue
+

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?

+

3.2. The Boolean OR

+

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:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
aba || b
FalseFalseFalse
FalseTrueTrue
TrueFalseTrue
TrueTrueTrue
+

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 Trueor 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
a = 10
+b = 20
+c = 30
+
+# this would print True on the screen
+# because both a < b and c > d are True
+print((a < b) and (c > b))
+
+# this would print False on the screen
+# because c < b is False
+print((a < b) and (c < b))
+
+# this would print True on the screen
+# because a < b is True
+print((a < b) or (c < b))
+
+# this would print False on the screen
+# because neither a > b nor  c < b is True
+print((a > b) or (c < b))
+

+

4. Membership Operators

+

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
print("water" in "this is a waterbottle")
+print("water" not in "this is a waterbottle")
+print("spongebob" in "squarepants")
+print("spongebob" not in "squarepants")
+
+# they also work on lists, tuples and dicts:
+
+print(5 in [5, 3, 1, 2, 7])
+print(11 not in [1, 2, 6, 7])
+
+print(17 in (15, 12, 16, 19, 17))
+print(16 not in (14, 17, 11, 21))
+
+# for dicts, it checks if a certain key is present in the dict
+print(3.14 in {3.14: "pi"})
+print(5 in {3.14: "pi"})
+
+

5. The Assignment Operation

+

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.

+

6. Shorthand Assignment Operators

+

Shorthand assignment operators allow us to assign values to variables:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
OperatorNameExampleNon Short Hand Equivalent
+=Additiona+=ba = a+b
-=Subtractiona-=ba = a-b
*=Multiplicationa*=ba = a*b
/=Divisiona/=ba = a/b
//=Integer Divisiona//=ba = a//b
%=Moduloa%=ba = a%b
**=Exponentiationa**=ba = 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.

+ + + + + + +
+
+ + +
+ + + +
+ + + +
+
+
+
+ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/search/search_index.json b/search/search_index.json new file mode 100644 index 0000000..45e0a10 --- /dev/null +++ b/search/search_index.json @@ -0,0 +1 @@ +{"config":{"lang":["en"],"separator":"[\\s\\-\\.\\_]+","pipeline":["stopWordFilter"]},"docs":[{"location":"","title":"Introduction to Programming With Python","text":""},{"location":"#1-what-is-a-program","title":"1. What is a program?","text":"

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":"
  1. Python:

    To use python, you must install it first. Find the download here

  2. 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

"},{"location":"arguments/","title":"Different types of arguments","text":"

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!

"},{"location":"arguments/#4-keword-arguments","title":"4. Keword Arguments","text":"

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

"},{"location":"arguments/#5-arbitrary-argumentsargs","title":"5. Arbitrary Arguments(*args)","text":"

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:

  1. What if you wanted to make an unknown number of pens? How would someone know how many variables to declare?
  2. What if you had a more complicated object with 100 properties? Would it be feasable to manually declare 100 variables for every object that you might need to create?

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?

  1. Colour (red, blue, white, etc)
  2. Material (steel, aluminum, plastic, wood, etc)
  3. Size (small, medium, large)
  4. Height of the seat (in m)
  5. Gear ratio (1, 2.5, 4, etc)
  6. Diameter of the wheels (in cm)
  7. Does it have a basket
  8. Does it have a Bell

What functions should a bicycle have?

  1. Change gear ratio
  2. Adjust seat height

Write a class that describes a bicycle object

Which properties should a bicycle object have?

  1. Colour (red, blue, white, etc)
  2. Material (steel, aluminum, plastic, wood, etc)
  3. Size (small, medium, large)
  4. Height of the seat (in m)
  5. Gear ratio (1, 2.5, 4, etc)
  6. Diameter of the wheels (in cm)
  7. Does it have a basket
  8. Does it have a Bell

What functions should a bicycle have?

  1. Change gear ratio
  2. Adjust seat height
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":"
  1. Reusability: The same class can be used to make as many objects as you want
  2. Modularity: The code becomes incredibly modular, and it is easy for a programmer to debug the code in case there are any bugs
  3. Clarity of code: Due to the code being modular, it is easier for others to read and understand the code
  4. Better organisation: The data can be clearly and neatly organised for more complex objects
  5. 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!

"},{"location":"classes_objects/#5-an-object-can-also-have-other-objects-as-its-properties","title":"5. An object can also have other objects as its properties","text":"
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. The if 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.

PractiseAnswer

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.

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. The while 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:

  1. CPU Type
  2. Storage Type
  3. Storage Quantity (in GB)
  4. RAM (in GB)
  5. GPU Type

Write a class for laptop and desktop objects that have the above properties, and the additional properties listed below:

Desktop:

  1. Monitor
  2. Monitor Resolution
  3. Keyboard
  4. Mouse

Laptop:

  1. Monitor Resolution
  2. Is it a touchscreen?

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:

  1. CPU Type
  2. Storage Type
  3. Storage Quantity (in GB)
  4. RAM (in GB)
  5. GPU Type

Write a class for laptop and desktop objects that have the above properties, and the additional properties listed below:

Desktop:

  1. Monitor
  2. Monitor Resolution
  3. Keyboard
  4. Mouse

Laptop:

  1. Monitor Resolution
  2. Is it a touchscreen?

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.

"},{"location":"operations/#2-relational-operators","title":"2. Relational Operators","text":"

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
  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
  6. 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:

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?

"},{"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:

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 Trueor 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.

"},{"location":"operations/#6-shorthand-assignment-operators","title":"6. Shorthand Assignment Operators","text":"

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.

"},{"location":"vars/#2-variables","title":"2. Variables","text":"

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

"},{"location":"vars/#32-floating-point-float","title":"3.2. Floating Point (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

"},{"location":"vars/#33-boolean-bool","title":"3.3. Boolean (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.

"},{"location":"vars/#34-string-str","title":"3.4. String (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:

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:

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:

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:

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:

  1. You can only use letters, numbers and underscores to name your variables.

  2. A variable name cannot start with a number.

  3. Variable names are CaSe SeNsItIvE. This means that a and A are two different variable names!

  4. 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.

  1. 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\".

  2. 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\".

  3. 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.

  4. 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.

"}]} \ No newline at end of file diff --git a/sitemap.xml b/sitemap.xml new file mode 100644 index 0000000..3e1de05 --- /dev/null +++ b/sitemap.xml @@ -0,0 +1,43 @@ + + + + None + 2023-10-25 + daily + + + None + 2023-10-25 + daily + + + None + 2023-10-25 + daily + + + None + 2023-10-25 + daily + + + None + 2023-10-25 + daily + + + None + 2023-10-25 + daily + + + None + 2023-10-25 + daily + + + None + 2023-10-25 + daily + + \ No newline at end of file diff --git a/sitemap.xml.gz b/sitemap.xml.gz new file mode 100644 index 0000000..94fffcd Binary files /dev/null and b/sitemap.xml.gz differ diff --git a/vars/index.html b/vars/index.html new file mode 100644 index 0000000..ae0902f --- /dev/null +++ b/vars/index.html @@ -0,0 +1,1360 @@ + + + + + + + + + + + + + + + + + + + + + + Variables - Introduction to Python Programming + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + + +
+ + +
+ +
+ + + + + + + + + +
+
+ + + +
+
+
+ + + + + + +
+
+
+ + + + + + + +
+
+ + + + + + + + +

Python Basics

+

1. Constants

+

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.

+

2. Variables

+

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
# creating and storing a value in a variable
+# is known as variable initialisation
+
+a = 10
+b = 20.5
+c = a+b
+
+# a, b and c are the names of the variables here.
+
+# to be able to see the value of a variable,
+# we need to print it to the screen
+print(c)
+
+# you can change a variable simply by re-assigning another value to it:
+c = a-b
+print(c)
+
+

You can also store sentences, words:

+
1
+2
a = "this is a string"
+print(a)
+
+

You can store lists as well:

+
1
+2
ls = [1, 4.5, "python is awesome!"]
+print(ls)
+
+

3. Data Types

+

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:

+

3.1. Integer (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

+

3.2. Floating Point (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

+

3.3. Boolean (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.

+

3.4. String (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
a = """this is
+a multiple line
+string"""
+
+print(a)
+
+b = '''this is
+another multiple line
+string'''
+
+print(b)
+
+

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
a = "python is awesome"
+print(a[0])
+# this will give you the first letter of the string
+# in any programming language in general,
+# when we number items, we always start at 0 and not 1
+
+
+# in python, you can actually use a negative index:
+print(a[-1])
+# and this gives you the last character of a.
+
+

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
b = "this is known as slicing"
+print(b[4:8])
+# this will give you a string that starts from the
+# 5th character of b and ends at the 9th character.
+# Note that the 9th letter is not included in this new sliced string
+# result: " is k"
+
+print(b[3:])
+# this will give you a string that starts from the 4th character of b
+# result: "s is known as slicing"
+
+print(b[:5])
+# this will give you a string that ends at the 6th character of b.
+# Note that the 6th character is not included in this new sliced string
+# result: "s is known as slicing"
+
+print(b[2:10:3])
+# this will give you a string that starts from the 
+# 3rd character of b and ends at the 11th character.
+# Note Only the every 3rd character is selected, starting from the first.
+# result: "iik"
+
+print(b[::-1])
+# this will give you a string that is the reverse of the original!
+# result: "gnicils sa nwonk si siht"
+
+print(len(b))
+# gives you the length of the string
+
+

You can also join two or more strings togethere: +

1
+2
+3
+4
a = "this is "
+b = "known as string"
+c = " concatenation!"
+print(a+b+c)
+

+

What would happen if you tried to access a poition of the string that is greater than its length?

+
1
+2
+3
+4
a = "this is a string"
+print(a[20])
+# the string does not have a 21st character,
+# you will get an error if you try this!
+
+

3.5. List (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
a = [2, 3.4, "this is a list", True, ["this list is inside the first one", ":O"]]
+

+

This declares a variable of type list called a with the following values:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
IndexValue
02
13.4
2"this is a list"
3True
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
a = [
+        2,
+        3.4,
+        "this is a list",
+        True,
+        ["this list is inside the first one", ":O"]
+    ]
+
+

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
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, [10, 20, 30]]
+print(a[0])
+# this will give you the first element of the list
+
+print(a[-1])
+# and this gives you the last element of this (this is a list in itself)
+
+print(a[4:8])
+# slicing also works exactly like strings.
+# this will give you a list starting from the
+# 5th element all the way to the 9th element.
+
+print(len(a))
+# this gives you the number of elements in a list.
+
+# you can change any element of the list like so:
+a[2] = 55
+
+# change the 2nd element of the last element of the list
+a[-1][1] = 22
+

+

you can combine lists as follows:

+
1
+2
+3
+4
+5
a = [1, 2]
+b = [3, 4]
+c = [5, 6]
+
+print(a+b+c)
+
+

you can add an element to a list using the append function:

+
1
+2
+3
a = [1, 2]
+a.append(3)
+print(a)
+
+

you can extend a list using another list by using the extend function:

+
1
+2
+3
+4
a = [1, 2]
+b = [3, 4]
+a.extend(b)
+print(a)
+
+

What would happen if you tried to access an element of the list whoes index is greater than the length?

+
1
+2
+3
+4
a = "this is a string"
+print(a[20])
+# the string does not have a 21st character,
+# you will get an error if you try this!
+
+

3.6. Tuple (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
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"])
+

+

Similar to a list, it is common to break up a long tuple over multiple lines:

+
1
+2
+3
+4
+5
+6
+7
+8
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"]
+    )
+
+

This declares a variable of type tuple called a with the following values:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
IndexValue
02
13.4
2"this is a tuple"
3True
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
a = (1, 2, (3, 4, 5), [1, 2, 3])
+print(a[0])
+# this will give you the first element of the tuple
+
+print(a[-1])
+# and this gives you the last element of this tuple
+
+print(a[0:3])
+# slicing also works on tuples.
+# this will give you a tuple starting from the 
+# first element all the way to the 3rd element.
+
+# note that you cannot change the elements of a tuple.
+# trying to do that will get you an error
+
+# however, you CAN change a list inside a tuple.
+a[-1][2] = 10
+
+

3.7. Dictionary (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
a = {
+        "this is a key": "this is it's value",
+        3.14: "pie",
+        4: "2x2",
+        (2, 3): "a tuple!"
+    }
+

+

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
a = {
+        "this is a key": "this is it's value",
+        3.14: "pie",
+        4: "2x2",
+        (2, 3): "a tuple!"
+    }
+print(a["this is a key"])
+print(a[3.14])
+print(a[4])
+print(a[(2, 3)])
+
+# Similar to a list or tuple, you will get an
+# error from python if you try to access a key
+# that is not present in a dictionary
+
+# you can also use the get function to get values:
+print(a.get(3.14))
+
+# you can actually specify a default value when using get
+# this is, in case the key is not in the dictionary,
+# then use the default value instead!
+
+print(a.get(22, "not found"))
+
+
 1
+ 2
+ 3
+ 4
+ 5
+ 6
+ 7
+ 8
+ 9
+10
+11
+12
+13
+14
+15
+16
+17
a = "this is a string"
+print(type(a))
+
+a = 2.2
+print(type(a))
+
+a = [1, 2]
+print(type(a))
+
+a = 2
+print(type(a))
+
+a = (4, 5)
+print(type(a))
+
+a = True
+print(type(a))
+
+

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.

+

4. Variable Naming Rules and Conventions:

+

There are some rules that must be followed when naming a variable. They are:

+
    +
  1. +

    You can only use letters, numbers and underscores to name your variables.

    +
  2. +
  3. +

    A variable name cannot start with a number.

    +
  4. +
  5. +

    Variable names are CaSe SeNsItIvE. This means that a and A are two different variable names!

    +
  6. +
  7. +

    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.

    +
  8. +
+

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.

+
    +
  1. +

    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".

    +
  2. +
  3. +

    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".

    +
  4. +
  5. +

    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.

    +
  6. +
  7. +

    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.

    +
  8. +
+ + + + + + +
+
+ + +
+ + + +
+ + + +
+
+
+
+ + + + + + + + + + + + + + + \ No newline at end of file