Module #1 (Variables, Statements, etc.)

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

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.

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.
  11. You will be able to access Python by clicking on the Start button and then on All Programs->Python 3.x->IDLE (Python GUI)

Directions for Macintosh

  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.
  9. You will be able to access Python by navigating to your Applications folder and finding the "Python 3.x folder" - inside of this folder you will find a file labeled "IDLE.app" - double click on this file to launch the program

Using IDLE & Writing your first program

IDLE stands for "Integrated DeveLopment Environment" - it's designed to make it easy for you to both write and run Python programs.

IDLE has two modes – interactive mode and script mode. Interactive mode functions a lot like a calculator – you issue a command to the program, the command is executed and the result is immediately displayed. Script mode allows you to compose your code in a separate window and save it as a new text document on your computer. This document can then be read by IDLE at a later time and executed. You can run code written in Script mode by clicking on Run->Run Module

It’s important to note that code is executed in sequential order – statements that appear at the top of your documents will run before statements that appear later.


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.


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