Module #1 (Variables, Statements, Types, and Operators)

Welcome to the first online module for Introduction to Computer Programming! This module is designed to get you up and running with Python on your own computer as well as introduce you to a variety of elementary programming techniques, such as variables, data types, and formatting strings. You should proceed through the content below in a linear fashion. Be sure to take notes as you go on anything that might be confusing - we will go over any questions you may have on the material next week during class.


Installing Python and PyCharm

Note: Before you begin working with the Python programming language you will need to install it onto your computer. Note that if you don’t have your own computer you can use a lab machine in one of the computer labs outlined on the course syllabus.

Required Software:

The video and content below cover the installation of the following required software:

Python

Directions for Microsoft Windows

  1. Visit https://www.python.org/downloads/windows/
  2. Click on 'Latest Python 3 Release - Python 3.x.y'. Do not download any version of Python that begins with a 2! (i.e. Python 2.7 is NOT appropriate for this class). Note that won't actually be a Python 3.x.y version - the 'x' and 'y' could be any number. The important piece here is to ensure that you have Python 3 installed.
  3. Scroll down and click on 'Windows x86-64 executable installer' - download this file to your computer's hard drive.
  4. Once the download completes you can double-click on the file that was downloaded to begin the installation process
  5. You will be asked if you want to run the file that was downloaded - click "Run"
  6. Select "Install for all users" and click Next
  7. You will then be asked to specify a destination directory for Python - you can just click Next here as well.
  8. The following screen asks you to customize your version of Python - you can click Next here.
  9. The installation wizard will begin installing Python onto your computer. You may be asked to confirm this - click "Yes" to continue
  10. Finally, click the Finish button once the installation is complete.

Directions for MacOS

  1. Visit https://www.python.org/downloads/mac-osx/
  2. Click on 'Latest Python 3 Release - Python 3.x.y' - Do not download any version of Python that begins with a 2! (i.e. Python 2.7 is NOT appropriate for this class). Note that won't actually be a Python 3.x.y version - the 'x' and 'y' could be any number. The important piece here is to ensure that you have Python 3 installed.
  3. Scroll down and click on 'Mac OS X 64-bit/32-bit installer' - download this file to your hard drive.
  4. Once the download completes you can double-click on the file that was downloaded to begin the installation process
  5. Hold down the Control key on your keyboard and double-click on the "Python.mpkg" file. Click the "Open" button to continue.
  6. An installation wizard will appear - click the Continue button three times. You will then be prompted to agree to a software license - click Agree.
  7. Click the Install button.
  8. You may need to provide your administrator password to complete the installation process.

PyCharm

Directions for Microsoft Windows

  1. In your browser, go to https://www.jetbrains.com/pycharm/download
  2. Click on 'Community Edition' to Download the PyCharm installer
  3. Once the download completes you can double-click on the file that was downloaded to begin the installation process
  4. The installer will ask if you want to allow the PyCharm installer to make changes to your computer; click "Yes" to allow the installer to continue
  5. You will be presented with a few installation options:
    • Choose a location to install PyCharm (customize the location or leave it at its default value)
    • Optionally, add shorcuts, file assocations, etc. (you can leave these blank / unchecked)
    • Choose a "Start" menu folder to place PyCharm "launcher" (it's okay to leave this at its default value)
  6. Start PyCharm by pressing the windows key to search for PyCharm (start typing in PyCharm) or click on the desktop icon if you chose to add it in the previous steps
  7. Since this is the first time running PyCharm, you will have to go through a few dialog boxes:
    • Choose "Don't import settings"
    • Read and agree to the end user license agreement
    • Configure the user interface theme, plugins, etc. (fill these out to your preference, but note that you are not required to choose a specific theme or install any plugins)
  8. Start a new project
    • You should be able to use the default settings...
    • However, you can use the tree control to expand the "Project Interpreter" options to verify that it has found an appropriate version of Python to use
    • Check the value in the "Base Interpreter" field has a version greater 3.6 somewhere in its file path or file name (there may or may not be a . between the major and minor version numbers)

Directions for MacOS

  1. In your browser, go to https://www.jetbrains.com/pycharm/download
  2. Click on 'Community Edition' to Download the PyCharm installer
  3. Once the download completes you can double-click on the file that was downloaded to begin the installation process
  4. Open the .dmg file (if it doesn't automatically open)
  5. Drag the PyCharm community edition app to your applications folder
  6. Start PyCharm by going into the Applications folder and clicking on the PyCharm icon
  7. Since this is the first time running PyCharm, you will have to go through a few dialog boxes:
    • Choose "Don't import settings"
    • Read and agree to the end user license agreement
    • Configure the user interface theme, plugins, etc. (fill these out to your preference, but note that you are not required to choose a specific theme or install any plugins)
  8. Start a new project
    • You should be able to use the default settings...
    • However, you can use the tree control to expand the "Project Interpreter" options to verify that it has found an appropriate version of Python to use
    • Check the value in the "Base Interpreter" field has a version greater 3.6 somewhere in its file path or file name (there may or may not be a . between the major and minor version numbers)

Using PyCharm & Writing your first program

This part of the module goes over creating a small program to demonstrate basic usage of PyCharm.

These modules are shared with CSCI-UA.0002, Introduction to Computer Programming (No Prior Experience). Consequently, some videos will use a different IDE, called IDLE, instead of PyCharm.

Python programs are written in plain text files (that is, a file with content that is just text - no formatting, no binary data such as images, etc.). You may be familiar with text files that end in .txt; they are usually opened automatically in notepad on Windows or TextEdit in MacOS. Python files are text files that contain Python source code. Python files typically end with a .py extension.

PyCharm is a Python IDE ("Integrated Development Environment"). An IDE is an application that comes with several tools that help you write code. Some common features that IDEs may include are:

  • a text editor for editing Python files (usually identifiable by a .py at the end of the name) and other text files
  • syntax highlighting (color coding different parts of your program for readability)
  • code completion / hinting (suggestions on potential completions for the code that you are in the middle of typing)
  • a debugger to help run your code line-by-line while inspecting values of variables
  • an interactive shell to type continually run code as you type it

PyCharm on its own doesn't include the programming language, Python, so Python must be installed prior to using PyCharm. That means that PyCharm is not Python; they are two separate pieces of software. In fact, you can use other text editors / IDEs to work with Python, such as IDLE (an IDE bundled with Python), and Spyder (an IDE bundled with a popular distribution of Python, Anaconda). However, PyCharm has some features, like the inclusion of type warnings, that other IDEs do not have. With that said, it is a bit overwhelming due to the number of features it has, but we'll focus mainly on editing and running programs.

PyCharm can also be intimidating 😅 at first because of the small amount of setup required to simply create and edit a single file program. This is because PyCharm is project-centric; It really wants you to organize your work into a bundle of files and configurations called a project. In PyCharm, a project:

  • may contain multiple Python files (.py)
  • can have a version of Python associated with them
  • may contain libraries / modules that files in that project depend on to run

In PyCharm, in order to write code, __you should have a project created first__ (when you first start PyCharm, you'll be given the opportunity to create a new project, but you can also create projects at any time).

One way to organize your work is to create a single project for all of the work that we do in class... and then create separate individual projects per homework.

Note that a project in PyCharm is a feature specific to PyCharm:

  • this particular notion of projects is not inherently part of Python, the programming language
  • in fact, Python allows for multiple ways to create programs
    • even ways that don't involve setting up all of the supporting files and structure found in PyCharm's concept of a project
    • ...so some Python editors are just file-based rather than project-based

To test your installation of Python and PyCharm - create a new project and add a new file in the project as shown in the video. Your program should look something like this:

Sample Program: This is your first Python program! 🐍



Running this program through PyCharm should yield the same output as running the same program through the embedded Python editor in this page. Check out the video for more details on:

  • running your program
  • seeing the output of your program
  • where to find errors (and other feedback)
  • using the interactive shell

Creating and editing files will be your main method of writing programs in PyCharm. However, much like other IDEs and editors, PyCharm also offers an interactive Python console. You can use this to run lines of code as you type them, without having to save any of your code as a file. This feature is sometimes called an interactive shell or console... or sometimes a REPL (R-E-P-L): Read, Eval, Print Loop. That is, the console will read a line of code that you type in, evaluate (or run it), and print out the result of the expression you typed in, and it'll do this over and over again.

What is the Python interactive shell for?

  • The Python console is great for experimenting with Python syntax and concepts
  • ... but it’s typically not used to create reusable programs.
The videos in these modules show both PyCharm and IDLE being used as the primary text editor. However, in practice, we'll be using PyCharm throughout the course. Despite PyCharm being trickier to get started with, it does have some helpful features that IDLE does not... such as warnings for potential type errors and a more intuitive (and powerful) debugger.

File Locations

When initially installing PyCharm, the default options set the folder that your projects are saved to as $HOME/PycharmProjects... where $HOME is:

  • On Linux: /home/$USER_NAME
  • On MacOS: /Users/$USER_NAME/PycharmProjects/
  • On Windows: c:\Users\$USER_NAME\PycharmProjects/ (this may vary depending on which version of windows you're using)

$USER_NAME is your actual user name. Within this directory, your projects are folders that contain .py files, with the folder names matching your project names.


Functions & Function Calls

A "function" is a pre-written block of computer code that will perform a specific action or set of actions. Python comes with a number of built-in functions, and you can also write your own (more on that later in the semester)

Functions always begin with a keyword followed by a series of parenthesis. For example:

print ()

You can "pass" one or more "arguments" into a function by placing data inside the parenthesis. For example:

print ("Hello World!")

Different functions expect different arguments. The print function, for example, expects zero or more arguments (multiple arguments are separated by commas) that will be printed to the screen.

When you ask Python to run a function we say that you have "called" the function.

Sample Program: The following program shows how to call the print function with a single argument. Note that the default behavior of the print function is to print out the supplied argument followed by a line break. So the code below will generate two lines of output. Click the "Run" button to see the program in action or download a copy.

Sample Program: The following program shows how you can call the print function by sending it no arguments. When you do this you are asking Python to print nothing to the screen, but recall that the default behavior of the print function is to print whatever arguments are provided followed by a line break. So calling the print function without any arguments will essentially print out a single line break. Click the "Run" button to see the program in action or download a copy.

Sample Program: The following program shows how to call the print function with multiple arguments. Note how the arguments are separated by the "comma" character inside of the open and closed parenthesis characters. Also note how Python automatically adds a "space" character between each argument. We will talk about how to override this behavior later in this module. In addition, notice how Python ignores blank lines - lines 5 and 6 have nothing on them, but this doesn't impact the output of the program at all (i.e. two extra linebreaks are not generated because of these blank lines). Click the "Run" button to see the program in action or download a copy.

Programming Challenge: Using the code editor below, write a program that generates the following output. Note the line breaks on the second and fourth lines. Click the "Run" button to check your work, and click here to download the solution.
Pear

Peach Grapefruit

Orange Pineapple Grape

Programming Challenge: Using the code editor below, write a program that generates the following output. Note the line breaks on the second and fourth lines. Click the "Run" button to check your work, and click here to download the solution.
*
* *
* * *
* * * *

* * * *
* * *
* *
*


Strings & String Literals

In a programming language data that is textual in nature (i.e. the phrase "Hello, World!") is called a "string". Strings can contain 0 or more printed characters. A string with zero characters is called an "empty string".

"String Literals" are strings that you define inside your program. They are "hard coded" values and must be "delimited" using a special character so that Python knows that the text you’ve typed in should be treated as printed text (and not a function call). For Example:

print ('hello, world!')

Python supports four different delimiters:

  • The single apostrophe ( ' )
  • The quotation mark ( " )
  • The triple quote ( """ )
  • The triple apostrophe ( ''' )

String literals must use the same delimiter at the beginning of the string as well as at the end of the string

Sample Program: The following program demonstrates how the three different string delimiters can be used in Python. Note how each string uses the same delimiter at the beginning and end of the string. Click the "Run" button to see the program in action or download a copy.

Sample Program: This program shows how you can use the delimiter characters within a string. In the first call to the print function we are passing it an argument that is delimited by the double quote character, which means we can use the single quote character inside of the string since that character does not mean that the we have reached the end of the string. In the second call to the print function we are using the double quote delmiter - this lets us use both the single and double quote characters inside of the string as needed. Click the "Run" button to see the program in action or download a copy.

Programming Challenge: Using the code editor below, write a program that generates the following output.

Welcome to "Introduction to Computer Programming"
I'm looking forward to working with you this semester!
Click the "Run" button to see the program in action. Download a copy of the solution to this programming challenge.

Programming Challenge: Using the code editor below, write a program that generates the following output.

Hello, I'm happy you decided to run this "Python" program!
Click the "Run" button to see the program in action. Download a copy of the solution to this programming challenge.


Basic Formatting using the print() Function

Note: the techniques discussed in this section will not run using the web-based Python code editor. Please use IDLE to run the code samples discussed in this section.

The print() function has two default behaviors:

  • It will always print a "line break" character at the end of a line
  • It will always print a "space" character between multiple arguments

For example, given this program:

print ("Hello", "there")
print ("everybody!")

We would expect to see the output:

Hello there
everybody!

However, we can override this default behavior using a special set of "keyword" arguments. These arguments are called "sep" for "separator" and "end" for "line ending". Each of these arguments expects a String. For example, let's say you had a program where you wanted to print "*" characters instead of spaces between each item. You could do the following to make this happen:

print ("a", "b", "c", sep="*")

Note how the "sep" keyword is used here in conjunction with the equal sign - this is essentially telling Python to use the "*" character as the separator between each item.

Likewise, you can override the default behavior of the print() function to print a linebreak at the end of a line by using the "end" keyword argument, like this:

print ("a", "b", "c", end="#")
print ("d", "e", "f")

This will generate the following output:

a b c#d e f

... and if you don't want to print ANYTHING at the end of a line or between a character you can use an "empty string", like this:

print ("a", "b", "c", sep="")

Which will generate:

abc

You can combine these two techniques as well!

print ("a", "b", "c", sep="*", end="#")

Variables

A variable is a storage location and an associated symbolic name (an identifier) which contains some known or unknown quantity or information. Variables are one of the most fundamental aspects of computer programming. You can think of a variable as a "container" that temporarily stores information in your computer's memory.

You can create a variable by using the following syntax (similar to punctuation in a natural language):

variablename = somedata

The = symbol is called the 'assignment operator' and will cause Python to store the data on the right side of the statement into the variable name printed on the left side

When creating a variable you need to follow these naming rules:

  • Variables can’t contain spaces (though you can use the underscore character ("_") in place of a space)
  • The first character of a variable name must be a letter or the underscore character.
  • No characters are allowed in a variable name besides alphanumeric (alphabet or numeric) characters and the underscore ("_") character (no special characters like &, !, +, $, etc.)
  • Python is case sensitive, so two variables with the same name but different case (i.e. Craig vs craig) are two different variables
  • You can't use any of Python's built in "reserved words" (i.e. you can't create a variable called "print" because that would conflict with the print function)

You can print the contents of a variable by simply printing the variable name, like this:

name = "John Smith"
print (name)
Output:
John Smith

Variables can "vary" over time, meaning that you can re-assign the value of a variable in your program and change the data that is being stored in that variable

You also need to make sure that your variables have been created before you use them. The following program will not run because the variable "foo" is not available when we attempt to access it in our program (it is declared AFTER we attempt to use it)

print (foo)
foo = "Hello, world!"
Output:
NameError: name 'foo' is not defined

Sample Program: The following program defines three variables. It then prints out the contents of those variables along with a string literal. Click the "Run" button to see the program in action or download a copy.

Sample Program: This program defines three variables, but only two get printed. Variables don't always need to be printed to the user. In this program it really doesn't make sense for us to define the third variable since it isn't used, but it's not an error and Python will have no problem running this code. Click the "Run" button to see the program in action or download a copy.

Programming Challenge: Using the code editor below, write a program that creates three variables. These variables should store the names of three US Cities. Name your variables appropriately (i.e. don't call your variables x, y and z - use more descriptive names). Next, print out your cities so that they display as follows.

City #1: NYC
City #2: Chicago
City #3: San Francisco
Click the "Run" button to see the program in action. Download a copy of the solution to this programming challenge.


The "input" function

Sometimes you want to ask a user a question while your program is running. One of the simplest ways to do this is to request information from the keyboard using the input function.

input is a built-in function in Python. It accepts a single string as an argument. It then prompts the user with that string and waits for them to type in a series of characters. Your program will resume when the user hits the ENTER key. Whatever the user typed in during that time is sent back to your program as a string which can be stored in a variable. For example:

user_age = input("How old are you?")

The input function always "returns" a string. This means that when the function finishes running it will produce a string which can be assigned to a variable (using the assignment operator =)and used in your program.

Sample Program: The following program asks the user for their name via the input function. The input function takes one argument - a string - which is a question that you want to ask the user. The function then waits for the user to respond and hit the ENTER key. When the user does respond the function "returns" a string which is captured using the assignment statement and stored in a variable. Click the "Run" button to see the program in action or download a copy.

Sample Program: The following program asks the user for two animal names using two calls to the input function. Those two variables are then used later in the program to produce some output for the user. Click the "Run" button to see the program in action or download a copy.

Programming Challenge: Using the code editor below, write a program that asks the user for three super heroes. Then generate the following output using the supplied values:

Superhero #1: Wonder Woman
Superhero #2: Aquaman
Superhero #3: Nightcrawler
Click the "Run" button to see the program in action. Download a copy of the solution to this programming challenge.

Programming Challenge: Using the code editor below, write a program that asks the user for three colors. Then print out the colors in all possible combintaions. Here's a sample running of your program:

Green Blue Pink
Green Pink Blue
Blue Green Pink
Blue Pink Green
Pink Green Blue
Pink Blue Green
Click the "Run" button to see the program in action. Download a copy of the solution to this programming challenge.


Numeric Literals

When you want to store a number in a variable you can do so by placing the number on the right side of the assignment operator in the same way you would if you were storing a String.

number_of_items = 10

Note that you do not delimit numeric literals with quotation marks as you would with a string - simply type the number "as-is" and Python will interpret it as a numeric value as opposed to a sequence of characters.

We call numbers that are explicitly stated in your program a "numeric literal" - you literally are storing the numeric value specified.

Python supports two numeric data types - integers and floating point numbers. To create an integer literal simply type the integer, like so:

speed_of_light = 300000

To create a floating point literal you can type the number with its decimal point, like this:

cost_per_carrot = 1.99

Note that you cannot place formatting characters into a numeric literal (no $ or , characters should be used when defining a numeric literal)


Math Operators

All programming languages have tools for manipulating numeric data which we call "math operators". Here is a list of some of the basic math operators that exist in Python:

+  Addition
-  Subtraction
*  Multiplication
/  Division (floating point division - fractional results included)
// Division (integer division - fractional results truncated)

We use operators along with numeric data to create "math expressions" that Python can evaluate on our behalf. Python can output the result of a math expression using the print function, like this:

print (5+2)
print (100 * 5 – 12)

We can also store the result of a math expression in a variable, like this:

answer = 5 + 2
print (‘the answer to 5 + 2 is’, answer)

Variables can also be used in a math expression in place of a numeric literal, like this:

price = 100.00
sales_tax = 0.07
total = price + sales_tax*price 
Sample Program: The following program stores three test scores in three different variables. The program then computes the total of all three tests as well as the average score and displays this information to the user. Click the "Run" button to see the program in action or download a copy.

Sample Program: The following program computes a series of discounts on an item. The program begins by asking the user for their name using the input function. It then uses a series of math expressions to compute some discounted price values which are outputted to the user. Click the "Run" button to see the program in action or download a copy.

Programming Challenge: Using the code editor below, write a program that asks the user for their first name and their last name. Next, compute how much the user should leave as a tip at a restaurant for a $150.00 bill. Assume a tip rate of 15%. Then have your program produce the following output (assume the user entered "John Smith" as their full name):

Welcome to the restaurant John Smith !
For a bill of $150.00 you should leave 22.5 for your server
With this tip your total bill will be 172.5
Click the "Run" button to see the program in action. Download a copy of the solution to this programming challenge.


Commenting Your Code

Your programs will eventually get to be very, very long. Commenting is a way for you to leave "notes" for yourself or other programmers so that you (and/or others) understand what your thinking process was when you originally wrote your program

Python supports comments via the # symbol. You can use the # symbol to tell Python to essentially ignore anything else on that line which comes after the symbol. Here are some examples:

print ('Hello, world!')  # this will print the string Hello World

# the following line will print my name
print ('Craig')

It's important to get into the practice of commenting early and to be consistent about leaving comments throughout your program.

Python also supports multi line comments through the use of the triple quote delimiter. For example:

"""
This line will be ignored
So will this one
And this one
"""

# the following line will NOT be ignored
print ('hi there')
	  

We sometimes use comments as a way to pseudocode a programming project before we launch into writing it using real code. Think of this as writing a "rough draft" or "outline" of what you want your program to do before you actually write any real Python code. Pseudocoding allows us to outline the necessary tasks without having to be burdened with writing the actual code to accomplish the desired tasks. For example:

# get two test scores from the user
# add them together and divide by 200
	  
# print out the result and report the average 
# score to the student
	  
Sample Program: This program is well-documented through the use of comments. Commenting makes it easier for someone to quickly understand how a program is designed to operate. Click the "Run" button to see the program in action or download a copy.

Programming Challenge: Comment the code below to help document what is happening in this program. Click the "Run" button to check your work, and click here to download the solution.

Programming Challenge: Write a program to go along with the comments displayed in the program below. Click the "Run" button to check your work, and click here to download the solution.


Data Types

A value is a fundamental unit of data that a program works with. The values we have seen so far have been numeric (i.e. 7, 5.5, etc.) or strings (i.e. "Hello!")

When storing data in memory, Python needs to keep track of the value (i.e. the number 5) as well as the "data type" of the value (in this case, an Integer). The "data type" describes the kind of data being stored, and allows you to perform certain actions on the value (i.e. you can add or subtract two Integer values)

There are three basic types of data that we will be working with during the first half of the term:

  • Strings (character-based data)
  • Numbers
  • Logical Values (True / False)

Python has two different data types for numeric values:

  • Integers
    • Whole numbers that do not contain a decimal point
    • Abbreviated as "int" in Python
    • Examples: 5, -5, 100, 10032
  • Floating Point Numbers
    • Numbers that contain a decimal point
    • Abbreviated as "float" in Python
    • Examples: 5.0, -5.0, 100.99, 0.232132234

You can store numeric data inside variables and Python will automatically select the correct data type for you. For example:

num_1 = 5		# this is an int
num_2 = 4.99		# this is a float

Keep in mind that you do not use separators (e.g. commas) or symbols (e.g. $, %, etc.) when storing numeric data. Example:

num_3 = $5,123.99	# error!

You can check the data type being stored by a variable by using the "type" function. The "type" function takes one argument (the value to be analyzed) and returns the data type as a string. Here's an example:

var1 = "Hello"
var2 = 5
var3 = 10.532

print (type(var1))
print (type(var2))
print (type(var3))
		

The result of the program above would be to display that var1 is a string, var2 is an Integer and var3 is a floating point number.


Data Type Conversion

Sometimes we need to convert values from one data type to another. For example, say you had the following variable in your program:

price = "1.99"

The data type of the variable "price" is a string (because it is initialized using quotes). However, let's say you want to perform a math operation using this variable. In this program you couldn't do that because strings are not numbers - they are only sequences of characters.

We can convert the value stored in the variable "price" to a floating point number using a data type conversion function:

price = "1.99"

# convert price to a floating point number
real_price = float(price)
		  

Python has a number of data type conversion functions built in. All of these functions accept a value and attempt to convert that value into the data type that corresponds with the name of the function. The result is returned out of the function. For example:

# define our variables
a = "1"		# a is a string
b = 5.75	# b is a floating point number
c = 3		# c is an integer

# convert data types
d = int(a)		# d is now the integer value 1
e = str(b)		# e is now the string "5.75"
f = float(c)		# f is now the floating point value 3.0
		  

str, float and int are data type conversation functions. They each take one argument and convert that argument into the desired data type.

Note that sometimes you can't convert from one data type to another. For example, what do you think would happen if you tried to run the following code? (Hint: Python won't be very happy with this!)

a = "hello world!"
b = float(a)
		  

Remember that we can use the input function to ask the user a question from within our programs. However, the input function returns a string – this means that the data type that comes out of the input function is a series of printed characters. If we want to use the value supplied by the user in a calculation we need to convert the string into one of the two numeric data types that Python supports (float and int). Here's an example:

# ask the user for their monthly salary
monthly_salary = input('how much do you make in a month?')

# convert the salary into a float
monthly_salary_float = float(monthly_salary)

# calculate the yearly salary
yearly_salary = monthly_salary_float * 12

# print the result
print ('that means you make', yearly_salary, 'in a year')
		  

In the previous example we performed our data type conversion in two lines. We could have done that in a single line using a technique called "nesting". Here's an example:

mynum = float( input("give me a number!") )

In this example we execute the innermost function first (the input function) - this returns a string, which is then immediately passed as an argument to the float function, which converts the string to a floating point number. The result is stored in the variable "mynum"

Sample Program: In this program we have a number of Strings that are holding numbers that we want to add together. However, we can't do this directly since you can't perform math operations on the String data type. This proram first converts the strings into numeric data types and then computes the sum. Click the "Run" button to see the program in action or download a copy.

Sample Program: TThis program asks the user to enter in the name of an item, how many of those items they wish to purchase and the cost per item. It then computes the total amount of their purchase and prints this out. To do this the program converts the inputted strings into numeric data types using the int and float functions. Click the "Run" button to see the program in action or download a copy.

Programming Challenge: Write a program that asks the user to enter in their name and five test scores. You can assume the test scores will be valid floating point numbers. Next, compute the average test score for this user and print it to the screen along with their name. Example input/output:
Enter student: Craig
Enter 5 scores (one per line): 90
85
92
87
94.5
Average test score for Craig: 89.7
Click the "Run" button to check your work, and click here to download the solution.


More Math Operations & Mixed Type Expressions

Python contains two different division operators.

  • The / operator is used to calculate the floating-point result of a division operation. The result is always a floating point value.
  • The // operator is used to calculate the integer result of a division operation (essentially throwing away the remainder). This operation will always round down. The result is always an integer.

Most times you will use the floating point division operator (/). Here are a few examples of these operators in action:

print (5/2)		# output:  2.5
print (5//2)		# output: 2
print (-5/2)		# output: -2.5
print (-5//2)		# output: -3

Python supports the standard order of mathematical operations (PEMDAS). You can use parenthetical notation inside your math expressions to group operations For example:

((5+10+20)/60) * 100

You can raise any number to a power by using the "**" operator. For example:

answer = 3 ** 2
print (answer)		# output: 9
		

The modulo operator (%) returns the whole number remainder portion of a division operation. For example:

print (5/2)		# output: 2.5
print (5%2)		# output: 1
		

Python allows you to mix integers and floating point numbers when performing calculations. The result of a mixed-type expression will evaluate based on the operands used in the expression. Python will automatically "widen" the data type of your result based on the values in your expression (i.e. if you add together an integer and a float the result will be a float since Python will need to preserve the decimal values from the floating point operand).

Operand #1		Operand #2		Result
int			int			int
float			float			float
int			float			float
float			int			float
Sample Program: This program demonstrates the basic math operators we have covered so far. In addition, the program also showcases how Python evaluates mixed type expressions. Click the "Run" button to see the program in action or download a copy.

Programming Challenge: A customer in a store is purchasing 5 items. Write a program that asks for the price of each item, and then displays the subtotal of the sale, the amount of sales tax, and the total. Assume the sales tax is 6 percent. Click the "Run" button to check your work, and click here to download the solution.


Basic String Operations

You can't "add" two strings together, but you can "concatenate" them into a single compound string using the same symbol that is used for numeric addition. For example:

a = input("first name: ")
b = input("last name: ")
fullname = b + ',' + a
print (fullname)

You can also "multiply" a string by an integer value to produce a larger string. The resulting string concatenates the original string 'n' times, where n is the integer you use in your expression. For example:

lyrics = 'Fa ' + 'La ' * 8
print (lyrics)		# Fa La La La La La La La La 
		
Sample Program: This program asks the user to enter in two words. It then concatenates and repeats the words using the + and * string operators. Click the "Run" button to see the program in action or download a copy.

Programming Challenge: Write a program that generates the "Pig Latin" version of a word. Pig Latin can be computed by taking the first letter of the word and putting it at the end of the word plus the suffix "ay". Here's an example:
Word      Pig Latin
python    "ython" + "p" + "ay"
Here's a sample running of your program:
Enter the first letter of a word:  p
Enter the rest of your word: ython

The Pig Latin version of python is ythonpay
Click the "Run" button to check your work, and click here to download the solution.


Formatting strings and numbers

The format function can be used to format a string before you decide to print it out to the user.

format takes two arguments – a number and a formatting pattern (expressed as a string). format() returns a string which can be treated like any other string (i.e. you can print it out immediately, store its value in a variable, etc.)

The first argument passed to the format function is the item that you wish to format. The second argument passed to the function is the formatting "pattern" you wish to apply to this item. This pattern varies based on what you would like to do to the item in question. Once the pattern is applied to the item the format function will return a string version of your item with the formatting pattern applied.

The format function can be used to generate a customized string version of a float or integer number. For example, here's a program that truncates a floating point number to two decimal places:

a = 1/6
print (a)	# 0.16666666667, float

b = format (a, '.2f')
print (b)	# 0.17, string

In the example above we called the format function with two arguments - a variable of type float and a formatting pattern of type string. The formatting pattern ('.2f') means "we are formatting a floating point value (as indicated by the 'f' character). We want to limit the number of decimal places to 2 (as indicated by the '.2' before the 'f' character)"

Here are some additional examples of formatting numbers using the format() function:

a = 10000/6			# float
b = format (a, '.2f')		# format a as a 2 digit number - b is a string
c = format (a, '.5f')		# format a as a 5 digit number - c is a string
d = format (a, ',.5f')		# format a as a 5 digit number with the "," separator between placed into the resulting string - b is a string

Another common use of the format function is to generate a string that contains a known # of characters. For example, say you have the strings "Craig" and "Computer Science". You might want to generate output that looks like the following given these items:

Name		Department
Craig		Computer Science

In this case we need to ensure that the strings "Name" and "Craig" are the same width so that the strings that come after them ("Department" and "Computer Science") line up correctly. You can use the format function to "pad" a string with extra spaces at the beginning or the end of the string. For example:

x = format('Craig', '<20s')

This will generate a new string (x) that contains the string 'Craig' plus 15 spaces at the end of the string (because "Craig" is 5 spaces the resulting string will have 15 additional spaces added to yield a string that contains 20 total characters). The total length of the string in this case will be 20 characters. The '<' character in the formatting pattern tells Python to left justify the string and place the extra spaces at the end of the new string. You can also have Python right justify the string and place the spaces at the beginning of the new string by doing the following:

b = format('Craig', '>20s')

Note that the format function always returns a string. This means that the result of the format function is unable to be used in a math expression. However, you could use a data type conversion function ( int() or float() ) to turn the string generated by the format() function back into a numeric data type if you wanted to.

Special Note: The format() function DOES NOT work in the web-based code editor that is included in these online modules. To work with the format() function you should launch IDLE and run your source code from within that IDE.

Errors, Error Types and Debugging

In general, there are three different kinds of errors that can occur to you while writing a program:

  • Syntax errors: The code that you wrote does not follow the rules of the language. For example, a single quote is used where a double quote is needed; a colon is missing; a keyword is used as a variable name. With a Syntax error your program will not run at all (IDLE will yell at you before it even attempts to run your program)
  • Runtime errors: In this case, your code is fine but the program does not run as expected (it "crashes" at some point as it is running). For example, if your program is meant to divide two numbers, but does not test for a zero divisor, a run-time error would occur when the program attempts to divide by zero.
  • Logic errors: These can be the hardest to find. In this case, the program is correct from a syntax perspective; and it runs; but the result is unanticipated or outright wrong. For example, if your program prints "2 + 2 = 5" the answer is clearly wrong and your algorithm for computing the sum of two numbers is incorrect.

Here are some suggestions for isolating errors and correcting them:

  • Set small, incremental goals for your program. Don’t try and write large programs all at once.
  • Stop and test your work often as you go. Celebrate small successes!
  • Use comments to have Python ignore certain lines that are giving you trouble
  • Use the print function to print out information so that you can inspect what is happening at key points in your program

Errors and how they're reported varies depending on the editor you're using and how you're running your program. For example, in PyCharm, syntax errors, are automatically detected and marked (relative to their position in the file), whereas in IDLE - a more basic Python editor - syntax errors are only displayed when the file is attempted to be run. Syntax and runtime errors typically result in the display of the description of the error that occurred. This description contains valuable information on the cause of the error.


Type Hinting / Annotations

This portion of the module covers "type annotations" syntax that was first introduced in Python 3.6. Our online editor does not yet support Python 3 fully, so type annotations will not work online, but they will work in your IDE!

A type can be defined as a set or category of values along with the functions and operations that you can use with those values. Consequently, a value's type dictates the valid operators and functions that can be used with it. For example, a Python program will crash during runtime if an operation or function is used with incompatible types:

Sample Program: The input function always returns a string, so adding a string to an int results in a TypeError.



We're not informed that there's a type error until the program is run. We can agree, that, at this point it's already too late.... if we have to wait until the program is run to uncover the error, there is a chance that our program will crash in the hands of the program's user! Hope is lost. Everyone is sad 😭! Wouldn't it be better to check for type errors before the program runs?

We can do this manually, of course, but that's a bit cumbersome. Let's get our computer to perform the tedious task of checking our code for type errors before we run it! We can run a piece of software, a type checker, to automatically detect our mistakes. Win 👍! Wait! ...Unfortunately, our type checker's aren't actually that smart 😕 - we have to tell them what type/types we're intending to use before they can check for type errors in our program.

So… it's important for you, the programmer, to be able to specify intended types in a form that can be understood by a type checker - a program that can check your code for type errors. Python has syntax (called type annotations or type hinting) for systematically defining types for variables and functions. From the Python docs:

"These annotations can be used to avoid many kind of bugs, for documentation purposes, or maybe even to increase speed of program execution."

Python is a dynamically typed language (like JavaScript, Ruby, Scheme or PHP) - it's not necessary to declare a type for variables, function, parameters and function return values. Types are only checked when the code runs. So, you can just declare variables, and they can contain any type of value that you want! This also allows variables to change type over time, because variables don't have stick to declared type!

val = 1 # hey, notice that I don't have to specify type; I just assign a value
val = 'hello' # ok, fine, my type can change over time!

This is different from statically typed languages, like C, C++, Rust, and Java: the programmer has to declare types beforehand because types are checked before the program runs. Here's an example of specifying types in Java:

int count = 5;
String defaultAnswer = "Yes";

In Java, you won't be able to assign a value of a different type to a variable declared as another type:

// count was declared as an int
count = "won't work!";  // but now I'm setting count to a string... 

// this will result in a compilation error, so the program can't be run

In Java, the compiler serves as a static type checker. That is, it's a tool/program that looks for type errors in your code without running your code. Now we have two strategies for detecting type issues: static type checking and run-time type checking. With static type checking, the program doesn't have to be run to catch some type errors. In fact, in Java, a program can't run if the compiler finds any type errors. In Python, however, you can have a type error, but the program will still run (it'll just crash when it encounters the type error).

Python code will run, even if a type error eventually occurs:

# in Python, program will run (but crash)
n = 100
print(n) # 100 will be printed out
n += " one" # OH NOOOO... I'VE CRAAAAAAASHED!

In Java, a program cannot be run if there's a type error detected:

// in java, this program will not compile, and consequently cannot be run!
int i = 100;
System.out.println(i);
i += "one";

Note that there could still be run-time type errors in statically typed languages (for example, in Java, there are some cases where converting from one type to another can only be checked during run time).

Python, again, is a dynamically typed language. However, we can use tools that will check our program for type errors before running it. For example, you can use a program called mypy as a static type checker. You can use it on your code before you try running your code. We'll use the static type checker built into our IDE, PyCharm. It'll continually check the program that you're writing for any type issues.

So, how do we tell our static type checker what types we want? Well, Python supports gradual typing through optional type hinting / type annotations. This feature allows parts of a program to be statically typed and other parts to be dynamically typed. That means that -- in Python -- you can declare types if you want to. To declare types for variables, function parameters and function return values, you'll need Python 3.6 or greater (technically, you can do this with a lesser version of Python, but the syntax is a little bit different).

Type annotations can be optionally added to variables by adding colon and the appropriate type after the variable name:

count: int = 100

For now, the types that we can use as annotations are: int, str and float:

chance_of_eating_pizza_tonight: float = 0.99
description: str = "I am now invincible! (from most type errors, that is)"

We'll cover further usage of type annotations as we go through the semester (for example, dealing with composite types, function parameters, etc.).

As mentioned earlier, PyCharm includes a static type checker. It looks at your code as you type. It can actually catch some type errors without using type annotations. By default, PyCharm (Community Edition 2019.1), only counts these as warnings, rather than errors (why tho??? - these should totally be errors), so they'll appear as yellow markers in the editor's right-hand gutter:

type error found; pycharm shows a warning!

However, there are some cases where PyCharm can only catch type errors with type annotations. In the picture below, a function is declared (this is not something we have covered yet, but it does show the importance of adding type annotations), and the function's return value is used in such a way that results in a type error. However, PyCharm does not give any warning or error regarding this issue because there are no type annotations (notice the green check mark 👀✅!).

type error not found; pycharm shows no warnings or errors!

When we give PyCharm some help by adding type annotations, we get the warnings (see the video for a fully annotated example).

Let's get back to the static typing versus dynamic typing. Why is static typing soooo good 😎?

  • it catches bugs earlier in development life cycle - no need to waste time running your program
  • program may run faster as types (mostly) do not need to be checked while program is running
  • type annotation syntax provides inline documentation of code - particularly useful when working on large codebases or large teams
  • provides type information to tools / programs that you use to code...allowing features such as more intelligent auto completion

Hm. With all of those advantages, it sounds like dynamic typing, as a language feature, is bad 🙅‍♀️. Did Python's creators mess up? Why allow dynamic typing at all? What does dynamic typing offer?

  • you can write programs faster
  • there are situations where runtime type checking is required anyway

Dynamic type checking is not a bad idea, and it does make a language easier to learn and less tedious to write in. Python is dynamically typed, so it's easy and fun to work with... but it also has gradual typing with optional tools if you want the advantages of static type checking for your project.

With that said, for our class, add type annotations to your code! It'll cut down on bugs, it'll force you to think about types when you declare variables and functions, and you'll be just a little more prepared for learning a statically typed language, like Java.


Drawing Graphics in Python (Turtle)

Note that the graphics techniques presented in this section will not run correctly using our web-based coding environment. To try any of the code samples included below simply launch IDLE on your own computer and run the code locally.

So far we have explored how to use Python to produce text-based output using the print function. However, computer programs can produce much more than just text! For example, a program can be written to produce graphics, audio, video and even schematics for a physical object that can be rendered on a 3D printer. The purpose of this sub-module is to introduce you to the basics of creating simple graphical patterns using Python.

"Turtle Graphics" is a method of producing pictures by instructing a cursor (called a 'turtle') to move around on a Cartesian coordinate plane. The turtle can move left, right and forward and carries a pen around with it which can be used to draw lines to the canvas. By calling a series of functions we can cause the "turtle" to trace out shapes and figures on the screen.

In order to start working with turtle graphics we need to gain access to some graphics-specific functions that are not part of the standard Python language. We can do this by asking Python to "import" these functions into a program from a function library, which we refer to as a "module" in Python. A "module" is nothing more than a file that a programmer has written that contains specialized functions that go above and beyond the basic capabilities of a programming language. We can do this by using the "import" statement, like this:

import turtle

This tells Python to make available all of the functions stored in the "turtle" library. We can now call functions inside of this module by using the module name as a prefix - for example, there is a function in the "turtle" library called "setup" - to call it you can do the following:

# import the functions from the "turtle" library
import turtle

# call the "setup" function that exists in the "turtle" library
turtle.setup(500, 500)

Note that we could not just call "setup" all by itself because that function doesn't exist in the standard set of Python functions. By adding the prefix turtle. we tell Python to call a function called "setup" that exists within the "turtle" module. We will discuss modules and how they work in greater detail in future lessons.

The "setup" function in the turtle module takes two arguments - the width and height of the graphical canvas you wish to create. Graphical canvases can be thought of as a standard Cartesian coordinate plane with 0,0 being at the center of the canvas (see image below):

2D coordinate plane, with the origin being in the center

Turtle Graphics canvas - width = 10, height = 10

Here's a basic program that shows this in action. Simply copy and paste this code into a new program in IDLE.

Important note: Don't save your graphics programs using the filename "turtle.py" - this will cause Python to get confused between your program and the "turtle" module.
# make the turtle module available
import turtle

# set up the screen size (width=500, height=500) - measured in pixels
# the starting point of the turtle to the center of the screen(0, 0)
turtle.setup(500, 500)

When you run this program you will notice that IDLE will pop up a new window for you of the desired height. The window will appear blank (all white) because we haven't directed our program to draw anything to it just yet.

To draw basic shapes we need to instruct our "turtle cursor" to move around the screen. The turtle can be instructed to move using some basic functions, including:

# forward: tells the turtle to move forward by 
# a desired number of units (pixels)
turtle.forward(100)

# right: tells the turtle to adjust its heading 
# to the right by a desired number of degrees
turtle.right(90)

# left: tells the turtle to adjust its heading
# to the left by a desired number of degrees
turtle.left(45)

Here's a sample program that shows how to draw a square to the screen. Note that the turtle initially faces to the right when your program starts.

# make the turtle graphics module available
import turtle

# set up our graphical canvas
# width = 500, height = 500
# starting point = 0, 0
turtle.setup(500,500,0,0)

# move the turtle forward by 100 pixels
# note that the turtle initially faces to the right
turtle.forward(100)

# now turn to the right by 90 degrees
turtle.right(90)

# now the turtle is facing down.  move another 100 pixels
turtle.forward(100)

# turn to the right by 90 more degrees
# this will point the turtle to the left
turtle.right(90)

# and move forward by another 100 pixels
turtle.forward(100)

# repeat the process one more time!
turtle.right(90)
turtle.forward(100)

... and here's what should be generated when you run the program above:

An image of a square being drawn by the turtle graphics module

A simple square drawn in Turtle Graphics

Here are a few challenges

Programming Challenge: Write a series of Python programs that draw the following shapes to the screen:

  • A triangle (3 sided figure)
  • A pentagon (5 sided figure)
  • An octogon (8 sided figure)

If you'd like to view the solutions download a copy.

The turtle cursor can be controlled using some additional functions, including:

# goto: instructs the turtle cursor to move to a specific position on the canvas
# note that the turtle's heading is unaffected by this function (i.e. if the turtle 
# is facing right and then is told to move to a particular coordinate it will still 
# be facing to the right when it gets to that location)
turtle.goto(100, 50) 

# setheading: tells the turtle to turn and face a specific direction (expressed as
# an angle).  0=right, 90=up, 180=left, 270=down
turtle.setheading(90)

# penup: tells the turtle to pick up its pen - no "ink" will be drawn to the canvas
# if the turtle is asked to move from this point forward (this function takes no arguments)
turtle.penup()

# pendown: tells the turtle to put down its pen - resumes drawing "ink" to the screen
turtle.pendown()

Here's a sample program that draws two squares at opposite sides of the canvas:

# make the turtle graphics module available
import turtle

# set up our graphical canvas
# width = 500, height = 500
# starting point will be the center of the screen
turtle.setup(500,500)

# pick up the pen so we can move to a new position
turtle.penup()

# now move to the top left side of the screen
turtle.goto(-200, 200)

# put the pen down
turtle.pendown()

# draw a square here
turtle.forward(100)
turtle.right(90)
turtle.forward(100)
turtle.right(90)
turtle.forward(100)
turtle.right(90)
turtle.forward(100)
turtle.right(90)

# pick up the pen and move to the bottom right side
# of the screen
turtle.penup()
turtle.goto(100, -100)

# put the pen down when we get here
turtle.pendown()

# make sure we are facing to the right
turtle.setheading(0)

# now draw another square
turtle.forward(100)
turtle.right(90)
turtle.forward(100)
turtle.right(90)
turtle.forward(100)
turtle.right(90)
turtle.forward(100)
turtle.right(90)

... and here's what the program above should look like when run:

Two squares that have been drawn by the turtle graphics module

Two squares drawn on opposite sides of the canvas

Programming Challenge: Write a Python program that draws a triangle, a square, a pentagon and an octogon at different positions on the screen. Make sure that each figure is drawn so that it appears fully on the screen. Here's a sample image of what your program should look like when run:

Four shapes drawn by turtle graphics: Square at the top left, Pentagon at the top right, Octagon at the bottom left and Triangle at the bottom right

If you'd like to view the solutions download a copy.

In summary, here are the turtle functions that were covered in this section. In future modules we will explore turtle graphics in greater detail, including how to control color, speed and add interativity to our drawings. If you're curious to learn more feel free to check out the official Turtle Graphics Documentation Site.

# setting up a turtle canvas
turtle.setup(width, height)

# orientation functions
turtle.right(degrees)
turtle.left(degrees)
turtle.setheading(degrees)

# movement functions
turtle.forward(pixels)
turtle.goto(x_position, y_position)

# drawing control
turtle.penup()
turtle.pendown()

Quiz

Now that you've completed this module, please visit our NYU Classes site and take the corresponding quiz for this module. These quizzes are worth 5% of your total grade and are a great way to test your Python skills! You may also use the following scratch space to test out any code you want.

Feedback

Tell us what you thought about this module (it's anonymous).
How helpful did you find this module on a scale of 1-5:
Very unhappy face
Unhappy face
Neutral face
Happy face
Very happy face
Which resource(s) in this module did you find the most helpful (check all that apply):

Copyright 2014-2018