Introduction to Python
We’ll run through mostly programming examples that can be executed on your online interpreter. After you get a feel for basic examples, you will start writing your own code.
1. Print Statements and Debugging and Loops
The print statement is an essential part of most modern programming languages. It allows for the user to display feedback on the screen of a device. I will use the syntax and variables of the version 3 statement, though much of it will work with python version 2.
You’ll notice if you open the online interpreter it begins with a simple “Hello World” program written in python 2. If you run the program, it prints “Hello World” to the screen. This lowly and humble print statement with no adornments whatsoever will be among your greatest allies in debugging. Simple print statements have the following syntax:
print(“Your Statement Goes Here“)
A bug in a program occurs due to some sort of programming error. Usually, we say bugs allow programs to run, but cause them to produce unexpected or undesirable results. We will investigate a piece of code that is supposed to do a simple task below and debug it. In this process we will learn some of the basic syntax and statements of python that we will frequently use as well as the idea of how to debug code.
The purpose of our first program will be to add up the numbers from 1 to 5 (This should sum to 15, btw!). We will then extend this to a program that will add up the numbers 1 + n where we specify n through input commands.
Here’s our first attempt and the output:
n = 1
a = 0
while n < 5:
n = n + 1
a = a + n
print(a)
Something’s wrong! But first, let’s dissect the code and see what each line means. Line 1 reads “n = 1”. This declares a variable and sets it value to 1. It is good programming practices to declare your variables early and to initialize them to sensible starting values at the same time. Can you determine what line 2 does?
The while statement contains a condition and the format
while Your Condition Goes Here:
The colon is necessary and the subsequent indents are necessary. They tell us what statements are in the looping structure. While statements are a form of looping structure. They repeat instructions over and over. Here, the loop runs until n is 5 and in the loop, we add 1 to n and then add the value contained in n to a. Once, we complete the while loop, we print the value in the variable a. Notice, to access variables, we use their names from within the program with no quotes.
This program runs, but it doesn’t produce the desired output. Let’s use print statements to figure out why.
n = 1
a = 0
print(“Before the loop a = “,a, “and n = “,n )
while n < 5:
print(“During the loop, but before statement the first statement a = “,a, “and n = “,n )
n = n + 1
print(“During the loop, but before statement the second statement a = “,a, “and n = “,n )
a = a + n
print(“At the end of the loop a = “,a, “and n = “,n, “\n” )
print(a)
Now, we can notice certain particular things. The first thing is the more general structure of a print statement in python. We see that we can write
print(“TEXT“, var, …, “\n“)
The \n character is common across many programming languages and means print a newline or carriage return at the end of the line. Python does this automatically, but this gives me an additional newline which skips a line. Variables are reference without quotations and text is referenced with quotations.
I structured the print statements very deliberately so I could discern when the loop started and what happened at each step in the loop and when a new iteration of the loop began.
Can you find the bug in the code now? I think there is a very easy fix!
set a = 1 initially. (Note that other solutions are certainly possible!)
n = 1
a = 1
k = input(“Please determine a value greater than or equal to 1, n, such that you want a sum of integers from 1 to n.\n”)
while n < int(k):
n = n + 1
a = a + n
print(a)
2. Control Statements and Exceptions
First, let’s examine the new features in this program. The call to input takes a string and displays it. It’s standard to tell the user what sort of input you would like. Next, we need to realize that python has several different data types, floats, ints, and strings. floats are floating point decimal numbers stored as binary representations (this will be important later). ints are signed integers (python remembers whether you integer was positive or negative). Strings are collections of symbols. Even though, to you, 10 and ten represent the same idea, to python “10” and 10 are worlds apart. The first is a string has no numeric value. We can, however, invoker the built-in int() function in python and convert k to an integer.
This program does what we would like, but it lacks several programming best practices. Users make mistakes, but good programmers catch those mistakes. Here, we have a couple of possibility for mistakes: the user could enter a number less than 1, the user could enter a sequence of nonnumeric characters, or the user could enter a floating point number. The completed programming is given below. We have a new programming structure- the if statement. This is known a type of control statement. The syntax of this statement is
if CONDITION:
COMMANDS
[else:
OTHER COMMANDS]
The else portion is optional and red portion is specified by the programmer. I would like to point out that a common programming mistake here involves the use of “==” for conditional statements. a == 2 checks to see if a is equal to 2, but a = 2 sets a equal to 2. They are NOT interchangeable. The indentions are also syntactical and python requires a certain number of indentions to determine when it is executing instructions in a loop or control structure or when it has reached the end of that loop or control structure. One other fine point to make is that we assigned a new variable int_k = int(k). The reason for this is performance oriented. It is poor practice to have function calls in a loop. They may substantially slow a program.
n = 1
a = 1
k = input(“Please determine a value greater than or equal to 1, n, such that you want a sum of integers from 1 to n.\n”)
if k.isdigit():
int_k = int(k)
if int_k == 0:
raise ValueError(“You must enter a value great than 0.”)
else:
raise ValueError(“You did not enter an integer!”)
while n < int_k:
n = n + 1
a = a + n
print(a)