Skip to content

Instantly share code, notes, and snippets.

@Mr-Malomz
Created February 4, 2019 23:59
Show Gist options
  • Save Mr-Malomz/9b6ff78b1662837dafa630f3b4556319 to your computer and use it in GitHub Desktop.
Save Mr-Malomz/9b6ff78b1662837dafa630f3b4556319 to your computer and use it in GitHub Desktop.
Refresh in Python
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Python \n",
"According to [StackOverflow](https://insights.stackoverflow.com/survey/2018/) survey, Python is considered as one of the fastest growing programming language. Python is an [Open Source](https://en.wikipedia.org/wiki/Open-source_software) programming language and works across all platform. Get [Python](http://python.org/downloads/) if youve'nt installed it yet.\n",
"\n",
"This notebook gives a refresh for experience programmer and an intro to **Python Programing Language** for newbies. \n",
"\n",
"Without much stories, lets dive straight in"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Python Basics\n",
"\n",
"##### Expression and Math Operators in Python\n",
"Python Output is done using the **print()** function. Now lets write our first program."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hello World\n"
]
}
],
"source": [
"#Print out Hello World in Python\n",
"\n",
"print('Hello World')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"###### Math Operators in Python\n",
"Python follows the popular **BODMAS** rule. Operators include:\n",
"* Exponential (**)\n",
"* Remainder/Modulus (%)\n",
"* Division (/)\n",
"* Multiplication (*)\n",
"* Addition (+)\n",
"* Subtraction (-)\n",
"\n",
"Math operation example in python\n"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"4\n",
"8\n",
"16\n",
"256\n"
]
}
],
"source": [
"#Exponential(**)\n",
"print(2 ** 2)\n",
"print(2 ** 3)\n",
"print(4 ** 2)\n",
"print(4 ** 4)"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0\n",
"1\n",
"2\n",
"3\n"
]
}
],
"source": [
"#Remainder/Modulus(%). Ouputs the remainder of a division\n",
"print(4 % 2) \n",
"print(5 % 2)\n",
"print(8 % 3)\n",
"print(7 % 4)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2.0\n",
"2.5\n",
"2.6666666666666665\n",
"1.75\n"
]
}
],
"source": [
"#Division\n",
"print(4 / 2) \n",
"print(5 / 2)\n",
"print(8 / 3)\n",
"print(7 / 4)"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"8\n",
"10\n",
"24\n",
"28\n"
]
}
],
"source": [
"#Multiplication(*)\n",
"print(4 * 2) \n",
"print(5 * 2)\n",
"print(8 * 3)\n",
"print(7 * 4)"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"6\n",
"7\n",
"11\n",
"11\n"
]
}
],
"source": [
"#Addition (+)\n",
"print(4 + 2) \n",
"print(5 + 2)\n",
"print(8 + 3)\n",
"print(7 + 4)"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2\n",
"3\n",
"5\n",
"3\n"
]
}
],
"source": [
"#Subtraction (-)\n",
"print(4 - 2) \n",
"print(5 - 2)\n",
"print(8 - 3)\n",
"print(7 - 4)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### Variables and Data Types in Python\n",
"**Variables** in python are like containers in the kitchen for storing maggi, salt, palm oil e.t.c. They are used for storing data values in computer memory. Storing data in variables allows flexibility in our program. Going back to our kitchen example, we can easily replace the content of a Container storing maggi with salt or crayfish. Variable in programming gives this flexibilty of replacement too.\n",
"\n",
"Rules in Naming Variables\n",
"* It **can** be only one word e.g a, b, z e.t.c\n",
"* It **can't** begin with a number e.g 123guy, 2morow\n",
"* It **can** use only letters, numbers(inbetweeen or at the end) and underscore character e.g rice, be3n, _tomorrow e.t.c\n",
"* No space is allowed inbetween variable names e.g rice and beans, ground nut\n",
"**Generally, a good variable name describe the data type it contains.**\n",
"\n",
"**Data Types** are like the maggi, salt, palm oil e.t.c stored inside the container.\n",
"\n",
"Types of Data Types\n",
"* String Data Type: are texts & statement\n",
"* Integers Data Type: are whole numbers\n",
"* Float Data Type: are point numbers\n",
"* Boolean Data Type: represent True or False\n",
"\n",
"With this brief intro, we can code :)"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Rice & Beans\n",
"Food\n",
"Maggi and Salt\n"
]
}
],
"source": [
"#string variables uses single or double quotation mark to store string\n",
"food = 'Rice & Beans'\n",
"category = 'Food'\n",
"ingredient = 'Maggi and Salt'\n",
"\n",
"#Now we can output our variables\n",
"print(food)\n",
"print(category)\n",
"print(ingredient)"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1\n",
"2\n",
"4\n"
]
}
],
"source": [
"#Integers are numbers and they do not require quotqtion when storing them\n",
"a = 1\n",
"b = 2\n",
"c = 4\n",
"\n",
"#Now we can output our variables\n",
"print(a)\n",
"print(b)\n",
"print(c)"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1.7\n",
"2.567\n",
"4.453\n"
]
}
],
"source": [
"#Floats are point numbers and they do not require quotqtion when storing them\n",
"ab_c = 1.7\n",
"b29 = 2.567\n",
"cGrade = 4.453\n",
"\n",
"#Now we can output our variables\n",
"print(ab_c)\n",
"print(b29)\n",
"print(cGrade)"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"True\n",
"False\n"
]
}
],
"source": [
"#Boolean essentially stores True or False. They are used to check validity of something\n",
"isMale = True\n",
"isBobrisky = False\n",
"\n",
"#Now we can output our variables\n",
"print(isMale)\n",
"print(isBobrisky)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"###### Working with strings\n",
"We can concatenate(add) strings and also use built in python function on string variables.\n",
"\n",
"Examples"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Make Up Tutorial\n"
]
}
],
"source": [
"print('Make Up Tutorial')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can create a new line inside a string using \" \\n \""
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Make Up \n",
"Tutorial\n"
]
}
],
"source": [
"print('Make Up \\nTutorial') # \"\\n\" inserted will push \"Tutorial\" into another line"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Assuming we want to put a quotation mark in a string, we need to escape it with a backslash **\"\\\"**. This tells python to execute the string as a whole."
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [
{
"ename": "SyntaxError",
"evalue": "invalid syntax (<ipython-input-14-eb3150ffdbe1>, line 2)",
"output_type": "error",
"traceback": [
"\u001b[1;36m File \u001b[1;32m\"<ipython-input-14-eb3150ffdbe1>\"\u001b[1;36m, line \u001b[1;32m2\u001b[0m\n\u001b[1;33m print('Python is a 'Good' programming language')\u001b[0m\n\u001b[1;37m ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m invalid syntax\n"
]
}
],
"source": [
"# without escape(\\) gives error\n",
"print('Python is a 'Good' programming language')"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Python is a 'Good' programming language\n"
]
}
],
"source": [
"# with escape\n",
"print('Python is a \\'Good\\' programming language')"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Python is a 'Good' programming language\n"
]
}
],
"source": [
"# We can also do it by combining single and double quote\n",
"print(\"Python is a 'Good' programming language\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Concatinating String**"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"My Name is Demola\n",
"Demola is a Male\n",
"And my best food is Amala\n"
]
}
],
"source": [
"name = 'Demola'\n",
"sex = 'Male'\n",
"food = 'Amala'\n",
"print('My Name is ' + name )\n",
"print(name + ' ' + ' is a ' + sex)\n",
"print('And my best food is ' + food)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Working with Python in-built function for string**"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"18\n"
]
}
],
"source": [
"plan = 'ai saturday meetUp'\n",
"# to get the length of a string. \"len()\" function counts whitespaces too\n",
"print(len(plan))"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"ai saturday meetup\n"
]
}
],
"source": [
"#Converting string to lowercase\n",
"print(plan.lower())"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"AI SATURDAY MEETUP\n"
]
}
],
"source": [
"#Convert to uppercase\n",
"print(plan.upper())"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"False\n"
]
}
],
"source": [
"#we can also check if its all lower or upper case\n",
"print(plan.islower()) # will return false because we have a capital letter in our string"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"False\n"
]
}
],
"source": [
"print(plan.isupper()) #also returns false because not letters in the string is upper case"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Chaining function in string\n",
"\n",
"It involves combination of functions"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"True\n"
]
}
],
"source": [
"# We are going to chain two functions here, first(\"upper()\") is to convert it to uppercase and the second (\"isupper\") checks if the string is Uppercase\n",
"print(plan.upper().isupper())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Getting Index of a string\n",
"\n",
"Python counts from a Zero(0) upward as suppose from a One(1) upward"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"ingredient = 'Curry'"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"C\n"
]
}
],
"source": [
"#Let's get the first letter in the variable above\n",
"print(ingredient[0])"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"r\n"
]
}
],
"source": [
"print(ingredient[3])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can also get the index of the letters directly using python in-built \"index()\" function "
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"4\n"
]
}
],
"source": [
"#let's get the index \"y\" in Curry\n",
"print(ingredient.index(\"y\"))"
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0\n"
]
}
],
"source": [
"print(ingredient.index(\"C\"))"
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {},
"outputs": [
{
"ename": "ValueError",
"evalue": "substring not found",
"output_type": "error",
"traceback": [
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[1;31mValueError\u001b[0m Traceback (most recent call last)",
"\u001b[1;32m<ipython-input-29-a4ad24f21c98>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[1;31m#using a parameter like \"K\" that is not part of the \"Curry\" string throws error\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 2\u001b[1;33m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mingredient\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mindex\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"K\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[1;31mValueError\u001b[0m: substring not found"
]
}
],
"source": [
"#using a parameter like \"K\" that is not part of the \"Curry\" string throws error\n",
"print(ingredient.index(\"K\"))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Other functions"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Kurry\n"
]
}
],
"source": [
"#replace the first letter the variable \"ingredient\"\n",
"print(ingredient.replace(\"C\", \"K\")) #Replace function takes two parameters. First the original letter and second the new letter to replace it with"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Python provides alot of built in functions to work with string. Check them out on [Python Inbuilt Function](https://docs.python.org/3/library/functions.html)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Working with Python in-built function for Numbers(Integers & Float)**"
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"num = 5"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Python has in-built function to change variable data types"
]
},
{
"cell_type": "code",
"execution_count": 32,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"5\n"
]
}
],
"source": [
"#let's convert variable num to a string\n",
"print(str(num))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Converting numbers to string help us concantenate strings with numbers"
]
},
{
"cell_type": "code",
"execution_count": 33,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"My favourite number is 5\n"
]
}
],
"source": [
"print('My favourite number is ' + str(num))"
]
},
{
"cell_type": "code",
"execution_count": 34,
"metadata": {},
"outputs": [
{
"ename": "TypeError",
"evalue": "must be str, not int",
"output_type": "error",
"traceback": [
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)",
"\u001b[1;32m<ipython-input-34-cb93a8e309ac>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[1;31m#Returns error if we didnt convert to string first\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 2\u001b[1;33m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'My favourite number is '\u001b[0m \u001b[1;33m+\u001b[0m \u001b[0mnum\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[1;31mTypeError\u001b[0m: must be str, not int"
]
}
],
"source": [
"#Returns error if we do not convert to string first\n",
"print('My favourite number is ' + num)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Common number related functions"
]
},
{
"cell_type": "code",
"execution_count": 35,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"5.78\n"
]
}
],
"source": [
"#getting absolute value of a number\n",
"print(abs(-5.78))"
]
},
{
"cell_type": "code",
"execution_count": 36,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"16\n"
]
}
],
"source": [
"#Power function\n",
"print(pow(4, 2)) #takes two parameter. it means 4 raise to the power of 2"
]
},
{
"cell_type": "code",
"execution_count": 37,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"5\n"
]
}
],
"source": [
"#getting maximum number \n",
"print(max(2, 5, 3, 4, 1))"
]
},
{
"cell_type": "code",
"execution_count": 38,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1\n"
]
}
],
"source": [
"#getting minimum number \n",
"print(min(2, 5, 3, 4, 1))"
]
},
{
"cell_type": "code",
"execution_count": 39,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"6\n",
"4\n"
]
}
],
"source": [
"#round function rounds a number with decimals to whole number\n",
"\n",
"print(round(5.6745))\n",
"\n",
"print(round(4.123))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Modules** are collection of precompiled functions and variables that we can use in our program. They are like a Cabinet for storing food stuffs and other ingredient and we can use them whenever we want to cook.\n",
"\n",
"Inother to get access to this more inbuilt number based functions, we need to import the **Math** module"
]
},
{
"cell_type": "code",
"execution_count": 40,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"from math import * #This is how we import a module. The code is simply saying import all codes in math module"
]
},
{
"cell_type": "code",
"execution_count": 41,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"3\n",
"4\n"
]
}
],
"source": [
"#floor function outputs a number without the decimal points\n",
"print(floor(3.456))\n",
"\n",
"print(floor(4.567))"
]
},
{
"cell_type": "code",
"execution_count": 42,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"4\n",
"5\n"
]
}
],
"source": [
"#Ceil function rounds the decimal numbers up\n",
"print(ceil(3.456))\n",
"\n",
"print(ceil(4.567))"
]
},
{
"cell_type": "code",
"execution_count": 43,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"5.0\n",
"12.0\n"
]
}
],
"source": [
"#sqrt function outputs the square root of a number\n",
"print(sqrt(25))\n",
"\n",
"print(sqrt(144))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"###### Getting Input from a User\n",
"Python provides a function that allows us to get input from a user, store it as a variable and perform other functions with the input. Input function makes our program interactive "
]
},
{
"cell_type": "code",
"execution_count": 44,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"What is your name? Demola\n"
]
},
{
"data": {
"text/plain": [
"'Demola'"
]
},
"execution_count": 44,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"#use the input() function and type in a prompt whenever its executed\n",
"\n",
"input('What is your name? ') #\"What is your name?\" is the prompt describing what the user to do"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now let's create a simple program to ask for user's name and and also say Hello"
]
},
{
"cell_type": "code",
"execution_count": 45,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"What is your name? Adaobi\n",
"Hello Adaobi!\n"
]
}
],
"source": [
"name = input('What is your name? ')\n",
"print('Hello ' + name + '!')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"How about we modify the above program alittle bit"
]
},
{
"cell_type": "code",
"execution_count": 46,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"What is your name?Jerry\n",
"How old are you?25\n",
"Hello Jerry! You are 25\n"
]
}
],
"source": [
"name = input('What is your name?')\n",
"age = input('How old are you?')\n",
"print('Hello ' + name + '! You are ' + age)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"###### Project: Basic Calculator\n",
"\n",
"The calculator gets two number from user, multiply and outputs the result"
]
},
{
"cell_type": "code",
"execution_count": 47,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Enter a number: 3\n",
"Enter another number: 4\n",
"12.0\n"
]
}
],
"source": [
"#first we will create variables\n",
"num1 = input('Enter a number: ')\n",
"num2 = input('Enter another number: ')\n",
"\n",
"\n",
"#lastly, we will multiply and output our result. By default, inputs from users comes as a string. So we need to convert it into a number usting float() function\n",
"result = float(num1) * float(num2)\n",
"print(result)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"###### Project: Mad Libs Game\n",
"Mad Libs is a game where one player prompts another player input a list of words to fill in a blank space. Learn more about [Mad Libs Game](https://en.wikipedia.org/wiki/Mad_Libs)"
]
},
{
"cell_type": "code",
"execution_count": 48,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Enter a color: blue\n",
"Enter a Plural Noun: Microwave\n",
"Enter a celebrity name: Yemi Alade\n",
"Roses are blue\n",
"Microwave are blue\n",
"I love Yemi Alade\n"
]
}
],
"source": [
"#first we need to create variables to prompt inputs from users\n",
"color = input('Enter a color: ')\n",
"plural_noun = input('Enter a Plural Noun: ')\n",
"celebrity = input('Enter a celebrity name: ')\n",
"\n",
"#Outputs of inputs from users to fill in blank spaces\n",
"print('Roses are ' + color)\n",
"print(plural_noun + ' are blue')\n",
"print('I love ' + celebrity)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### List\n",
"A list is a value that contains multiple value in an ordered an ordered sequence. List uses square brackets \"[ ]\". List accepts all data types"
]
},
{
"cell_type": "code",
"execution_count": 49,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['Rice', 'Beans', 'Yam', 'Potatoes']\n"
]
}
],
"source": [
"# let make a list of foods\n",
"food = ['Rice', 'Beans', 'Yam', 'Potatoes']\n",
"\n",
"print(food)"
]
},
{
"cell_type": "code",
"execution_count": 50,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Rice\n",
"Potatoes\n",
"Beans\n"
]
}
],
"source": [
"#we can also refer to element with their index and output them\n",
"print(food[0])\n",
"\n",
"print(food[3])\n",
"\n",
"print(food[1])"
]
},
{
"cell_type": "code",
"execution_count": 51,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Potatoes\n",
"Yam\n"
]
}
],
"source": [
"# we can also access index from the back of the list using negative sign\n",
"print(food[-1])\n",
"\n",
"print(food[-2])"
]
},
{
"cell_type": "code",
"execution_count": 52,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['Yam', 'Potatoes']\n"
]
}
],
"source": [
"#we can also group-select list\n",
"\n",
"print(food[2:]) #this will print the last elements of the list. \"2:\" means print element with index 2 and above"
]
},
{
"cell_type": "code",
"execution_count": 53,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['Rice', 'Beans']\n"
]
}
],
"source": [
"#This will output element in index \"0\" & \"1\" and exclude \"2\"\n",
"print(food[0:2])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can also modify a list element"
]
},
{
"cell_type": "code",
"execution_count": 54,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['Rice', 'Beans', 'Cocoyam', 'Potatoes']\n"
]
}
],
"source": [
"#Let's replace element with the name \"Yam\" with \"Cocoyam\"\n",
"food[2] = \"Cocoyam\"\n",
"\n",
"print(food)"
]
},
{
"cell_type": "code",
"execution_count": 55,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['Potatoes', 'Beans', 'Cocoyam', 'Potatoes']\n"
]
}
],
"source": [
"#more replacement. Using list element to replace another list element\n",
"food[0] = food[-1]\n",
"\n",
"print(food)"
]
},
{
"cell_type": "code",
"execution_count": 56,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['Potatoes', 'Beans', 'Cocoyam']\n"
]
}
],
"source": [
"#Deleting an element in a list\n",
"del food[-1]\n",
"\n",
"print(food)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Just like strings and numbers, python also provides in-built functions to work with list"
]
},
{
"cell_type": "code",
"execution_count": 57,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"jackpot_num = [23, 45, 24, 55, 76, 88, 90]\n",
"surname = ['John', 'Jacob', 'Travota', 'James']"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Extend Function adds a list to another list"
]
},
{
"cell_type": "code",
"execution_count": 58,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['John', 'Jacob', 'Travota', 'James', 23, 45, 24, 55, 76, 88, 90]\n"
]
}
],
"source": [
"#let's add the surname list to jackpot_num list\n",
"surname.extend(jackpot_num)\n",
"\n",
"print(surname)"
]
},
{
"cell_type": "code",
"execution_count": 59,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[23, 45, 24, 55, 76, 88, 90, 'Number']\n"
]
}
],
"source": [
"#adding individual element to the end of a list\n",
"jackpot_num.append(\"Number\")\n",
"\n",
"print(jackpot_num)"
]
},
{
"cell_type": "code",
"execution_count": 60,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[23, 'B-29', 45, 24, 55, 76, 88, 90, 'Number']\n"
]
}
],
"source": [
"#insert function adds elemnt to a specified index\n",
"jackpot_num.insert(1, 'B-29') \n",
"\n",
"print(jackpot_num)"
]
},
{
"cell_type": "code",
"execution_count": 61,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[23, 'B-29', 45, 24, 55, 76, 88, 90]\n"
]
}
],
"source": [
"#deleting element\n",
"jackpot_num.remove(\"Number\")\n",
"print(jackpot_num)"
]
},
{
"cell_type": "code",
"execution_count": 62,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[23, 'B-29', 45, 24, 55, 76, 88]\n"
]
}
],
"source": [
"#More on deleting element. Pop function removes element from the end of a list\n",
"jackpot_num.pop()\n",
"print(jackpot_num)"
]
},
{
"cell_type": "code",
"execution_count": 63,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0\n",
"1\n"
]
}
],
"source": [
"#checking index of element\n",
"print(jackpot_num.index(23)) #get the index of the first element in a list\n",
"\n",
"print(jackpot_num.index('B-29'))\n"
]
},
{
"cell_type": "code",
"execution_count": 64,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[23, 'B-29', 45, 24, 55, 76, 88]\n"
]
}
],
"source": [
"# we can also copy a list\n",
"\n",
"jackpot = jackpot_num.copy()\n",
"\n",
"print(jackpot)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Tuples \n",
"Tuples are type of data structure similar to a list. Tuples are created using bracket \"()\". \n",
"\n",
"Tuples are immutable(cannot be changed or modify)"
]
},
{
"cell_type": "code",
"execution_count": 65,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"(2, 5, 7)\n"
]
}
],
"source": [
"coordinates = (2, 5, 7)\n",
"\n",
"print(coordinates)"
]
},
{
"cell_type": "code",
"execution_count": 66,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"7\n",
"5\n"
]
}
],
"source": [
"#access tuple by index \n",
"print(coordinates[-1])\n",
"\n",
"print(coordinates[1])"
]
},
{
"cell_type": "code",
"execution_count": 67,
"metadata": {},
"outputs": [
{
"ename": "TypeError",
"evalue": "'tuple' object does not support item assignment",
"output_type": "error",
"traceback": [
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)",
"\u001b[1;32m<ipython-input-67-4aea07e0be32>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[1;31m#trying to change tuple element gives an error (they are immutable)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 2\u001b[1;33m \u001b[0mcoordinates\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;36m1\u001b[0m\u001b[1;33m]\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;36m2\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 3\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 4\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mcoordinates\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
"\u001b[1;31mTypeError\u001b[0m: 'tuple' object does not support item assignment"
]
}
],
"source": [
"#trying to change tuple element gives an error (they are immutable)\n",
"coordinates[1] = 2\n",
"\n",
"print(coordinates)"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": true
},
"source": [
"## Functions in Python\n",
"Function is a collection of codes that perform a specific task. Generally, function helps us to structure and breakdown to our code. We are already familiar with print(), input(), str() functions used above, we can also write our own function.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 68,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"#now let's write a function that greets us\n",
"def greeting():\n",
" print('Hello')\n",
" print('Good Day')\n",
" print('Enjoy your day')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"A code inside a function needs to be indented for python to consider it as codes inside the function.\n",
"\n",
"for the function above to execute, we need to call the function "
]
},
{
"cell_type": "code",
"execution_count": 69,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hello\n",
"Good Day\n",
"Enjoy your day\n"
]
}
],
"source": [
"greeting()"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": true
},
"source": [
"##### Functions with Parameters\n",
"Parameters are piece of infos we give to our function to execute.\n",
"\n",
"let's modify our function above"
]
},
{
"cell_type": "code",
"execution_count": 70,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hello demola\n",
"Good Day demola\n",
"Enjoy your day demola\n"
]
}
],
"source": [
"def greeting(name):\n",
" print('Hello ' + name)\n",
" print('Good Day ' + name)\n",
" print('Enjoy your day ' + name)\n",
" \n",
" \n",
"\n",
"#Now let's call the function with a parameter\n",
"greeting(\"demola\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Another function example with more parameters"
]
},
{
"cell_type": "code",
"execution_count": 71,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"My name is Adaobi, A Female and i am 21 years old!\n"
]
}
],
"source": [
"def hello(name, sex, age):\n",
" print('My name is ' + name + ', A ' + sex + ' and i am ' + age +' years old!' )\n",
"\n",
" \n",
"#call the function with name, sex & age\n",
"hello('Adaobi', 'Female', '21')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### Functions with Return Statement\n",
"Return statement are used to get information from a function.\n",
"\n",
"Now let's write a function that returns the square of a number"
]
},
{
"cell_type": "code",
"execution_count": 72,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"27"
]
},
"execution_count": 72,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def square(num):\n",
" return num ** num \n",
"\n",
"#call the function \n",
"square(3)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Any code inputed after the **return** statement in a function will not run.\n",
"\n",
"let's see an example"
]
},
{
"cell_type": "code",
"execution_count": 73,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"8"
]
},
"execution_count": 73,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def cube(digit):\n",
" return digit * digit * digit\n",
" print('Thanks for the calculation') #This line of code wil not be execute\n",
" \n",
" \n",
"\n",
"#call the function\n",
"cube(2)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"For the print statement to run above, it has to come before the return statement"
]
},
{
"cell_type": "code",
"execution_count": 74,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Thanks for the calculation\n"
]
},
{
"data": {
"text/plain": [
"8"
]
},
"execution_count": 74,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def cube(digit):\n",
" print('Thanks for the calculation')\n",
" return digit * digit * digit\n",
"\n",
"#call the function \n",
"cube(2)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Conditions in Python\n",
"Conditions in python are like checks carried out before executing a code. For example, we need to check the kitchen and confirm if rice is available, before we can cook rice or opt for beans instead."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### IF statement \n",
"In IF statement we check if a condition is true, if it is, we do something and if it's not true we will skip it or do another thing.\n",
"\n",
"Now let's code if statement"
]
},
{
"cell_type": "code",
"execution_count": 75,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Yeah!! There is rice at home\n"
]
}
],
"source": [
"#Assuming we have rice in the kitchen\n",
"\n",
"#let's create a boolean variable to check our condition\n",
"is_rice_at_home = True\n",
"\n",
"#if statement below\n",
"if is_rice_at_home:\n",
" print('Yeah!! There is rice at home')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The code above will execute the print statement because an if statement checks if the condition stated is true.\n",
"\n",
"Assuming there is no Rice in the kitchen and and we change our boolean variable to be False"
]
},
{
"cell_type": "code",
"execution_count": 76,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"#No rice in the Kitchen\n",
"is_rice_at_home = False\n",
"\n",
"\n",
"#if statement\n",
"if is_rice_at_home:\n",
" print('Yeah!! There is rice at home')"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": true
},
"source": [
"The code above will not give any output becuasethe if condition is not met."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"lets make our condition more dynamic by giving the program what to execute if the condition is not met. We can achieve this using the **if else statement**\n",
"\n",
"#### IF ELSE statement "
]
},
{
"cell_type": "code",
"execution_count": 77,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"No rice in the Kitchen, but we can cook Beans!\n"
]
}
],
"source": [
"#No rice in the Kitchen but we can cook beans instead\n",
"is_rice_at_home = False\n",
"\n",
"\n",
"#if statement\n",
"if is_rice_at_home:\n",
" print('Yeah!! There is rice at home')\n",
"else:\n",
" print('No rice in the Kitchen, but we can cook Beans!')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**PS:** we need to indent our code properly"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Fortunately, python allows multiple condition in programs using \"OR\" & \"AND\""
]
},
{
"cell_type": "code",
"execution_count": 78,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"You are a Male OR Tall OR Both\n"
]
}
],
"source": [
"#Another example with multiple condition. \n",
"is_male = True\n",
"is_tall = True\n",
"\n",
"#check multiple condition\n",
"if is_male or is_tall:\n",
" print('You are a Male OR Tall OR Both')\n",
"else: \n",
" print('You are neither a Male nor Tall')\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": true
},
"source": [
"The condition above checks if either one or both of the condition above is true before it execute."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The code will still execute if we change one of the condition to false. This is becuase the stated condition is either one or both condition is true"
]
},
{
"cell_type": "code",
"execution_count": 79,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"You are a Male OR Tall OR Both\n"
]
}
],
"source": [
"is_male = False\n",
"is_tall = True\n",
"\n",
"#check multiple condition\n",
"if is_male or is_tall:\n",
" print('You are a Male OR Tall OR Both')\n",
"else: \n",
" print('You are neither a Male nor Tall')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"But if we change both condition to False, then it will not execute the IF statement but execute the ELSE statement instead "
]
},
{
"cell_type": "code",
"execution_count": 80,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"You are neither a Male nor Tall\n"
]
}
],
"source": [
"is_male = False\n",
"is_tall = False\n",
"\n",
"#check multiple condition\n",
"if is_male or is_tall:\n",
" print('You are a Male OR Tall OR Both')\n",
"else: \n",
" print('You are neither a Male nor Tall')\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Assuming we want both of our condition to be TRUE before the code execute. We can do this using the \"AND\" operator"
]
},
{
"cell_type": "code",
"execution_count": 81,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"You are a Male AND You are Tall\n"
]
}
],
"source": [
"is_male = True\n",
"is_tall = True\n",
"\n",
"#check multiple condition\n",
"if is_male and is_tall:\n",
" print('You are a Male AND You are Tall')\n",
"else: \n",
" print('You are either not male or not tall or both')\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The else statement will execute if one or both the condition is False"
]
},
{
"cell_type": "code",
"execution_count": 82,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"You are either not male or not tall or both\n"
]
}
],
"source": [
"is_male = False\n",
"is_tall = True\n",
"\n",
"#check multiple condition\n",
"if is_male and is_tall:\n",
" print('You are a Male AND You are Tall')\n",
"else: \n",
" print('You are either not male or not tall or both')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can make our program more dynamic with multiple if conditions using the **IF ELIF & ELSE statement** \n",
"\n",
"#### IF ELIF ELSE statement "
]
},
{
"cell_type": "code",
"execution_count": 83,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"You are not Male, but you are tall\n"
]
}
],
"source": [
"is_male = False\n",
"is_tall = True\n",
"\n",
"#check multiple condition\n",
"if is_male and is_tall:\n",
" print('You are a Male AND You are Tall')\n",
" \n",
"elif is_male and not is_tall:\n",
" print('You are a short Male')\n",
"\n",
"elif not is_male and is_tall:\n",
" print('You are not Male, but you are tall')\n",
" \n",
"else: \n",
" print('You are not male or tall')"
]
},
{
"cell_type": "code",
"execution_count": 84,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"You are a short Male\n"
]
}
],
"source": [
"is_male = True\n",
"is_tall = False\n",
"\n",
"#check multiple condition\n",
"if is_male and is_tall:\n",
" print('You are a Male AND You are Tall')\n",
" \n",
"elif is_male and not is_tall:\n",
" print('You are a short Male')\n",
"\n",
"elif not is_male and is_tall:\n",
" print('You are not Male, but you are tall')\n",
" \n",
"else: \n",
" print('You are not male or tall')"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": true
},
"source": [
"### Comparison using Operators in Conditions\n",
"Operators in python are:\n",
"\n",
"* '==' **Equal to**\n",
"* '!=' **Not equal to**\n",
"* '<' **Less than**\n",
"* '>' **Greater than**\n",
"* '<=' **Less than or equal to**\n",
"* '>=' **Greater than or equal to**\n",
"\n",
"To illustrate this operators better, we will create a function that accepts user input and tells us the maximum number "
]
},
{
"cell_type": "code",
"execution_count": 85,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def max_number(num1, num2, num3):\n",
" if num1 >= num2 and num1 >= num3:\n",
" return 'The maximum number is: ', num1\n",
" \n",
" elif num2 >= num1 and num2 >= num3:\n",
" return 'The maximum number is: ', num2\n",
" else: \n",
" return 'The maximum number is: ', num3"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The code above accepts 3 parameters num1, num2 & num3.\n",
"\n",
"The first if statement checks if **num1** is greater than or equal to either **num2** and **num3**. If the condition is true, then it will return **num1** as the maximum number\n",
"\n",
"The second elif statement checks if **num2** is greater than or equal to either **num1** and **num3**. If the condition is true, then it will return **num2** as the maximum number\n",
"\n",
"The third else statement returns **num3** if both conditions above are not met"
]
},
{
"cell_type": "code",
"execution_count": 86,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"('The maximum number is: ', 10)"
]
},
"execution_count": 86,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"#Now let's call the function\n",
"max_number(5, 6, 10)"
]
},
{
"cell_type": "code",
"execution_count": 87,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"('The maximum number is: ', 26)"
]
},
"execution_count": 87,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"max_number(26, 3, 15)"
]
},
{
"cell_type": "code",
"execution_count": 88,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"('The maximum number is: ', 44)"
]
},
"execution_count": 88,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"max_number(5, 44, 10)"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": true
},
"source": [
"We can also use comparison operator on strings\n"
]
},
{
"cell_type": "code",
"execution_count": 89,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Type in your pet namr: Skippo\n",
"My pet's name is Skippo\n"
]
}
],
"source": [
"pet_name = input('Type in your pet namr: ')\n",
"\n",
"if pet_name == 'Sisqo':\n",
" print('My pet\\'s name is Sisqo')\n",
"elif pet_name == 'Skippo':\n",
" print('My pet\\'s name is Skippo')\n",
"else:\n",
" print('Type in your pet name')"
]
},
{
"cell_type": "code",
"execution_count": 90,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Type in your pet namr: loral\n",
"Type in your pet name\n"
]
}
],
"source": [
"pet_name = input('Type in your pet namr: ')\n",
"\n",
"if pet_name == 'Sisqo':\n",
" print('My pet\\'s name is Sisqo')\n",
"elif pet_name == 'Skippo':\n",
" print('My pet\\'s name is Skippo')\n",
"else:\n",
" print('Type in your pet name')"
]
},
{
"cell_type": "code",
"execution_count": 91,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Type in your pet namr: Sisqo\n",
"My pet's name is Sisqo\n"
]
}
],
"source": [
"pet_name = input('Type in your pet namr: ')\n",
"\n",
"if pet_name == 'Sisqo':\n",
" print('My pet\\'s name is Sisqo')\n",
"elif pet_name == 'Skippo':\n",
" print('My pet\\'s name is Skippo')\n",
"else:\n",
" print('Type in your pet name')"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": true
},
"source": [
"###### Project: Building a Better Calculator"
]
},
{
"cell_type": "code",
"execution_count": 92,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Enter first number: 3\n",
"Enter Operator: **\n",
"Enter second number: 4\n",
"81.0\n"
]
}
],
"source": [
"#first we will create a variable and convert it to a number since input by default converts it's input to a string\n",
"num1 = float(input('Enter first number: '))\n",
"\n",
"#lets also get the operator\n",
"operator = input('Enter Operator: ')\n",
"\n",
"num2 = float(input('Enter second number: '))\n",
"\n",
"#Now we will write condition statement to figure out the kind of operations users want\n",
"if operator == '+':\n",
" print(num1 + num2)\n",
"\n",
"elif operator == '-':\n",
" print(num1 - num2)\n",
" \n",
"elif operator == '*':\n",
" print(num1 * num2)\n",
"\n",
"elif operator == '**':\n",
" print(num1 ** num2)\n",
" \n",
"elif operator == '/':\n",
" print(num1 / num2)\n",
" \n",
"else: \n",
" print('Invalid Operator!!')\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": true
},
"source": [
"## Dictionary\n",
"Dictionary is a collection of many value like a **List** but with different kind of indexes. Dictionary allows a **key-value** pair. It works like a normal dictionary which has a word(key) and a definition(value).\n",
"\n",
"We define dictionary using angle bracket \"{}\"\n",
"\n",
"In a dictionary, the value on the left is KEY, the value on the right is the VALUE and colon(:) is used to assign a VALUE to a KEY. We seperate multiple values in dictionary using comma(,). The KEY in a dictionary must be unique"
]
},
{
"cell_type": "code",
"execution_count": 93,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'Jan': 'January', 'Feb': 'February', 'Mar': 'March', 'Apr': 'April', 'May': 'May', 'Jun': 'June', 'Jul': 'July', 'Aug': 'August', 'Sep': 'September', 'Oct': 'October', 'Nov': 'November', 'Dec': 'December'}\n"
]
}
],
"source": [
"#lets create a dictionary that converts month\n",
"month_conversion = {\n",
" 'Jan': 'January',\n",
" 'Feb': 'February',\n",
" 'Mar': 'March',\n",
" 'Apr': 'April',\n",
" 'May': 'May',\n",
" 'Jun': 'June',\n",
" 'Jul': 'July',\n",
" 'Aug': 'August',\n",
" 'Sep': 'September',\n",
" 'Oct': 'October',\n",
" 'Nov': 'November',\n",
" 'Dec': 'December'\n",
"}\n",
"\n",
"print(month_conversion)"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": true
},
"source": [
"We can access dictionary values in different ways via it's key"
]
},
{
"cell_type": "code",
"execution_count": 94,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"January\n"
]
}
],
"source": [
"#Accessing dictionary using square bracket\n",
"print(month_conversion['Jan'])"
]
},
{
"cell_type": "code",
"execution_count": 95,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"March\n"
]
}
],
"source": [
"print(month_conversion['Mar'])"
]
},
{
"cell_type": "code",
"execution_count": 96,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"November\n"
]
}
],
"source": [
"#Accessing dictionary using get() function\n",
"print(month_conversion.get('Nov'))"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": true
},
"source": [
"Using an invalid key a dictionay will return 'None'"
]
},
{
"cell_type": "code",
"execution_count": 97,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"None\n"
]
}
],
"source": [
"print(month_conversion.get('Mow'))"
]
},
{
"cell_type": "code",
"execution_count": 98,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Not a valid key, Please enter a valid key\n"
]
}
],
"source": [
"# we can also print out a default value when the specified key is not valid \n",
"\n",
"print(month_conversion.get('Mow', 'Not a valid key, Please enter a valid key'))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Dictionary also takes integers as key "
]
},
{
"cell_type": "code",
"execution_count": 99,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{1: 'a', 2: 'b', 3: 'c', 4: 'd'}\n"
]
}
],
"source": [
"alpha = {1:'a', 2:'b', 3:'c', 4:'d'}\n",
"print(alpha)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Iteration and Looping in Python\n",
"Looping in python allows us to loop through a block of code repeatedly.\n",
"\n",
"###### While Loops\n"
]
},
{
"cell_type": "code",
"execution_count": 100,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1\n",
"2\n",
"3\n",
"4\n",
"5\n",
"6\n",
"7\n",
"8\n",
"9\n"
]
}
],
"source": [
"a = 1\n",
"\n",
"while a < 10:\n",
" print(a)\n",
" a = a + 1 #This line of code tells python to keep adding \"1\" to \"a\" value until the condition is met"
]
},
{
"cell_type": "code",
"execution_count": 101,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1\n",
"2\n",
"3\n",
"4\n",
"5\n"
]
}
],
"source": [
"# Better way of writing the while loop\n",
"b = 1\n",
"while b < 6: #as long as this condition is true, it will keep looping over the code below\n",
" print(b)\n",
" b +=1 #this is the same thing as \"a = a + 1\""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"###### Project: Building a Guesing Game\n",
"This game involves us specifying a secret word and the user interacts with the program by guessing the secret word. The user has a limit of 3 times, if the user guesses more than 3 times then they have lost the game"
]
},
{
"cell_type": "code",
"execution_count": 103,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Guess a word : guy\n",
"Guess a word : house\n",
"Guess a word : today\n",
"Out of Guess: YOU LOSE!\n"
]
}
],
"source": [
"#Guessing game code\n",
"\n",
"secret_word = 'Lion'\n",
"guess =''\n",
"guess_count = 0\n",
"guess_limit = 3\n",
"out_of_guess = False\n",
"\n",
"while guess != secret_word and not out_of_guess:\n",
" if guess_count < guess_limit:\n",
" guess = input('Guess a word : ')\n",
" guess_count += 1\n",
" \n",
" else: \n",
" out_of_guess = True\n",
"\n",
" \n",
"if out_of_guess:\n",
" print('Out of Guess: YOU LOSE!')\n",
"\n",
"else:\n",
" print('You win')\n",
" "
]
},
{
"cell_type": "code",
"execution_count": 104,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Guess a word : Lion\n",
"You win\n"
]
}
],
"source": [
"#Let's run the game again but with right word\n",
"\n",
"secret_word = 'Lion'\n",
"guess =''\n",
"guess_count = 0\n",
"guess_limit = 3\n",
"out_of_guess = False\n",
"\n",
"while guess != secret_word and not out_of_guess:\n",
" if guess_count < guess_limit:\n",
" guess = input('Guess a word : ')\n",
" guess_count += 1\n",
" \n",
" else: \n",
" out_of_guess = True\n",
"\n",
" \n",
"if out_of_guess:\n",
" print('Out of Guess: YOU LOSE!')\n",
"\n",
"else:\n",
" print('You win')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"###### For Loop\n",
"This is probably the most common type of loop in any programming language. It can be use to iterate over any elements of an array, dictionary e.t.c\n",
"\n",
"For loop takes in a variable and loop over a collection"
]
},
{
"cell_type": "code",
"execution_count": 105,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"R\n",
"i\n",
"c\n",
"e\n",
" \n",
"&\n",
" \n",
"B\n",
"e\n",
"a\n",
"n\n",
"s\n"
]
}
],
"source": [
"#Example to print out all the letters in a string\n",
"\n",
"for letters in 'Rice & Beans':\n",
" print(letters)\n"
]
},
{
"cell_type": "code",
"execution_count": 106,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"David\n",
"James\n",
"Jim\n",
"Janet\n",
"Skibo\n"
]
}
],
"source": [
"#Example: Looping through an array\n",
"\n",
"name = ['David', 'James', 'Jim', 'Janet', 'Skibo']\n",
"\n",
"for index in name:\n",
" print(index)"
]
},
{
"cell_type": "code",
"execution_count": 107,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"jan\n",
"feb\n",
"mar\n",
"apr\n",
"may\n"
]
}
],
"source": [
"#Example: using a dictionary\n",
"month_in_a_year = {\n",
" 'jan': 'january',\n",
" 'feb': 'february',\n",
" 'mar': 'march',\n",
" 'apr': 'april',\n",
" 'may': 'may'\n",
"}\n",
"\n",
"for month in month_in_a_year:\n",
" print(month)"
]
},
{
"cell_type": "code",
"execution_count": 108,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"january\n",
"february\n",
"march\n",
"april\n",
"may\n"
]
}
],
"source": [
"# to get the values in a dictionary. We will use a values() function\n",
"month_in_a_year = {\n",
" 'jan': 'january',\n",
" 'feb': 'february',\n",
" 'mar': 'march',\n",
" 'apr': 'april',\n",
" 'may': 'may'\n",
"}\n",
"\n",
"for month in month_in_a_year.values():\n",
" print(month)"
]
},
{
"cell_type": "code",
"execution_count": 109,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0\n",
"1\n",
"2\n",
"3\n",
"4\n"
]
}
],
"source": [
"#Example: Iterating over ranges of number\n",
"\n",
"for index in range(5):\n",
" print(index)"
]
},
{
"cell_type": "code",
"execution_count": 110,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"4\n",
"5\n",
"6\n",
"7\n",
"8\n"
]
}
],
"source": [
"#More on range\n",
"for index in range(4, 9):\n",
" print(index)"
]
},
{
"cell_type": "code",
"execution_count": 111,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"First Index\n",
"1\n",
"Third Index\n",
"3\n",
"4\n"
]
}
],
"source": [
"#Examples: More on loops\n",
"\n",
"for index in range(5):\n",
" if index == 0:\n",
" print('First Index')\n",
" elif index == 2:\n",
" print('Third Index')\n",
" else:\n",
" print(index)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Exponent Function using Loop**"
]
},
{
"cell_type": "code",
"execution_count": 112,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"64"
]
},
"execution_count": 112,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def expo(base_num, power_num):\n",
" result = 1\n",
" for index in range(power_num):\n",
" result = result * base_num\n",
" return result\n",
"\n",
"\n",
"#call the function\n",
"expo(4, 3)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Nesting in Python\n",
"Nesting is simply embedding a collection of element inside another collection"
]
},
{
"cell_type": "code",
"execution_count": 113,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[[1, 2, 3], [4, 5, 6], [7, 8, 9], [0]]\n"
]
}
],
"source": [
"#Example: List\n",
"nest =[\n",
" [1, 2, 3], \n",
" [4, 5, 6], \n",
" [7, 8, 9], \n",
" [0]\n",
"]\n",
"\n",
"print(nest)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Assuming we want to get individual number in a nested list. We can access it by [row][column]\n",
"\n",
"[row] is the horzontal list index\n",
"\n",
"[column] is the vertical lisyt index"
]
},
{
"cell_type": "code",
"execution_count": 114,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1\n"
]
}
],
"source": [
"#lets get 1\n",
"print(nest[0][0])"
]
},
{
"cell_type": "code",
"execution_count": 115,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"4\n"
]
}
],
"source": [
"#lets get 4\n",
"print(nest[1][0])"
]
},
{
"cell_type": "code",
"execution_count": 116,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"9\n"
]
}
],
"source": [
"#lets get 9\n",
"print(nest[2][2])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"###### Nested For loop\n",
"Python permits nesting of loop inside another loop.\n",
"\n",
"Using the nest variable above"
]
},
{
"cell_type": "code",
"execution_count": 117,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[1, 2, 3]\n",
"[4, 5, 6]\n",
"[7, 8, 9]\n",
"[0]\n"
]
}
],
"source": [
"#get the nest variable row\n",
"for row in nest:\n",
" print(row)"
]
},
{
"cell_type": "code",
"execution_count": 118,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[1, 2, 3]\n",
"1\n",
"2\n",
"3\n",
"[4, 5, 6]\n",
"4\n",
"5\n",
"6\n",
"[7, 8, 9]\n",
"7\n",
"8\n",
"9\n",
"[0]\n",
"0\n"
]
}
],
"source": [
"#Now let us print the column in each of the printed rows above\n",
"for row in nest:\n",
" print(row)\n",
" for col in row:\n",
" print(col)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"###### Project: Build A Translator\n",
"The translator simply transform a vowel in any given string to a letter 'g'"
]
},
{
"cell_type": "code",
"execution_count": 119,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def translator(phrase):\n",
" translation = ''\n",
" for letter in phrase:\n",
" if letter.lower() in 'aeiou':\n",
" if letter.isupper():\n",
" translation = translation + 'G'\n",
" else:\n",
" translation = translation + 'g'\n",
" else:\n",
" translation = translation + letter\n",
" return translation"
]
},
{
"cell_type": "code",
"execution_count": 121,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Enter a phrase: Today's is a good day\n",
"Tgdgy's gs g gggd dgy\n"
]
}
],
"source": [
"#Now lets call the function\n",
"print(translator(input('Enter a phrase: ')))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Comment in Python\n",
"Comments are vital parts of a code. It help us remember our code and also help other developer reviewing our code understand what that part of code is meant to do\n",
"\n",
"Comment in Python is either number sign (#this is a comment) for a line or tripple single or double quote (\"\"\" this is a comment\"\"\") for multi-line comment "
]
},
{
"cell_type": "code",
"execution_count": 122,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"#this is a comment\n",
"#print('Hello')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"\"\"\"This is also a multiline \n",
"comment using a double quote thrice\n",
"\"\"\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"'''\n",
"this a multi-line\n",
"comment with \n",
"single quote\n",
"'''"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exception Handling in Python\n",
"Python let us handle error that may inder our program from running"
]
},
{
"cell_type": "code",
"execution_count": 124,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Enter a number: 4\n",
"4\n"
]
}
],
"source": [
"# Example: convert a user input into a number\n",
"\n",
"number = int(input('Enter a number: '))\n",
"print(number)"
]
},
{
"cell_type": "code",
"execution_count": 125,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Enter a number: ab\n"
]
},
{
"ename": "ValueError",
"evalue": "invalid literal for int() with base 10: 'ab'",
"output_type": "error",
"traceback": [
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[1;31mValueError\u001b[0m Traceback (most recent call last)",
"\u001b[1;32m<ipython-input-125-40fab406a21e>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[1;31m#Assuming we break the rule and didn't enter a number\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 2\u001b[1;33m \u001b[0mnumber\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0minput\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'Enter a number: '\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 3\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mnumber\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
"\u001b[1;31mValueError\u001b[0m: invalid literal for int() with base 10: 'ab'"
]
}
],
"source": [
"#Assuming we break the rule and didn't enter a number\n",
"number = int(input('Enter a number: '))\n",
"print(number)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The code throws an error becuase the user entered letters as suppose to a number which will break our program. Inother to prevent breaking our program python provides a **TRY EXCEPT Block** for handling such cases "
]
},
{
"cell_type": "code",
"execution_count": 126,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Enter a number: ab\n",
"Invalid Input!!\n"
]
}
],
"source": [
"#Now lets modify the program above\n",
"try:\n",
" number = int(input('Enter a number: '))\n",
" print(number)\n",
"except:\n",
" print('Invalid Input!!')"
]
},
{
"cell_type": "code",
"execution_count": 127,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"division by zero\n"
]
}
],
"source": [
"#We can also make our code better by catch or excepting our error\n",
"try:\n",
" value = 10/0\n",
" number = int(input('Enter a number: '))\n",
" print(number)\n",
"except ZeroDivisionError as err:\n",
" print(err)\n",
"except ValueError:\n",
" print('Invalid Input')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Reading External File in Python\n",
"Python provides functins for reading, closing and editing files.\n",
"\n",
"It is a good practice to close the file after opening or working on it."
]
},
{
"cell_type": "code",
"execution_count": 133,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"#This open() fuction takes the path to the file we want to open\n",
"\n",
"file = open('C:/Users/USER/Desktop/ariba.txt', 'r+') "
]
},
{
"cell_type": "code",
"execution_count": 129,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 129,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# We can check if the file is readable\n",
"file.readable()"
]
},
{
"cell_type": "code",
"execution_count": 130,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'ARIBA CONTRACT\\n\\nMATERIAL - Ink cartridges 44103105\\nSUPPLIER - Supplier 2 (PunchOut)\\nCONTRACT ID - CW3751Materials ManagementMaterials ManagementMaterials ManagementMaterials Management'"
]
},
"execution_count": 130,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"#output the content of the file\n",
"file.read()"
]
},
{
"cell_type": "code",
"execution_count": 132,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'ARIBA CONTRACT\\n'"
]
},
"execution_count": 132,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"#Read the content of the file one by one using readline() function\n",
"file.readline()"
]
},
{
"cell_type": "code",
"execution_count": 134,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['ARIBA CONTRACT\\n',\n",
" '\\n',\n",
" 'MATERIAL - Ink cartridges 44103105\\n',\n",
" 'SUPPLIER - Supplier 2 (PunchOut)\\n',\n",
" 'CONTRACT ID - CW3751Materials ManagementMaterials ManagementMaterials ManagementMaterials Management']"
]
},
"execution_count": 134,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"#Reading all the content in a loop at once using readlines()\n",
"file.readlines()"
]
},
{
"cell_type": "code",
"execution_count": 135,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"#We can close the file\n",
"file.close()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Python also allows us to write new file and also append to an existing file\n",
"\n",
"Append"
]
},
{
"cell_type": "code",
"execution_count": 136,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"file = open('C:/Users/USER/Desktop/ariba.txt', 'a') #change the mode to append 'a'"
]
},
{
"cell_type": "code",
"execution_count": 137,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"20"
]
},
"execution_count": 137,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"#adding to the file\n",
"file.write('Materials Management')"
]
},
{
"cell_type": "code",
"execution_count": 138,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"file.close()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Writing a New File"
]
},
{
"cell_type": "code",
"execution_count": 139,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"new_file = open('new.html', 'w')\n",
"new_file.write('<div> Hello Mr HTML </div> \\n <p> It is a good day to Code</p>')\n",
"new_file.close()"
]
},
{
"cell_type": "code",
"execution_count": 140,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['<div> Hello Mr HTML </div> \\n', ' <p> It is a good day to Code</p>']\n"
]
}
],
"source": [
"print((open('new.html', 'r+')).readlines())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Modules in Python\n",
"Modules are collection of codes we can input into our program to make it more functional. We can also create a module ourself and use in other program. To read more and access other python modules check out [Modules](https://docs.python.org/3/py-modindex.html)\n",
"\n",
"Now let's work with a python module called randint that generates random numbers"
]
},
{
"cell_type": "code",
"execution_count": 141,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"9\n"
]
}
],
"source": [
"from random import randint\n",
"\n",
"rand_num = randint(0, 10) #generates a random number within the range of 0 and 10\n",
"print(rand_num)"
]
},
{
"cell_type": "code",
"execution_count": 142,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"34\n"
]
}
],
"source": [
"print(randint(25, 45))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Installing Third-Party Modules and Library in Python\n",
"Python has a huge community of developers constantly working on libraries and modules. we can simply google what we are trying to do and there's a possibility that someone have developed a module or library for that already\n",
"\n",
"###### Installing Modules & Libraries in Python \n",
"Python uses a Package manager known as **PIP** which helps us install, manage, update and delete modules & libraries. To install a module/library:\n",
"\n",
"1. Click the START button in your computer \n",
"2. Type in \"CMD\" in the search bar\n",
"3. Click the cmd program\n",
"4. Type in the library/module you want to install \n",
"Assuming we want to install a module named \"Python-docx\".\n",
"\n",
"Just type in **\"pip install python-docx\"**\n",
"\n",
"To delete **pip uninstall python-docx**\n",
"\n",
"Most third party modules installed on python are stored in a folder name **Site-Packages**.\n",
"\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Classes and Object in Python\n",
"In construction, an architect produces a **Plan or Blueprint** that civil engineers or builders follows in implemeenting a structural buildings.\n",
"\n",
"In programming, classes are like blueprint/plan to produce Object(like buildings). Classes and Object makes our program powerful and dynamic.\n",
"\n",
"Classes and Object are used to represent real-world datas.\n",
"\n",
"Variables in Object are called Properties and Functions in python are called Methods.\n",
"\n",
"Assuming we want to write a program representing a School in python, we can use Class and Object to implement all the sections in a school.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 143,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"#First let's model a student class\n",
"class Student:\n",
" def __init__(self, name, sex, department, gpa, is_on_probation):\n",
" self.name = name\n",
" self.sex = sex\n",
" self.department = department\n",
" self.gpa = gpa\n",
" self.is_on_probation = is_on_probation\n",
" "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**def __init__(self)** statement is used in a class to map out properties and methods a class should have. Its essentially defines what a student is.\n",
"\n",
"**self** is a class instance and it refers to the Object created at a particular instance.\n",
"\n",
"Remember that a class is like a plan/blueprint for creating an object. So we can now create a Student Profile using our Class Blueprint above"
]
},
{
"cell_type": "code",
"execution_count": 144,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"#Create an Object for a student (John and Zainab)\n",
"student_1 = Student('John', 'Male', 'Civil Engineering', 3.95, False )\n",
" \n",
"student_2 = Student('Zainab', 'Female', 'Medicine', 4.59, False)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now we can access each infos of a student"
]
},
{
"cell_type": "code",
"execution_count": 145,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Civil Engineering\n",
"John\n",
"Medicine\n",
"Female\n"
]
}
],
"source": [
"print(student_1.department)\n",
"\n",
"print(student_1.name)\n",
"\n",
"#accessing student 2\n",
"print(student_2.department)\n",
"\n",
"print(student_2.sex)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"###### Project: Multiple Choice Quiz\n",
"This game allows user to answer quizzes, keep track of the scores and output the final score."
]
},
{
"cell_type": "code",
"execution_count": 146,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"#Create a variable for the questions\n",
"questions = [\n",
" 'What colour are apples? \\n (a) Red/Green \\n (b) Purple \\n (c) Orange \\n\\n',\n",
" 'What colour are bananas? \\n (a) Teal \\n (b) Magenta \\n (c) Yellow \\n\\n',\n",
" 'What colour are strawberries? \\n (a) Yellow \\n (b) Red \\n (c) Blue \\n\\n'\n",
"]\n",
"\n",
"#To keep tract of the question, answer and scores, we need to use a class\n",
"\n",
"class Quiz:\n",
" def __init__(self, prompt, answer):\n",
" self.prompt = prompt\n",
" self.answer = answer\n"
]
},
{
"cell_type": "code",
"execution_count": 147,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"#Now we can create our quiz questions for users using the quiz class\n",
"\n",
"quiz_question = [\n",
" Quiz(questions[0], 'a'),\n",
" Quiz(questions[1], 'c'),\n",
" Quiz(questions[2], 'b')\n",
"]"
]
},
{
"cell_type": "code",
"execution_count": 148,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"#now we can create a function to ask the questions and also check if the answer is correct\n",
"def run_quiz(quiz_question):\n",
" score = 0\n",
" for quiz in quiz_question:\n",
" answer = input(quiz.prompt)\n",
" if answer == quiz.answer :\n",
" score +=1\n",
" print('You got ' + str(score) + '/' + str(len(quiz_question)) + ' correct')"
]
},
{
"cell_type": "code",
"execution_count": 149,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"What colour are apples? \n",
" (a) Red/Green \n",
" (b) Purple \n",
" (c) Orange \n",
"\n",
"a\n",
"What colour are bananas? \n",
" (a) Teal \n",
" (b) Magenta \n",
" (c) Yellow \n",
"\n",
"b\n",
"What colour are strawberries? \n",
" (a) Yellow \n",
" (b) Red \n",
" (c) Blue \n",
"\n",
"b\n",
"You got 2/3 correct\n"
]
}
],
"source": [
"#now let's run the quiz by calling the function\n",
"run_quiz(quiz_question)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Object Function\n",
"Object Function are also known as method, it's basically including a function in our class.\n",
"\n",
"Let's modify Student class created earlier and have a function embed in it"
]
},
{
"cell_type": "code",
"execution_count": 150,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"# a function to check if student is on dean list if the gpa is greater than 4.0 \n",
"class Student:\n",
" def __init__(self, name, sex, department, gpa, is_on_probation):\n",
" self.name = name\n",
" self.sex = sex\n",
" self.department = department\n",
" self.gpa = gpa\n",
" self.is_on_probation = is_on_probation\n",
" \n",
" def on_dean_list(self):\n",
" if self.gpa >= 4.0:\n",
" print('Student is ON Dean\\'s list')\n",
" else:\n",
" print('Student is NOT on Dean\\'s list')\n",
" "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now we can two more student and test if they're on dean's list or not\n"
]
},
{
"cell_type": "code",
"execution_count": 151,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"student_3 = Student('Racheal', 'Female', 'Business Administration', 3.45, False)\n",
"\n",
"student_4 = Student('Micheal', 'Male', 'Architecture', 4.89, False)"
]
},
{
"cell_type": "code",
"execution_count": 152,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Student is NOT on Dean's list\n",
"None\n"
]
}
],
"source": [
"#test if student is on dean's list\n",
"print(student_3.on_dean_list())"
]
},
{
"cell_type": "code",
"execution_count": 153,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Student is ON Dean's list\n",
"None\n"
]
}
],
"source": [
"print(student_4.on_dean_list())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Inheritance in Python Class\n",
"Inheritance in python involves a Class inheriting methods(function) and properties(variables) from another Class.\n",
"\n",
"Using Student Class above, we can create another class for Lecturers that inherit some of the properties of the Student Class.\n",
"\n",
"This is done by passing the class we want to inherit from as a parameter. So we will inherit the property of Name and Sex from the Student Class. "
]
},
{
"cell_type": "code",
"execution_count": 154,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"class Lecturer(Student): \n",
" def __init__(self, faculty, position, sex, name):\n",
" self.faculty = faculty\n",
" self.poeistion = position\n",
" Student.sex = sex\n",
" Student.name = name\n",
" "
]
},
{
"cell_type": "code",
"execution_count": 155,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"#Now let's define lecturers\n",
"\n",
"lecturer_1 = Lecturer('Engineering', 'Professor', 'Male', 'John Traversy')"
]
},
{
"cell_type": "code",
"execution_count": 156,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"John Traversy\n"
]
}
],
"source": [
"print(lecturer_1.name)"
]
},
{
"cell_type": "code",
"execution_count": 157,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Male\n"
]
}
],
"source": [
"print(lecturer_1.sex)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.3"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment