#!/usr/bin/env python # coding: utf-8 # # 2. Values, expressions and statements # # Open In Colab # # # - http://openbookproject.net/thinkcs/python/english3e/variables_expressions_statements.html # # ## Topics # - data values and types # - variables # - expressions and statements # - numeric operators and basic computations # - order of operations # - standard input and output # - type casting # - Composition and algorithm # # ## 2.1 Values and data types # - a value is one of the fundamental things or data -- like a letter or number -- that a program manipulates # - these values are clssified into types # - Python fundamentally supports two major data types: numbers and strings # - Boolean (True/False) is also supported type # # ### Numbers # - Integer (int) # - +/- whole numbers: 199, -98, 0 # - Float # - +/- real numbers - numbers with decimal points: 99.99, -0.01 # # # ### Strings # - Python uses **str** abbreviation for String type # - strings are one or more characters represent using single, double or tripple quotes # ## 2.2 First program - hello world! # In[1]: #---------------------------------------------------------- # hello world program # by: John Doe # Jan 1, 2017 # Copyright: Anyone may freely copy or modify this program #---------------------------------------------------------- print('hello world!') # say hello to the beautiful world! # In python 2: print is a statement not a function # print 'Hello World!' # ## 2.3 Comments # - Programming languages provide a way to write comment along with the codes # - Python uses \# symbol to write a single line comment # - comments are for humans/programmers to convey/explain what the code is doing or supposed to do # - Python interpreter ignores the comments # ## 2.4 Data Types # - built-in type() function can be used to know type of data # - functions will be covered in Chapter 04 # In[2]: type(100) # In[3]: type(-9) # In[4]: type(1000.99345435) # In[5]: type(-2.345) # In[6]: type('Hello World!') # In[7]: type('A') # In[8]: print("hello") # In[9]: type("17") # In[10]: type("""Triple double quoted data""") # In[11]: type('''Type of Triple single quote data is''') # In[12]: a = "hello" # In[13]: a # ## 2.5 Type conversion/casting # - data needs to be converted from one type to another as needed # - the process is called type casting # - use built-in functions such as str(), int() and float() # - **str(value)** - converts any value into string # - **int(value)** - converts numeric value into int # - **int(value)** - converts numeric value into float # In[14]: data = 'hello' # can't conver it to int or float types # In[15]: type(data) # In[16]: data = '100' type(data) # In[17]: data # In[18]: num = int(data) type(num) # In[19]: num # In[20]: price = float('500.99') type(price) # In[21]: float('hi') # In[22]: num = 99.99 strNum = str(num) type(strNum) # In[23]: type(True) # In[24]: type(False) # ## 2.6 Statements # - a **statement** is an instruction that the Python interpreter can execute # - we've seen assignment statements so far # - we'll later explore for, if, import, while and other statements # ## 2.7 Expressions # - an **expression** is a combination of values, variables, operators, and calls to functions # - expressions are evaluated giving a results # In[25]: 1+2 # In[26]: len('hello') # In[27]: print(2+3*4) # ## 2.8 Standard Output # - printing or writing output to common/standard output such as monitor # - way to display the results and interact with the users of your program # - use print() function # In[28]: print('''"Oh no", she exclaimed, "Ben's bike is broken!"''') # In[29]: print(34.55) # In[30]: print(2+2) # ## 2.9 Escape Sequences # - some letters or sequence of letters have special meaning to Python # - single, double and tripple single or double quotes represent string data # - use backslash \\ to represent these escape sequences, e.g., # - \\n - new line # - \\\\ - back slash # - \\t - tab # - \\r - carriage return # - \\' - single quote # - \\" - double quote # In[31]: print('What\'s up\n Shaq O\'Neal?') # In[32]: print('hello \there...\n how are you?') # In[33]: print('how many back slahses will be printeted? \\\\') # In[34]: print(r'how many back slahses will be printeted? \\\\') # ## 2.10 Variables # - variables are identifiers that are used to store values which can be then easily manipulated # - variables give names to data so the data can be easily referenced by their names over and again # - rules and best practices for creating identifiers and variable names: # - can't be a keyword -- what are the built-in keywords? # - can start with only alphabets or underscore ( _ ) # - can't have symbols such as $, %, &, white space, etc. # - can't start with a digit but digits can be used anywhere else in the name # - use camelCase names or use _ for_multi_word_names # - use concise yet meaningul and unambigous names for less typing and avoid typos # In[35]: help('keywords') # In[36]: # variable must be defined/declared before you can use print(x) # In[37]: x = 'some value' # In[38]: print(x) # In[39]: # Exercise: Define a bunch of variables to store some values of different types var1 = -100 num = -99.99 name = 'John' lName = 'Smith' MI = 'A' grade = 10.5 Name = 'Jake' grade = 19.9 # ## 2.11 Dynamic Typing # - type of variables are dynamically evaluated in Python when the assignment statement is executed # - same variable can be uesd to hold different data types # In[40]: var = 100 # In[41]: var = 'hello' # In[42]: var = 99.89 # In[43]: var # ## 2.12 Visualize variable assignments in pythontutor.com # [Click Here](http://pythontutor.com/visualize.html#code=var1%20%3D%20100%0Anum%20%3D%2099.99%0Aname%20%3D%20'John'%0AlName%20%3D%20'Smith'%0AMI%20%3D%20'A'%0Agrade%20%3D%2010.5%0Agrade%20%3D%2019.9%0AName%20%3D%20'Jake'&cumulative=false&curInstr=0&heapPrimitives=false&mode=display&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false) # ## 2.13 Computation - operators and operands # - **operators** are special tokens/symbols that represent computations like addition, multiplication and division # - the values an operator uses are called **operands** # - some binary operators that take two operands # - addition: 10 + 20 # - subtraction: 20 - 10 # - true division: 10 / 3 # - multiplication: 7 * 9 # - integer division: 10 // 3 # - remainder or modulus operator: 10 % 2 # - power: 2 ** 3 # In[44]: # Exercise: play with some examples of various operators supported by Python # ## 2.14 Order of operations # - depends on the rules of precedence # # **uses PEMDAS rule from high to low order** # # 1. Parenthesis # 2. Exponentiation # 3. Multiplication and Division (left to right) # 4. Addition and Subtraction (left to right) # # In[45]: # some examples print(2 * 3 ** 2) # In[46]: x = 1 y = 2 z = 3 ans = x+y-z*y**y print(ans) # ## 2.15 Operations on strings # - $+$ and $*$ operators also work on strings # - Chapter 08 covers more on string data type and operations # In[47]: # some examples fname = "John" lname = "Smith" fullName = fname + lname print(fullName) # In[48]: gene = "AGT"*10 # In[49]: print(gene) # ## 2.16 Standard input # - read data from standard or common input such as keyboards # - allows your program to receive data during program execution facilitating user interactions # - input values will have type string even if numbers are entered # - use variables to store the data read from standard input # In[50]: name = input('What is your name? ') # In[51]: print('hello,', name) # In[52]: num = input('Enter a number =>') print('You entered: ', num) print('type of', num, '=', type(num)) # In[53]: num # In[54]: # str must be casted into int or float depending on the value required num = int(num) print('type of', num, '=', type(num)) # ## 2.17 Composition # - break a problem into many smaller sub-problems or steps using high-level algorithm steps # - incrementally build the solution using the sub-problems or steps # ## 2.18 Algorithm # - step by step process to solve a given problem # - like a recipe for a food menu # - what are the steps you'd give a martian to buy grocery on earth? # 1. Make a shopping list # - Drive to a grocery store # - Park your car # - Find items in the list # - Checkout # - Load grocery # - Drive home # ## 2.19 Exercises # ### 1. area and perimeter of a rectangle # # - write a python script that calculates area and perimeter of a rectangle # In[55]: # Demonstrate composition step by step # Algorithm steps # 1. Get length and width of a rectangle # a. hard coded values OR # b. prompt user to enter length and width values # i. convert length and width into right data types # 2. Find area = length x width # 3. Find perimeter = 2(length + width) # 4. Display calculated results # ### 2. area and circumference of a circle # - write a python script that calculates area and circumference of a circle # - area of a circle is calculated using equation: $\pi r^{2}$ # - perimeter of a circel is calculated using equation: $2 \pi r$ # - you can use $\pi=3.14159$ # In[56]: # Demonstrate composition step by step # Algorithm steps # ### 3. Body Mass Index (BMI) # - write a python script that calculates BMI of a person # - BMI is body mass in kg divided by the square of body height in meter with the units of $kg/m^2$ # - https://www.nhlbi.nih.gov/health/educational/lose_wt/BMI/bmicalc.htm # ### 4. area and perimeter of a triangle # - write a python script that finds area and perimeter of a triangle given three sides # - Hint: Google and use Heron's formula to find area of triangle # In[ ]: