You are on page 1of 25

Chapter 2

How Python Runs Programs


Outline
Introduction to Python
Key Python coding concepts and conventions
Data types and variable names, and assignment operators
Introduction to the coding challenge
Introducing the Python Interpreter

- A layer of software logic between your code and the computer hardware on
your machine
- When Python package is installed on your machine, it generates a number of
components including at least:
1) an interpreter
2) a support library
- Python interpreter may take the form of an executable program, or a set of
libraries linked into another program
- Interpreter itself may be implemented as a C program, a set of Java classes,
or something else.
What do we need to run Python on our machines?
- Python interpreter on your computer
- Python installation details vary by platform:
1) Windows users fetch and run a self-installing executable file that puts
Python on their machines. Simply double-click and say Yes or Next at all
prompts.
2) Linux and Mac OS X users probably already have a usable Python
preinstalled on their computers—it’s a standard component on these
platforms today.
3) Other platforms have installation techniques relevant to those platforms.
For instance, Python is available on cell phones, game consoles, and
iPods, but installation details vary widely.
Resources to download
- You can download it from downloads page on the website,
https://www.python.org/. It may also be found through various other
distribution channels.
- Keep in mind that you should always check to see whether Python is already
present before installing it.
- On Unix and Linux, Python probably lives in your /usr directory tree. Because
installation details are so platform-specific, we’ll finesse the rest of this story
here.
- Google Colaboratory
- Jupyter notebooks
Program Execution
As Programmers:
- A Python program is just a text file containing Python statements.
- For example, the following file, named script0.py, is one of the simplest
Python scripts
- I could dream up, but it passes for a fully functional Python program:
print('hello world') # prints hello world
print(2 ** 100) # prints 2 to the power 100
Python’s View

- More details to get the full picture


- When you instruct Python to run your script, there are a few steps that Python
carries out before your code actually starts crunching away.
1) Specifically, it’s first compiled to something called “byte code”.
2) It is then routed to something called a “virtual machine”
Byte Code
Python first compiles your source code (the statements in your file) into a format
known as byte code. Compilation is simply a translation step, and byte code is a
lower-level, platform-independent representation of your source code. Roughly,
Python translates each of your source statements into a group of byte code
instructions by decomposing them into individual steps. This byte code translation
is performed to speed execution—byte code can be run much more quickly than
the original source code statements in your text file.
Python Virtual Machine (PVM)
After compiling the program into a byte code (or the byte code has been loaded
from existing files), it is shipped off for execution to something generally known as
the Python Virtual Machine (PVM, for the more acronym-inclined among you). The
PVM sounds is nothing but a program within Python that you have installed, and it
needs not be installed by itself. In fact, the PVM is just a big loop that iterates
through your byte code instructions, one by one, to carry out their
operations. The PVM is the runtime engine of Python; it’s always present as part
of the Python system, and it’s the component that truly runs your scripts.
Technically, it’s just the last step of what is called the “Python interpreter.”
What is different from other programming languages?
- For one thing, there is usually no build or “make” step in Python work: code
runs immediately after it is written. For another, Python byte code is not binary
machine code (e.g., instructions for an Intel chip). Byte code is a Python-
specific representation. This is why some Python code may not run as fast as
C or C++ code. (the PVM loop, not the CPU chip, still must interpret the byte
code, and byte code instructions require more work than CPU instructions.
Storing information in variables

- You can think of variables as a label for one or more pieces of information.
When doing analysis in python, all of your data (the variables you measured
in your study) will be stored as variables. You can also create variables for
other things too, which we will learn later on in the course.
- Examples:

Variable Value

Customer id 12347

First name Adam

Gender Male

Annual Income 100000


Storing information in variables

- We'll begin with customer id. As a rule, all variables need to be single words without spaces, otherwise
python will throw a Syntax Error. Use underscores _ instead of spaces. It's best practice to also use
lowercase letter for variable names and to use names that are meaningful. For example, customer_id is
more descriptive then ci and uses an underscore instead of a space. Now that we have some basic rules
down, let's create the variable customer_id. We do this by using a special operator called the assignment
operator denoted by a single equal sign, =. The name of the variable is on the left side of the equals sign and
the value being assigned is on the right.

customer_id = 12345

To see the value referenced in a variable, type in the variable name.

customer_id

12345
Reserved Keywords
Avoid using the following reserved python words as variables names.
- Data types: categorize value in memory
e.g., int for integer, float for real number, str used for storing strings in
memory
- Numeric literal: number written in a program
No decimal point considered int, otherwise, considered float
Some operations behave differently depending on data type
- Can we convert from one data-type to another?
Built-in functions convert between data types
- int(item) converts item to an int
- float(item) converts item to a float
- Nested function call: general format: function1(function2(argument))
value returned by function2 is passed to function1
- Type conversion only works if item is valid numeric value, otherwise,
throws exception
Performing Calculations
•Math expression: performs calculation and gives a value
Math operator: tool for performing calculation
Operands: values surrounding operator
Variables can be used as operands
Resulting value typically assigned to variable
•Two types of division:
/ operator performs floating point division
// operator performs integer division
Positive results truncated, negative rounded away from zero
Operator Precedence and Grouping with Parentheses

•Python operator precedence:


Operations enclosed in parentheses
- Forces operations to be performed before others
Exponentiation (**)
Multiplication (*), division (/ and //), and remainder (%)
Addition (+) and subtraction (-)
•Higher precedence performed first
Same precedence operators execute from left to right
The Exponent Operator and the Remainder Operator

•Exponent operator (**): Raises a number to a power


x ** y = xy
•Remainder operator (%): Performs division and returns the
remainder
a.k.a. modulus operator
e.g., 4%2=0, 5%2=1
•Typically used to convert times and distances, and to detect odd or even
numbers
Converting Math Formulas to Programming Statements

•Operator required for any mathematical


operation
•When converting mathematical expression
to programming statement:
May need to add multiplication operators
May need to insert parentheses
Mixed-Type Expressions and Data Type Conversion

•Data type resulting from math operation depends on


data types of operands
Two int values: result is an int
Two float values: result is a float
int and float: int temporarily converted to float, result of the
operation is a float
Mixed-type expression
•Type conversion of float to int causes truncation of fractional part
Breaking Long Statements into Multiple Lines

•Long statements cannot be viewed on screen


without scrolling and cannot be printed without
cutting off
•Multiline continuation character (\): Allows to
break a statement into multiple lines
result = var1 * 2 + var2 * 3 + \
var3 * 4 + var4 * 5
Breaking Long Statements into Multiple Lines

•Any part of a statement that is enclosed in parentheses


can be broken without the line continuation character.
print("Monday's sales are", monday,
"and Tuesday's sales are", tuesday,
"and Wednesday's sales are", Wednesday)
total = (value1 + value2 +
value3 + value4 +
value5 + value6)
More About Data Output

● print function displays line of output


Newline character at end of printed data
Special argument end='delimiter' causes print to place
delimiter at end of data instead of newline character
● print function uses space as item separator
Special argument sep='delimiter' causes print to use
delimiter as item separator
Formatting Numbers

•Can format display of numbers on screen using built-in


format function
Two arguments:
Numeric value to be formatted
Format specifier
•Returns string containing formatted number
•Format specifier typically includes precision and data type
Can be used to indicate scientific notation, comma separators, and the minimum field
width used to display the value
More About Data Output (cont’d.)

•Special characters appearing in string literal


Preceded by backslash (\)
Examples: newline (\n), horizontal tab (\t)
Treated as commands embedded in string
•When + operator used on two strings in performs
string concatenation
Useful for breaking up a long string literal
Coding Challenge
Please refer to the notebook where all instructions are there.
Submit your work to the following link.

You might also like