Download 1-2

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
CSC 241 NOTES
Y o s e f M e n de l s o h n
W i t h ma ny t h a n ks t o D r . A mb e r S e t t l e f o r t h e or i g i n al v e r s i o n of t he s e no t e s .
P r of S e t t l e ' s n ot e s i n t u r n a r e b a s e d o n t he P e r ko vi c t e x t .
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.
2.
3.
4.
5.
6.
x=5
x = 5.0
x = “5”
x = “hello”
x = hello
x = 3+4.5
#integer
#float
#string
#string
#error – unless a variable called ‘ehllo’ was defined at some earlier point
#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 yo utype 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.
2.
3.
4.
5.
6.
7.
8.
x = “hello”
x = “True”
x = True
x = “False”
x = False
x = 3+4
x = 3+4.0
x = 3<2
#string
#string
#boolean
#string
#boolean
#integer
#float
#boolean
Boolean expressions
Boolean expressions evaluate to either True or False rather than to a numerical
value.
True or False are stil 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
2



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 evalutae 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
3
>>> (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)
4
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.
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, 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
5
'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 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".
6
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:
7
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:
8
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 backshash \ 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:
9
>>>
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 one that we will discus it 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')
10
>>> y+4
21
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:
>>>
Enter x: 17
x is 17
>>> x+4
21
Working with Strings
Strings turn out to be extremely important in programming. They have huge
implications in marketing, security, data science, and more. Therefore, we will
spend a certain amount of time discussing techniques fokr working with strings.
It is very important that you become proficient at these techniques. Even though
they may seem to be somewhat pointless right now, they will become increasingly
important as you progress in programming.
Indexing Strings
Let's begin by talking about how to 'index' strings. That is, how to work with
individual characters of a string.
The individual characters of a string can be obtained using the indexing operator
which uses a pair of square brackets: []
The indexing operator takes a non-negative index (i.e. an integer number) and
returns the character of the string at offset of that index:
>>> a = 'hello'
>>> a[0]
'h'
>>> a[1]
'e'
>>> a[2]
'l'
Substrings of a string can be obtained using the indexing operator:
11
>>> name = 'Steve'
>>> name[0]
'S'
>>> name[0:2]
'St'
>>> name[3:4]
'v'
>>> name[1:4]
'tev'
If you leave out a character after the colon, you get all of the remaining
characters in the string. In the example below, all of the characters from
index location 2 through to the end of the string are returned:
>>> name[2:]
'eve'
Similarly, if you leave out a character before the colon, you get all of the
previous characters in the string:
>>> name[:2]
'St'
Note that, unlike the previous example, in this case, the index '2' is not
included in the output.
Negative indices can be used to access the characters from the back of the
string. For example, the last character can be obtained as follows:
>>> a[-1]
'o'
Putting it together: Interactive input and indexing
strings
Exercise: Implement a program that takes a 3-character string from the
user and prints the string with its characters reversed. You may assume
that the user will only enter a string that is exactly 3 characters. (However,
in the real world, we can never assume that users will 'follow the rules'!)
Example run:
>>>
Enter a string: ABC
CBA
Hint: See the table in Chapter 2 of the Perkovic text for string
functions that will help with this.
12
For one possible solution, see reverse.py.
Note: There are always multiple ways of accmplishing a given task.
Therefore your code will typically look different to mine. At this point,
because our programs are fairly short and simple, they will probably look
pretty close. However, as we progress through the course, you will see that
there are often multiple ways of accomplishing a given task.
13