CSC 241 Notes
Yosef Mendelsohn

With many thanks to Dr. Amber Settle for the original version of these notes.

Prof Settle's notes in turn are based on the Perkovic text.

Data Types

Every piece of data as an associated “type”. As of this point, you have seen a few data types: integers (whole numbers), floats (numbers with a decimal), and strings (text). For each of the following, identify the data type stored inside the variable ‘x’:

  1. x = 5 #integer
  2. x = 5.0 #float
  3. x = '5' #string
  4. x = 'hello' #string
  5. x = hello #error – unless a variable called ‘hello’ was defined at some earlier point
  6. x = 3+4.5 #float (since x is holding 7.5)

We will discuss data types in more detail as we proceed through the course.

However, let’s add a new and very important data type to our repertoire: ‘Booleans’. A boolean value is either True or False. Note that these are not strings. The moment you type in True or False in Python, Python recognizes that data type for what it is. That is, just like then you type in “hello” Python knows it’s a string, or when you type in 3.14, Python recognizes that value as a float, when you type False, Python will recognize that value as a boolean.

Let’s do a few more examples. Identify the data type stored inside the variable ‘x’:

  1. x = 'hello' #string
  2. x = 'True' #string
  3. x = True #boolean
  4. x = 'False' #string
  5. x = False #boolean
  6. x = 3+4 #integer
  7. x = 3+4.0 #float
  8. x = 3<2 #boolean

Boolean expressions

Boolean expressions evaluate to either True or False rather than to a numerical value.

True or False are still considered to be literals (just likes strings, integers, and floats).

For example, 3 < 2 should evaluate to false. Boolean expressions are used to test whether a logical statement is true or false.

Consider the following examples:

> 3 < 2

False

> 3 > 2

True

> x = 4

> x == 4

> # NOTE: == is a “comparison operator”

True

> x == 3

False

> x > 4

False

> x <= 4

True

> x != 5

True

In the example above we can see that testing whether two expressions have the same value is done using the double equality (==) operator.

To check whether two expressions are not equal, the not equals operator (!=) is used.

Just like any other literal, boolean values (True and False) can be stored inside variables:

> answer = True

> print(answer)

True

> answer = (3 2)

> print(answer)

False

In the previous example, we did not have to place (3<2) in parentheses. However, doing so made the code a little more clear.

And, as you are (hopefully) well aware by now, making code clear is always a great idea!

> age = 35

> allowed_to_drink = (age>=21)

> allowed_to_drink

True

Exercises: Do the following CodeLab exercises from Week 1, Lecture 2:

·  51053

·  51056

·  51057

·  51059

·  51054

·  51060

Boolean operators

Just like algebraic expressions can be combined into larger algebraic expressions, Boolean expressions can be combined together using the Boolean operators and, or, and not.

The and operator applied to two Boolean expressions will evaluate to True if both expressions evaluate to True. That is, if either expression evaluates to False, then the whole thing will evaluate to False.

> (2 < 3) and (4 > 5)

False

> (2 < 3) and (7 > 2)

True

> (2 < 3) and (3==4)

False

> (2 < 3) and False

False

As we’ve mentioned, the parentheses in the above examples are not required, but are a good idea. That being said, you'll find that people often do not include parentheses in some of these situations, so you should be able to interpret expressions like the above ones regardless of whether they include parentheses or not.

The or operator applied to two Boolean expressions evaluates to True if any of the expressions are true. That is, as long as one or both are True, then it evaluates to True. When you have some expressions separate by ‘or’, the only way for the condition to evaluate to false is if all of the expressions are false.

> 2 < 3 or 4 > 5

True

> 3 < 2 or 2 < 1

False

More examples:

x = 10

y = 5

> (x>4) and (y<10)

True

> (x>4) and (y<3)

False

> (x>4) or (y<3)

True

The not operator is a unary Boolean operator, which means that it is applied to a single Boolean expression. It evaluates to False if the expression it is applied to is True, or to True if the expression is False.

> not (3 < 4)

False

The following "truth table" is taken from the Perkovic text:

CodeLab: Do the following CodeLab exercise from the Week 1, Lecture 2section: 51062

Data Types

Every literal has an associated 'data type'. For the next little while in the course, we will focus on 3 data types in particular:

1.  Integers: Any whole number. For example: 3, 4, -27, 2233445562, 0, etc

2.  Floats: Any number that has a decimal. Example: 3.1415, 0.0, -0.34

3.  Strings: Any string of characters that is not a number. This includes symbols. E.g. 'hello', 'h', ' ' (i.e. a space), '^', '&(*@' à Note that in Python, strings are placed inside quotes. We will spend a lot of time becoming familiar with Strings.

Exercise:

For each example below, indicate the data type of the literal:

1.  3 integer

2.  '3' string

3.  0 integer

4.  'hello' string

5.  '' string (an empty string)

6.  ' ' string (holding a space)

Strings

Strings are used to represent character data.

Consider the following example:

> 'hello'

'hello'

> 'Hello world!'

'Hello world!'

String values can be represented as a sequence of characters, including blanks or punctuation characters, enclosed within single quotes. Double quotes will typically work, but for consistency's sake, it's best to stick with single quotes.

IMPORTANT: If the quotes are omitted, the text will be treated as a variable name, not a string value.

> hello

Traceback (most recent call last):

File "<pyshell#31>", line 1, in <module>

hello

NameError: name 'hello' is not defined

String values can be assigned to named variables:

> word1 = 'hello'

> word2 = 'world'

> word1

'hello'

> word2

'world'

Python provides a number of operations that can be performed on string values.

Concatenating (i.e. combining) Strings:

Concatenation turns out to be an important tool in many different areas, and we will be using it a lot in this course, so be sure that you are comfortable with it!

The ‘+’ operator, when used on two strings does NOT do addition! I hope you agree that trying to mathematically add two strings makes no sense. Instead, the + operator when surrounded by two strings returns a new string that is the combination of the two strings. We call the process of combining strings "concatenation".

> word1 = 'hello'

> word2 = 'world'

> word1 + word2

'helloworld'

> word1 + ' ' + word2

'hello world'

> 'one' + 'two'

'onetwo'

> 'How' + 'are' + 'you?'

'Howareyou?'

> 'How' + ' are' + ' you?'

'How are you?'

> word1 * word2

Traceback (most recent call last):

File "<pyshell#39>", line 1, in <module>

'hello' * 'world'

TypeError: can't multiply sequence by non-int of type 'str'

> word1 * 3

'hellohellohello'

However, the multiplication operator '*' can be used as a convenient shortcut when you want to output a string several times:

> 30 * '^'

'^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^'

CodeLab: Do the following CodeLab exercises from the 'Week1, Lecture 2' section:

·  51754

·  51755

·  51756

·  51098

Python files

A Python program is a text file containing Python statements. A programmer uses a text editor to create this file.

At this point, you've probably noticed that it can be tedious and frustrating to have to retype a block of code when all you want to is make some small modification to test or fix something.

One very useful solution is to take our code and put it in a file. You can then make as few or as many modifications as you like, and simply tell Python to run the entire file.

In order to type Python code into a file, the first thing we need is a "text editor".

Text Editors

Important: A word processing program such as Microsoft Word is NOT a valid text editor. It is, in fact, an entirely inappropriate choice for writing and editing programs in part because it adds extra formatting characters into the file. Instead programmers use specialized text editors to write their code.

There are many good editors for developing Python programs. We will use one called IDLE as it is full-featured, convenient, and easy to learn.

IDLE should have been installed when you installed Python.

NOTE:

·  Windows users: Do NOT use Windows Notepad.

·  Mac Users: Do NOT use TextEdit.

·  If you have done some coding before and have a preferred text editor that you already know how to use, this is fine with me. However, I can't guarantee that I'll be able to help if you run into problems with it.

IDLE includes features that are helpful for Python programming, such as: automatic indentation, abilities to run/debug Python code from within the editor, etc.

Exercise: Write the classic hello world program and save it as helloworld.py. (The 'py' extension is important).

To do so, first open the IDLE editor, then click on “File” and then “New File”. Then type out the program as shown below:

To execute this program, click F5. Or you can click on “Run” and then “Run Module”. ('Module' is Python's name for a file).

You will be asked to save the program in a file. The file name must have the suffix ‘.py’.

Optional: Running a Python Program from the Command Line

Once you’ve saved a Python program, you can also run it from the command line in the command-line window of your computer.

To run your program from the command line, you would type:

python helloworld.py

Important: This is not a Python command. That is, you would not type this command from inside a Python shell or text editor such as IDLE. Rather, this is a command you would type at the command line on your operating system.

Path: Also, your operating system needs to know exactly where (i.e. in which folder) your helloworld.py file lives. On my computer I had this file stored in a folder called: c:\temp\241

So in this case I would type:

python c:\temp\241\helloworld.py

If you want to avoid having to type out the full path to your file, use the 'cd' command to change to the folder where your Python files are stores. The 'cd' command works for Windows and Unix/Linux operating systems. The only difference is that while windows uses the backslash \ to separate folders, Unix-based systems use a forward slash: /

Here is how we would change to the temp à 241 folder in Windows:

cd c:\temp\241

Now you can simply type the 'python' command and your filename without having to write the entire path:

python helloworld.py

An application program – even one as simple as your helloworld.py program is typically run from outside “friendly” environments such as IDLE. Therefore, it is important to understand how to execute Python programs at the command line.

Interactive input

In order to solve a wider variety of problems, executing programs often need to interact with the user. For example, you may want to ask the user for some information such as their name or their age.

The 'input' function is used by the program to request input data from the user. Whatever the user types in will be treated as a string. That is, even if you ask the user for, say, their age and they type in an integer, Python will initially store it as a string.

Consider the following program in the file test_input1.py:

x = input("Enter x: ")

print("x is", x)

When this program is run it produces the following sample output:

>

Enter x: 'Hello'

Your value is 'Hello'

Important: Note that when we just ran the program, we had to put our input 'Hello' inside quotes. The reason is that if we didn't, the program would think that Hello was a variable. In order to indicate that it is a string, we had to put it in quotes.

If this last paragraph confuses you, don't worry about it just yet. It is an important issue, and therefore, we be discussed in more detail as we progress.

Strings v.s. Numbers

Let's rerun the 'test_input.py' program:

>

Enter x: 17

x is 17

At the moment, 'x' is holding the String '17':

> print(x)

'17'

Important: What would happen if we added 4 to this value?

> x+4

Traceback (most recent call last):

File "<pyshell#10>", line 1, in <module>

x+4

TypeError: Can't convert 'int' object to str implicitly

What happened?? We received this error because x is holding the string '17'.

Note that the variable 'x' is not holding the integer 17. It is holding the string '17'. Does it make sense to add a number to a string? For example, what do you think of the command:

> 'hello' + 5

I hope that you agree that this doesn't make much sense.

In order to force Python to evaluate a string, you need to use the eval() function:

> y = eval('17')

> y+4

21

In the above example, the string argument that is passed to the eval() function gets converted to an integer.

So we can modify the program above to produce a new one that reads in expressions that should be evaluated in a way that includes data types other than strings:

x = eval( input ("Enter x: ") )

print("x is", x)

When this program is run it produces the following sample output: