Module #2

This module is designed to expose you to a variety of elementary programming techniques such as data types, formatting strings and debugging strategies. When you're finished with the module please visit our NYU Classes site and take the Module 02 Quiz.

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
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: TThis 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

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 "" - 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)

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

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

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

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

# now turn to the right by 90 degrees

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

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

# and move forward by another 100 pixels

# repeat the process one more time!

... 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

# 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)

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

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

# pick up the pen so we can move to a new position

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

# put the pen down

# draw a square here

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

# put the pen down when we get here

# make sure we are facing to the right

# now draw another square

... 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

# movement functions
turtle.goto(x_position, y_position)

# drawing control


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.


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