User Tools

Site Tools


python:dierbach:chapter_2_data_and_expressions

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
python:dierbach:chapter_2_data_and_expressions [2016/07/29 01:36] mithatpython:dierbach:chapter_2_data_and_expressions [2016/07/29 03:03] (current) mithat
Line 2: Line 2:
 ~~NOTOC~~ ~~NOTOC~~
  
-====== Data and Expressions ====== 
-Mithat Konar\\  
-based on Dierbach's //[[http://www.wiley.com/WileyCDA/WileyTitle/productCd-EHEP002046.html|Introduction to Computer Science using Python]]//. 
 ===== Contents ===== ===== Contents =====
  
Line 231: Line 228:
   * Get a list of keywords:   * Get a list of keywords:
  
-<code>+<code python>
 >>> help() >>> help()
 help> keywords help> keywords
-...+# table of keywords appears
 help> quit help> quit
 >>>  >>> 
Line 287: Line 284:
 print('Tab: $', format(tab - amt_certificate, '.2f')) print('Tab: $', format(tab - amt_certificate, '.2f'))
 print('(negative amount indicates unused amount of gift certificate)') print('(negative amount indicates unused amount of gift certificate)')
 +
 </code> </code>
 ===== Operators ===== ===== Operators =====
Line 298: Line 296:
 ===== Arithmetic operators ===== ===== Arithmetic operators =====
  
-Demonstration of simple table syntax. +^symbol      ^operator         ^example         ^result  ^ 
- Right^Left  ^  Center  ^Default+|-x          |negation         |-10             |-10     | 
-|     12|12       12    |12     | +|x + y       |addition         |10 + 25         |35      | 
-   123|123   |   123    |123    +|x - y       |subtraction      |10 - 25         |-15     | 
-     1|    |        |     |+|x * y       |multiplication   |10 * 5          |50      
 +|x / y       |division         |25 / 10         |2.5     | 
 +|x %%//%% y  |truncating div.  |25 %%//%% 10    |2       | 
 +|            |                 |25 %%//%% 10.0  |2.0     | 
 +|x % y       |modulus          |25 % 10         |2.0     | 
 +|x %%**%% y  |exponentiation   |10 %%**%% 2     |100     | 
 + 
 +===== Example: Your Place in the Universe ===== 
 + 
 +PlaceInUniverse.py 
 + 
 +<code python> 
 +# Your Place in the Universe Program 
 + 
 +# This program will determine the approximate number of atoms that a person is 
 +# person consists of and the percent of the universe that they comprise 
 + 
 +# Initialization 
 +num_atoms_universe = 10e80 
 +weight_avg_person = 70  # 70 kg (154 lbs) 
 +num_atoms_avg_person = 7e27 
 + 
 +# Program greeting 
 +print('This program will determine your place in the universe.'
 + 
 +# Prompt for user's weight 
 +weight_lbs = int(input('Enter your weight in pounds: ')) 
 + 
 +# Convert weight to kilograms 
 +weight_kg = 2.2 * weight_lbs 
 + 
 +# Determine number atoms and percentage of universe 
 +num_atoms = (weight_kg / weight_avg_person) * num_atoms_avg_person 
 +percent_of_universe = (num_atoms / num_atoms_universe) * 100 
 + 
 +# Display results 
 +print('You contain approximately', format(num_atoms, '.2e'), 'atoms'
 +print('Therefore, you comprise', format(percent_of_universe, '.2e'), 
 +      '% of the universe'
 + 
 +</code> 
 +===== Expressions and Data Types ===== 
 + 
 +{{http://mkonar.org/assets/img/cat-silhouette-01-trans-64px.png}} 
 + 
 +===== What is an expression? ===== 
 + 
 +  * **expression**: a combination of symbols that evaluates to a value. 
 +  * ''%%4 + (3 * k)%%'' is an expression. 
 +    * Has two subexpressions: 
 +      * ''%%4%%'' 
 +      * ''%%(3 * k)%%'' 
 +        * Has two **subexpressions**: 
 +          * ''%%3%%'' 
 +          * ''%%k%%'' 
 + 
 +===== Operator precedence and associativity ===== 
 + 
 +  * **operator precedence** determines which operations happen first. 
 +  * **operator associativity** determines the order when two operands have the same precedence. 
 + 
 +===== Python’s rules ===== 
 + 
 +  * Similar to math. 
 +  * So far we have: 
 + 
 +^operator       ^associativity 
 +|%%**%%         |right to left  | 
 +|- (negation)   |left to right  | 
 +|*, /, %%//%%, %|left to right  | 
 +|+, -           |left to right  | 
 + 
 +===== Examples ===== 
 + 
 +<code python> 
 +>>> 6 - 3 + 2 
 +
 +>>> 2 * 3 / 4 
 +1.5 
 +>>> 2 ** 3 
 +
 +>>> 2 ** 3 ** 2  # exponentiation is r-to-l 
 +512 
 +</code> 
 +===== What is a data type? ===== 
 + 
 +  * Python differentiates between types of data. 
 +  * So far we have seen character strings and numbers. 
 +  * **data type**: a set of values and a set of operators that may be applied to those values. 
 +  * ''%%+%%'' on a number is different than on a string. 
 +  * can’t do ''%%/%%'' on a string. 
 + 
 +===== Python’s basic types ===== 
 + 
 +  * Python has many [[https://docs.python.org/3/library/stdtypes.html|built-in types]]. 
 +    * ''%%string%%'' : character strings 
 +    * ''%%int%%'' : integer values 
 +    * ''%%float%%'' : floating point (i.e., real) values 
 +    * ''%%bool%%'' : ''%%True%%'' or ''%%False%%'' 
 +  * Use ''%%type()%%'' to get the type of a variable or literal. 
 + 
 +<code python> 
 +>>> type(66) 
 +<class 'int'> 
 +>>> type(3.1) 
 +<class 'float'> 
 +>>> type(True) 
 +<class 'bool'> 
 +>>> type(3.1) 
 +<class 'float'> 
 +</code> 
 +===== Static versus dynamic typing ===== 
 + 
 +  * Python is a **dynamically typed** language. 
 +  * The same variable can store different type values at different times. 
 + 
 +<code python> 
 +x = 41 + 1 
 +print(x) 
 +x = 'I ate a donut.' 
 +print(x) 
 +x = False 
 +print(x) 
 +</code> 
 +  * In **statically typed** languages, once a variable is associated with a type, the type can’t be changed. 
 + 
 +===== Mixed-type expressions ===== 
 + 
 +  * Example: ''%%3 + 1.2%%'' 
 + 
 +===== Type coercion ===== 
 + 
 +  * **type coercion**: the implicit (and automatic) conversion of one type to another. 
 + 
 +''%%3 + 1.2%%'' -> ''%%3.0 + 1.2%%'' -> 4.2 
 + 
 +===== Type conversion ===== 
 + 
 +  * **type conversion**: explicitly converting one data type to another. 
 + 
 +<code python> 
 +>>> str(42)    # convert into to string 
 +'42' 
 +>>> int('42' # convert string to int 
 +42 
 +>>> int(3.9)   # convert float to int 
 +
 +>>> float('99') # convert int to float 
 +99.0 
 +>>> int('99.9') # nope 
 +Traceback (most recent call last): 
 +  File "<stdin>", line 1, in <module> 
 +ValueError: invalid literal for int() with base 10: '99.9' 
 +</code> 
 +===== Example: Temperature Conversion Program ===== 
 + 
 +TempConversion.py 
 + 
 +<code python> 
 +# Temperature Conversion Program (Fahrenheit to Celsius) 
 + 
 +# This program will convert a temperature entered in Fahrenheit 
 +# to the equivalent degrees in Celsius 
 + 
 +# program greeting 
 +print('This program will convert degrees Fahrenheit to degrees Celsius'
 + 
 +# get temperature in Fahrenheit 
 +fahrenheit = float(input('Enter degrees Fahrenheit: ')) 
 + 
 +# calc degrees Celsius 
 +celsius = (fahrenheit - 32) * 5 / 9 
 + 
 +# output degrees Celsius 
 +print(fahrenheit, 'degrees Fahrenheit equals', 
 +       format(celsius, '.1f'), 'degrees Celsius'
 + 
 +</code>
  
python/dierbach/chapter_2_data_and_expressions.txt · Last modified: 2016/07/29 03:03 by mithat

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki