{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Introduction to Python for engineers\n", "\n", "\n", "Around 7 years ago I have come across this beautiful language and fell in love with it! It helped me with my classes, my PhD carreer, my teaching and many other things. \n", "\n", "As every language consists of words and sentences programming language consists of variables, operators. We first will learn what they are, why do we need them. Then we will start constructing our first \"sentences\" - writing programs to solve our engineering problems.\n", "\n", "Here are the main elements that we will learn today.\n", "\n", "1. Python syntaxis\n", "2. Arithmetic operations in Python\n", "3. Conditionals\n", "4. Loops\n", "5. Functions\n", "\n", "These are the basic elements of every language. Don't consider them to be your goal, these are the tools. The best thing you can do with tools is to use them. So go ahead and start solving the problems right away! \n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Variables and arithmetic operations\n", "\n" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "# the first thing that you will need in Python are variables\n", "# You can assign a value to them and perform arithmetic operations with them\n", "a = 1\n", "b = 2" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n" ] } ], "source": [ "# If you want to see their values you can use the `print()` function\n", "\n", "print(a)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "-1\n" ] } ], "source": [ "#here is how to perform simple arithmetic operations with those variables\n", "\n", "c = a - b \n", "print(c)" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2 0.5 3.0\n" ] } ], "source": [ "# going further\n", "d = a*b\n", "e = a/b\n", "f = 9**(0.5)\n", "# if you want to print several variables, just list them with a comma\n", "print(d, e, f)" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n", "\n" ] } ], "source": [ "#NOTE:\n", "\n", "#python variables can have different type:\n", "# integer:\n", "a1 = 1\n", "# float\n", "f1 = 1.0\n", "#string\n", "s1 = \"1\"\n", "\n", "#although for us it is the same number, these are different variables for Python\n", "print(type(a1))\n", "print(type(f1))\n", "print(type(s1))\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Project 1\n", "\n", "Enough discussion lets do our first little project. Lets calculate the area of a triangle with sides (x = 3, y = 4, z = 5) using the formula:\n", "\n", "1. Using Phales's theorem $A = \\sqrt{s\\cdot(s-x)(x-y)(s-z)}$, where $s = x + y + z$\n" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [], "source": [ "# First lets assign values to variables \n", "\n", "x = 3\n", "y = 4\n", "z = 5\n", "\n", "#lets calculate the perimeter of the triangle \n", "s = (x+y+z)/2.0\n", "\n", "# now using s, lets calculate the area\n", "A = (s*(s-x)*(s-y)*(s-z))**0.5" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "8.0\n" ] } ], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Project 2\n", "\n", "Calculate the area of a triangle if its base $b = 30$, its height $h = 40$\n", "\n", "### Project 3\n", "\n", "Calculate the area of a trapezoid if its base $b1 = 5$, its height $h = 2$ and the length of the top side $a = 3$.\n", "\n", "### Project 4\n", "\n", "Lets get a problem from the world closer to engineering.\n", "Calculate the pressure of two moles of ideal gas, at temperature $T = 27 C$, and volume $V = 1 litre$\n" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2493000.0\n" ] } ], "source": [ "h = 40\n", "b = 30\n", "A = 0.5*h*b\n", "\n", "#area of a trapz\n", "a1 = 3\n", "b1 = 5\n", "h = 2\n", "A_trapezoid = h*(a1+b1)/2\n", "print(A_trapezoid) # use tab for autocomplete\n", "\n", "\n", "#CHBE problem\n", "V = 1 #l\n", "R = 8.31 #J/(mol K)\n", "T = 27 #C\n", "n = 1\n", "#if n = 1\n", "#p ?\n", "P = n*R*(T+273)/(V/1000.)\n", "print(P)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Conditionals\n", "\n", "Sometimes we want to compare values and proceed if only a certain condition is met. In these cases we use `if ... elseif ... else` statements.\n", "But before we start, let me introduce you to another data type - Boolean.\n", "It can have only two values `True, False`, but it is crucial for the design of many important algorithms in the modern computer science.\n" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [], "source": [ "# the boolean operators can be a result of conditional operations \n", "# 2 >= 1 = True\n", "# For example\n", "if 1>2:\n", " print(\"This is false\")" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "I am in else\n" ] } ], "source": [ "if 2<1:\n", " print(\"I am in the if\")\n", "elif 0>2:\n", " print(\"I am in the elif\")\n", "else:\n", " print(\"I am in else\")\n" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "I will no go here\n" ] } ], "source": [ "# Boolean operators can be \"multiplied/added\" with and/or\n", "# True and False = False\n", "# True and True = True\n", "# False and False = False\n", "# True or False = True\n", "# True or True = True\n", "# False or False = False\n", "\n", "if (True) or (False):\n", " print(\"I will no go here\")\n", "if (True) and (False):\n", " print(\"I will no go here\")\n", " " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "One reason why I love Python is its flexibility. Unlike Matlab that comes with lots of packages pre-installed and important, he core of of Python doesn't have virtually anything.\n", "To get the full power of Python we have to import libraries that we will need.\n", "To do that we use the `import` operator.\n", "\n", "`import random` imports the library for generating random numbers.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#random things\n", "import random\n", "r = random.randint(1,10)\n", "print(r)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Project 5\n", "\n", "Imagine you play a game of dice with your professor. We will call him Dr. Vikram. You pick a random number and compare it with Dr. Vikram's number which is `5`. If the difference between your number and Dr. Vikram's number is not larger than 1 then Dr. Vikram wins, if the difference is greater than 1 but not larger than 2, then you win! In all of other cases you noone wins. Your job is to write a program to simulate this game." ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "6\n", "vikram wins\n" ] } ], "source": [ "import random\n", "r = random.randint(1,10)\n", "print(r)\n", "vikram_number = 5\n", "if (vikram_number - r)<=1:\n", " print(\"vikram wins\")\n", "elif (vikram_number - r)<=2:\n", " print(\"felicia wins\")\n", "else:\n", " print(\"chbe wins\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Lists and loops\n", "\n", "By this stage, we have learned the basics of Python: variables, arithmetic operations, conditionals. However, sometimes we want to group data and explore a set of parameters, e.g. a set of pressure values in the tube. What " ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1.0, 2.0, 3.0, 4.0]\n" ] } ], "source": [ "#lists\n", "\n", "a_list = [1.0, 2.0, 3.0, 4.0]\n", "print(a_list)" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "second last element = 3.0\n" ] } ], "source": [ "# list numbering starts from 0 and goes until N-1\n", "# to access its first element we use \n", "a_list[0]\n", "# the third\n", "a_list[2]\n", "# the 4th\n", "a_list[3]\n", "# another way to get the last element is to use `-1`\n", "a_list[-1]\n", "# as you could have guessed, the second last element is [-2]\n", "a_list[-2]\n", "\n", "print(\"second last element = \", a_list[-2])" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[2.0, 3.0, 4.0]" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# There are cool ways to access parts of an array:\n", "# e.g. all the elements starting from the second one\n", "a_list[1:]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Loops\n", "\n", "Now, to systematically access elements of a list we need to use loops. Python has two types of loops: `for` which goes through the elements of a list (actually they are generators in Python3, but lets not get too bookwarmy here) and `while` loop, but I won't mention it here for now." ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1.0\n", "2.0\n", "3.0\n", "4.0\n" ] } ], "source": [ "# Lets print all of the elemenet of the a_list \n", "for i in a_list:\n", " print(i)" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1.0\n", "4.0\n", "9.0\n", "16.0\n" ] } ], "source": [ "# What if I want to print the values of the a_list squared\n", "for i in a_list:\n", " print(i**2) " ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "4" ] }, "execution_count": 24, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# to get the length of the list we use the len function\n", "len(a_list)" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n" ] } ], "source": [ "# another way to work with loops is to go over its elements \n", "# for this we need to generate a list of indices\n", "for i in range(len(a_list)):\n", " print(i)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Project 6 \n", "\n", "Do you remember Project 4, where we had to calculate the pressure of an ideal gas at certain temperature? Now I have a list of temperatures `t_list = [27, 60, 100, 150, 200]` and I want to calculate a list of pressures `P_list` corresponding to those temperatures. I remind that temperatures here are in `C`, there are two moles of gas, and volume of the vessel $V = 1 litre$\"." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Functions\n", "\n", "Ok ... hang in there! We are almost there!\n", "\n", "Lets get familiar with Functions.\n", "\n", "Why do we need them?\n", "\n", "Well ... sometimes we want to separate blocks of code into a block of its own. For that we use functions.\n" ] }, { "cell_type": "code", "execution_count": 41, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "myparam = 2\n", "2\n" ] } ], "source": [ "# Here is how we define Python functions\n", "\n", "def name_of_a_func(input_param):\n", " print(\"myparam = \", input_param)\n", " return input_param\n", "\n", "# here is how to call it\n", "\n", "b = name_of_a_func(2)\n", "print(b)" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "30.48" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# lets do a little project\n", "# lets write a function that converts inches to cm (1 inch = 2.54 cm)\n", "\n", "def inch_2_cm(param_inch):\n", " return param_inch*2.54\n", "\n", "inch_2_cm(12)" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "32.0" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Now lets write a function that convert temperature from degrees centigrade to Farenheit\n", "#Tf = 1.8*Tc + 32 \n", "\n", "def C_to_F(Tc):\n", " return Tc*1.8 + 32.\n", "\n", "# lets call the function\n", "C_to_F(0)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Project 8\n", "\n", "Now lets do something that will require almost all of the elements that we have learned today.\n", "Lets calculate ... Fibonacci sequence! I remind you a Fibbonacci sequence \n", "\n", "$F_{n}=F_{n-1}+F_{n-2}$\n", "with seed values: \n", "$F_{1}=0, F_{2}=1$\n", "\n", "Lets write a function that calculates n-th element of the Fibbonacci sequence." ] }, { "cell_type": "code", "execution_count": 47, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "myfib = 1\n", "myfib = 2\n", "myfib = 3\n", "myfib = 5\n", "myfib = 8\n", "myfib = 13\n", "myfib = 21\n", "myfib = 34\n", "fsum 87\n" ] }, { "data": { "text/plain": [ "87" ] }, "execution_count": 47, "metadata": {}, "output_type": "execute_result" } ], "source": [ "nterm = 10\n", "def Fib_sum(nterm):\n", "# f_sum \n", "# f_sum = 0 + 1+ 1 + 2 + 3 ...\n", "# if nterm = 0 => f_sum = 0\n", "# if nterm = 1 => f_sum = 1\n", "# nterm>1 => f_sum = sum (i =0, 1 ....[(n-1)+(n-2)])\n", " if nterm == 0:\n", " return 0\n", " elif nterm == 1:\n", " return 1\n", " else:\n", " f_sum = 0\n", " my_n_fib_number_old = 0\n", " my_n_fib_number_new = 1\n", " for i in range(2,nterm):\n", " my_n_fib_number = my_n_fib_number_new + my_n_fib_number_old\n", " print(\"myfib = \", my_n_fib_number)\n", " f_sum = f_sum + my_n_fib_number\n", " my_n_fib_number_old = my_n_fib_number_new\n", " my_n_fib_number_new = my_n_fib_number\n", " print(\"fsum \", f_sum)\n", " return f_sum\n", "Fib_sum(10)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Bibliography:\n", "\n", "\n", "http://www.science.uwaterloo.ca/~cchieh/cact/c120/idealgas.html\n", "\n", "https://en.wikipedia.org/wiki/Fibonacci_number" ] } ], "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.4" } }, "nbformat": 4, "nbformat_minor": 2 }