Learner objectives for this lesson
Python was created by Guido van Rossum in the late 1980s. It is an open source, general-purpose language. It is flexible and powerful, yet still simple enough to be quickly picked up by new programmers. Python is fairly high on the high-level programming languages spectrum, meaning its syntax and grammar is fairly close to pseudo-code.
Python can be run on any computer architecture, so long as a Python interpreter is installed on the machine. This is similar to Java in the sense that as long as Java (more specifically, a Java Virtual Machine) is installed on your computer (you've seen the pesky Java update dialogs), you can run Java code written on any other architecture. It is convenient, cross-platform approach to application development. In contrast to interpreted languages, compiled languages are translated into specific computer architecture machine code (i.e. for a specific Intel processor instead of an AMD processor). Interpreted languages, such as Python and Java, tend to run slower than compiled languages, such as C and Fortran.
An IDE is a program we use to write other programs. It conveniently combines editing of source code with running your program.
IDEs provide a variety of tools to assist programmers, for example:
In this class, programs will execute in a text-based window called a console
In the real world, many programs have a graphical user interface (GUI). We will touch on GUI programming, but it is beyond the scope of this course. Major in computer science and take upper-division CS classes, you will learn GUI programming then :)
Say we want to write a program to compute the volume of a cone, such as the one hosted on Google Search:
What information would we need?
How would we relate that information to produce a result?
How would we interact with the user?
How would we test such a program for correctness?
These are all questions you will start to think when solving problems algorithmically.
Problem input: radius (of the base), height (of the cone)
Problem output: volume (of the cone)
$ volume = 1 / 3 * pi * radius^2 * height $
Algorithm
# get radius from userasdjf;lksadjgf;lkdsagalskjfd
print("Please enter the radius of a cone")
radius = float(input())
# get height from user
print("Please enter the height of a cone")
height = float(input())
# use relevant formula to compute volume
volume = 1 / 3 * 3.14 * radius ** 2 * height
# display result to user
print("The volume of a cone with radius %.2f and height %.2f is %.2f" %(radius, height, volume))
Please enter the radius of a cone 5 Please enter the height of a cone 10 The volume of a cone with radius 5.00 and height 10.00 is 261.67
# a useful statement to describe the code
The above instruction is an example of a single line comment. Comments are ignored by the Python interpreter. Single line comments are denoted by a #
symbol; any code after the #
symbol is simply text and is not going to be run by Python.
'''
this is a multi line
comment block
it spans multiple lines
'''
"""triple double quote"""
Use comments liberally in your code! They help others read your code (including yourself, months later when it isn't so fresh in your mind). In this class, you will be required to comment your code by adhering to the CptS 111 Python Coding Standard.
Python has reserved several identifiers as keywords that have special meaning about the nature of your program. You cannot use reserved keywords as user-defined identifiers in your program. Examples of reserved keywords include True
, False
, None
, and
, or
, not
, if
, else
, elif
, in
, is
, pass
, return
, for
, while
, etc. In the near future, you will learn about these keywords and what they do!
Represent names of built-in variables (data) and functions (operations) in Python, such as print
and input
. It is not recommended to redefine these identifiers.
print(<text to display>)
displays text to the screeninput()
reads input from the keyboardMemory cells to store data ("variables") that are named by the programmer for computations. We will also later be able to name our own algorithms ("functions").
radius
to store the radius of a cone, versus my_variable
)cone_volume
)Note: Python is case sensitive.
Declaring a variable reserves memory space for a value. It also associates a name with a memory cell (user-defined identifier).
height = float(input())
10
The above instruction declares a variable called radius
and stores the value 0.0
in the memory location associated with radius
. radius
is an example of a user-defined identifier.
All variables have an associated data type. A data type is a set of values and a set of operations on those values. Examples of data types include:
"5" + "7"
returns the string "57" because "5" and "7" are strings, not integers.If you want to find out what data type a variable is, Python will tell you. Use the function type(<variable name.)
to find out.
x = 5
print(type(x))
x = 5.0
print(type(x))
my_str = "hello"
print(type(my_str))
<class 'int'> <class 'float'> <class 'str'>
Do the work of the algorithm by transforming inputs into outputs. For example, consider the volume of the cone example:
volume = 1 / 3 * 3.14 * radius ** 2 * height
When the code statement above is executed by Python (the program is running), Python evaluates the expression on the right hand side of the assignment operator (=), and assigns the result to the variable volume
.
Python evaluates arithmetic expressions according to the same order of operation precedence you are familiar with (think PEMDAS: Parenthesis, Exponents, Multiplication, Division, Addition, Subtraction), plus a few more operators.
Check out this Python precedence table to learn more.
Store a computational result into a variable
The assignment operator '=' in programing is not the same as = in math
Clearly not mathematically "equal"
We can also assign the value of one variable to another:
x = 5 # declare a new variable, x, and assign it the integer 5
y = x # declare a new variable, y, and assign it the value of x (which is 5)
y = -x # compute the negation of x (-5) and assign it to y
Code such as, x = x + 1
is quite common, in fact, it is so common that Python has a shorthand operator (+=) to shorten this code: x += 1
. There are other shorthand operators for other arithmetic operators too:
x = 0
print(x)
x = x + 1
print(x)
x += 3
print(x)
x -= 3
print(x)
x *= 5
print(x)
0 1 4 1 5
It is extremely useful to obtain input data interactively from the user, and to display output results to the user
Python offers several functions that perform input and output operations.
Begin Digression: Functions
A function is a set of statements that perform a task. A function performs the task, hiding from you the details of how it performs the task (they're irrelevant). We'll study functions in depth!
End Digression
The print()
function is used to display text output of the program to the user, via the console. We have already seen the print()
function in action:
print("The volume of a cone with radius %.2f and height %.2f is %.2f" %(radius, height, volume))
The volume of a cone with radius 5.00 and height 10.00 is 261.67
The text in red and surrounded by quotes is called a string, which is a sequence of characters. This is what will be displayed to the screen.
The %.2f
is called a placeholder for a floating point number (i.e. the f) with 2 decimal places (i.e. the .2). %d
is used as placeholder for integers and %s
is used as a placeholder for strings.
The variable names at the end of the statement in parenthesis are the list of values corresponding to the placeholder (order matters!). The value of radius
will be inserted at the first placeholder, the value of height
for the second, and the value of volume
for the third. Do you see that order matters?
Note: Adding "\n"
to a string will print a newline character, a non-printable character that starts the cursor on a new line. This can be useful if you want to add extra space between text without writing extra print()
statements.
print("Standard spacing")
print("Adding extra space with the newline character\n")
print("**Next line**")
Standard spacing Adding extra space with the newline character **Next line**
radius = float(input())
5
This statement forces the program to pause until the user enters a value from the keyboard and hits the return key. input()
returns a string representation of the text entered by the user (recall a string is a sequence of characters). Since we want to assign a floating point number to the variable radius
for use in arithmetic computation later, we type cast the string entered by the user into a value of type float
.
Notes on input/output:
input()
should always be used in conjunction with a print()
statement that displays a prompt, so that the user knows that an input value is expected.input()
: radius = float(input("Please enter the radius"))
. In this case, the inner-most function (input()
) is executed first. Once the user has pressed enter and the value is read in, the value is converted to a float by the type cast.help()
¶If you want more information about how to use a function, such as print()
, ask Python! Type help(<identifier name>)
to get more information about a variable, data type, function, etc.
help(print)
Help on built-in function print in module builtins: print(...) print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False) Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments: file: a file-like object (stream); defaults to the current sys.stdout. sep: string inserted between values, default a space. end: string appended after the last value, default a newline. flush: whether to forcibly flush the stream.
The process of locating and fixing errors in your programs is called debugging. There are 3 types of errors that can occur in a program:
print("hello"
5 / 0
Following Lab 0, you should have downloaded and installed Anaconda3. This is the Python distribution we are going to use for this class. Follow these steps to run the volume of a cone code from above: 1. Launch the Spyder IDE (integrated development environment). 1. Copy and paste the volume of a cone code into the left panel's text editor. 1. Save the program as cone_volume.py. Press the run button (the green play button) on the toolbar or press F5 on your keyboard to run the program. 1. In the right panel of Spyder, your code should be running in the console, cool!
Arithmetic in Python!