Introduction to Python Programming

  • Chapter 2: Expressions
Chapter 2 cover

Chapter outline

  • The Python shell
  • Type conversion
  • Mixed data types
  • Floating-point errors
  • Dividing integers
  • The math module
  • Formatting code
  • Python careers

Figure 2.1

  • credit: modification of work "Grace Hopper at Univac I console", courtesy of the Computer History Museum
Grace Hopper at Univac I console

2.1 The Python shell

  • Learning Objectives
  • Use a Python shell to run statements and expressions interactively.
  • Explain the function of the up and down arrow keyboard shortcuts.

2.1 The Python shell

2.1 The Python shell

  • The interpreter
  • Python is an interpreted high-level language: source code is translated one line at a time while the program runs.

  • The Python interpreter translates source to machine code and executes it; on errors it stops and displays a message.

  • A shell (console/terminal) lets you interact directly with the interpreter one line at a time.

2.1 The Python shell

  • Correcting a typo

2.1 The Python shell

  • The arrow keys (REPL history)
  • REPL = 1. Read → 2. Eval → 3. Print → 4. Loop.

  • Most shells maintain a history of every line of code the user types. Pressing the up or down arrow key on the keyboard displays the history.

  • The up arrow displays the previous line; the down arrow displays the next line. That way, the user can repeat a line without having to type the line again.

2.2 Type conversion

  • Learning Objectives
  • Explain how the interpreter uses implicit type conversion.
  • Use explicit type conversion with
    • int()
    • float()
    • str()

2.2 Type conversion

  • Implicit type conversion
  • Python interpreter automatically convert one data type to another.
  • Example: once distance is assigned 252.5, the interpreter converts it from int to float as needed.

2.2 Type conversion

  • Book ratings

2.2 Type conversion

  • Ordering pizza

2.2 Type conversion

  • Explicit conversions
  • int(x) → integer (fractional part removed). Ex: int(5.9)5.
  • float(x) → floating-point. Ex: float(2)2.0.
  • str(x) → string. Ex: str(3.14)"3.14".

2.3 Mixed data types

  • Learning Objectives
  • Identify the data types produce by operations with integers, floats, and strings.

  • Use operators and type conversions to combine integers, floats, and strings.

2.3 Mixed datatypes

  • Combining integers and floats

2.3 Mixed data types

  • Combining integers and floats
  • Often a program needs to combine numbers of different data types.

  • Example: quantity = int(input()),
    price = float(input()),
    total = quantity * pricefloat.

  • Division with / always yields a float.

2.4 Floating-point errors

  • Learning Objectives
  • Explain numerical inaccuracies related to floating-point representation.
  • Use round() to mitigate output issues.

2.4 Floating-point errors

  • Round-off error
  • Computers store information using 0's and 1's. All information must be converted to a sequence of 0's and 1’s.
  • Floating-point values are stored as binary by Python.
    • The conversion of a floating point number to the underlying binary results in specific types of floating-point errors.
  • Many decimals are approximations
  • The difference between the approximation and the true value is called → round-off error.

Table 2.1 Round-off error.

Round-off error examples

Examples of round()

2.4 Floating-point errors

  • Overflow error
  • An overflow error occurs when a value is too large to be stored.
  • The maximum and minimum floating-point values that can be represented are
    1.8×10308
    and
    −1.8×10308 , respectively.
  • Attempting to store a floating-point value outside the range (−1.8×10308,1.8×10308 ) leads to an overflow error.
  • Below, 3.0256 and 3.0512 can be represented, but 3.01024 is too large and causes an overflow error.

Table 2.2 Overflow error.

Overflow error examples

2.5 Dividing integers

  • Learning Objectives
  • Evaluate expressions with floor division and modulo.
  • Use modulo to convert between units.

2.5 Dividing integers

  • Division and modulo
  • True division / → converts to floats, e.g., 7/4 = 1.75.
  • Floor division // → quotient only, e.g., 7//4 = 1.
  • Modulo % → remainder, e.g., 7%4 = 3. Pronounced “mod”.

Quotient and remainder

Money and time

2.5 Dividing integers

  • Unit conversions
  • Division is useful for converting one unit of measure to another. To convert centimeters to meters, a variable is divided by 100. Ex: 300 centimeters divided by 100 is 3 meters.
  • Use // for whole units and % for the remainder (modulus m).
  • Example: 193 cm → meters: 193//100 = 1, remainder: 193%100 = 93.

2.6 The math module

  • Learning Objectives
  • Distinguish built-in functions and math functions.
  • Use functions and constants defined in the math module.

2.6 Importing math into Python

2.6 The math module

  • Importing modules
  • Python standard library provides extensive and reusable modules.
  • module is previously written code that can be imported in a program. The import statement defines a variable for accessing code in a module. Import statements often appear at the beginning of a program.
  • The standard library also defines built-in functions such as print(), input(), and float(). A built-in function is always available and does not need to be imported. The complete list of built-in functions is available in Python's official documentation.
  • A commonly used module in the standard library is the math module. This module defines functions such as sqrt() (square root).

Table 2.3 Example constants in math

math constants

Table 2.4 Example functions math module

math functions

Table 2.5

additional math examples

Table 2.6

additional math examples

2.7 Formatting code

  • Learning Objectives
  • Identify good spacing for expressions and statements.
  • Write multi-line statements using implicit line joining.

2.7 Formatting code

  • Recommended spacing
  • Good spacing:
  • 
    	name = input("Enter someone's name: ")
    	place = input("Enter a famous place: ")
    	print(name, "should visit", place + "!")
    								
  • Poor spacing: 
  • 
    	name=input ("Enter someone's name: " )
    	place =input("Enter a famous place: ")
    	print( name,"should visit" , place+ "!")
    							  

String concatenation

Table 2.7 Guidelines for spaces.

Spacing guidelines

2.8 Python careers

  • Learning Objectives
  • Summarize Python’s use beyond CS and IT.
  • Describe two kinds of applications built with Python.

2.8 Python careers

  • Example job titles: software engineer, data scientist, web developer, systems analyst.
  • These jobs often require a degree in computer science (CS), information technology (IT), or a related field. However, programming is not limited to these fields and careers.
  • Python programs can automate tasks and solve problems quickly. 

Table 2.8 Python outside of CS and IT.

Python outside of CS and IT

Table 2.9 Applications built with Python.

Applications built with Python

Table 2.10 Chapter 2 reference.

Chapter 2 reference

License

  • This ancillary resource is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 (CC BY NC-SA) license; it may be distributed, remixed, built upon for noncommercial purposes only, and must be attributed to OpenStax and redistributed under the same license.