24
CSC 401 NOTES Lecture #1 Yosef Mendelsohn Getting started with Python You can find out the link to install Python by visiting the 'Resources' page. Briefly, go to www.python.org and download Python version 3.6 or later. When you do, you will have a copy of the language on your computer, as well as a specizied text editor for writing your code called IDLE. The Python interpreter One way you can use Python is by using the "command- line" window. This will look something like: You can then execute the classic first program (hello world) as follows: >>> print("Hello world!") Hello world!

Lecture 1 - DePaul University · Web viewThe easiest types of expressions are mathematical expressions, which will have us using the Python interpreter like a calculator. To do this,

  • Upload
    others

  • View
    1

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Lecture 1 - DePaul University · Web viewThe easiest types of expressions are mathematical expressions, which will have us using the Python interpreter like a calculator. To do this,

CSC 401 NOTESLecture #1

Yosef Mendelsohn

Getting started with Python

You can find out the link to install Python by visiting the 'Resources' page. Briefly, go to www.python.org and download Python version 3.6 or later. When you do, you will have a copy of the language on your computer, as well as a specizied text editor for writing your code called IDLE.

The Python interpreterOne way you can use Python is by using the "command-line" window. This will look something like:

You can then execute the classic first program (hello world) as follows:

>>> print("Hello world!")Hello world!

The function print() is not like a function in mathematics.

It takes input, for example the phrase Hello world!, and does something with it, specifically prints it to the screen.

Page 2: Lecture 1 - DePaul University · Web viewThe easiest types of expressions are mathematical expressions, which will have us using the Python interpreter like a calculator. To do this,

However, the way we are going to code in this course is by using a specizied text editor called IDLE. The screen shot below shows an execution of the hello world program:

In this course, we will use IDLE for all of our development. You are certainly free to use a different text editor if you find one that you prefer. However, this class will use IDLE.

ExpressionsOne of the most fundamental things in any programming language is an expression.

The easiest types of expressions are mathematical expressions, which will have us using the Python interpreter like a calculator. To do this, we type an ordinary algebraic expression at the prompt and press enter to evaluate it:

>>> print(3+7)10

Note: When typing an expression (eg: 3+7 ), IDLE will not only cause that expression to be executed, but it will also typically output the result of that expression:

In other words, typing the following:>>> 3+7

Will result in the following output:10

Let's look at some more expressions:

2

Page 3: Lecture 1 - DePaul University · Web viewThe easiest types of expressions are mathematical expressions, which will have us using the Python interpreter like a calculator. To do this,

>>> 12/52.4

>>> 12 // 52

>>> 12 % 52

>>> 3*2+17

>>> (3-1)*(4+1)10

>>> 4.321/3+1011.440333333333333

>>> 4.321/(3+10)0.3323846153846154

>>> 2.752.75

>>> 2**38

Variables and IdentifiersLike you have seen in algebra, a value may be assigned to variable. For example, we can create a variable and then assign it a number.

Let's create a variable called 'age' and assign it a value of 65:>>> age = 65>>> print(age)65

Identifiers: An identifier is the name we give to something. Any time we name something (such as a variable) we must choose an identifier. Choose your identifiers wisely! Good code is clear code.

Suppose we wanted to have a variable in which we recorded the age at which people are allowed to consume alcohol. Which of the following identifiers do you think is best?

>>> x = 21>>> age = 21>>> legal_drinking_age = 21

I hope you agree that the last one is far more clear.

3

Page 4: Lecture 1 - DePaul University · Web viewThe easiest types of expressions are mathematical expressions, which will have us using the Python interpreter like a calculator. To do this,

That being said, when you are just practicing, you don't need to go overboard on this. When we are learning Python, I don't mind if you use identifiers such as 'x' or 'n1' and things like that. However, when writing code such as for your homework, you should always try to use clear identifiers!

Getting back to variables…>>> y = 21>>> print(y)21

>>> x>>> print(x)Traceback (most recent call last): File "<pyshell#10>", line 1, in <module> xNameError: name 'x' is not defined

Note the initial error message above. The variable name x is undefined until it is assigned. Any attempt to use the variable before it is defined will result in an error. However, the code below will execute just fine:

>>> x = 3>>> x3

Note: Again, we do not necessarily have to type 'print(x)' above. In a live interpreting environment such as IDLE, Python will automatically output the result However, when you are executing a complete program, you should use the 'print' function if you wish to output information to the console.

Assignment Statements

The statement x = 4 is called an assignment statement.

An assignment statement has the following syntax:<variable name> = <expression>

Important: Note that the assignment operator (=) here is not checking whether one value is equal to another. Instead, the '=' operator is assigning a value to the variable 'x'. If you want to compare two things to see if they are identical, we use a different operator. We will discuss this shortly.

In an assignment statement, the expression to the right of the assignment operator is evaluated and then the value of the expression is placed into the variable on the left side of the assignment operator.

4

Page 5: Lecture 1 - DePaul University · Web viewThe easiest types of expressions are mathematical expressions, which will have us using the Python interpreter like a calculator. To do this,

Once a value has been assigned to a variable, the variable can be used in expressions.

When Python evaluates an expression containing a variable, it will evaluate the variable to its currently assigned value.

Consider the following example:

>>> x = 4>>> 4*x16

>>> y = 4*x>>> y16

It is also possible to modify the value of an existing variable:>>> score = 83>>> score = score + 3>>> print(score)86

>>> salary = 50000>>> salary = salary + (0.1*salary)>>> print(salary)55000.0

Let's say we have exam scores for 3 students and wish to calculate the average of those scores:

>>> score1 = 87>>> score2 = 93>>> score3 = 62>>> mean = (score1+score2+score3)/3.0>>> print(mean)80.66666666667

>>> print(score4)Traceback (most recent call last): File "<pyshell#10>", line 1, in <module> score4NameError: name 'score4' is not defined

Note: In our example for 'mean' it was necessary to divide by 3.0 rather than 3. We will discuss the reason for this down the road.

Data TypesEvery 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’:

5

Page 6: Lecture 1 - DePaul University · Web viewThe easiest types of expressions are mathematical expressions, which will have us using the Python interpreter like a calculator. To do this,

Note: You can see the answers by enlarging the font.

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 expressionsBoolean 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 < 2False

>>> 3 > 2True

>>> x = 4>>> x == 4 >>> # NOTE: == is a “comparison operator”True

>>> x == 3False

6

Page 7: Lecture 1 - DePaul University · Web viewThe easiest types of expressions are mathematical expressions, which will have us using the Python interpreter like a calculator. To do this,

>>> x > 4False

>>> x <= 4True

>>> x != 5True

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_drinkTrue

Boolean operatorsJust 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)

7

Page 8: Lecture 1 - DePaul University · Web viewThe easiest types of expressions are mathematical expressions, which will have us using the Python interpreter like a calculator. To do this,

False

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

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

>>> (2 < 3) and FalseFalse

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 > 5True

>>> 3 < 2 or 2 < 1False

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.

8

Page 9: Lecture 1 - DePaul University · Web viewThe easiest types of expressions are mathematical expressions, which will have us using the Python interpreter like a calculator. To do this,

>>> not (3 < 4)False

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

This is not something you need to memorize!

Data TypesEvery 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, etc2. Floats: Any number that has a decimal. Example: 3.1415, 0.0, -0.343. 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 integer2. '3' string3. 0 integer4. 'hello' string5. '' string (an empty string)6. ' ' string (holding a space)

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

9

Page 10: Lecture 1 - DePaul University · Web viewThe easiest types of expressions are mathematical expressions, which will have us using the Python interpreter like a calculator. To do this,

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

>>> helloTraceback (most recent call last): File "<pyshell#31>", line 1, in <module> helloNameError: 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

10

Page 11: Lecture 1 - DePaul University · Web viewThe easiest types of expressions are mathematical expressions, which will have us using the Python interpreter like a calculator. To do this,

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 * '^''^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^'

Python filesA 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 EditorsImportant: 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.

11

Page 12: Lecture 1 - DePaul University · Web viewThe easiest types of expressions are mathematical expressions, which will have us using the Python interpreter like a calculator. To do this,

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 LineWe will typically NOT use this process. Instead, we will typically run our programs using our IDE (i.e. IDLE). However, I am including it here for completeness.

12

Page 13: Lecture 1 - DePaul University · Web viewThe easiest types of expressions are mathematical expressions, which will have us using the Python interpreter like a calculator. To do this,

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.

13

Page 14: Lecture 1 - DePaul University · Web viewThe easiest types of expressions are mathematical expressions, which will have us using the Python interpreter like a calculator. To do this,

Interactive inputIn 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:

x = input("Enter x: ")print("x is", x)

TRY IT: Save these two lines of code in a file called: input_practice.py and then execute it by pressing F5.

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. NumbersLet's rerun the 'test_input.py' program:

>>> Enter x: 17x is 17

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

14

Page 15: Lecture 1 - DePaul University · Web viewThe easiest types of expressions are mathematical expressions, which will have us using the Python interpreter like a calculator. To do this,

>>> print(x)'17'

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

>>> x+4Traceback (most recent call last): File "<pyshell#10>", line 1, in <module> x+4TypeError: 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.

One way we can force Python to evaluate a string is to use the eval() function:

>>> y = eval('17')>>> y+421

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:

>>> Enter x: 17x is 17

>>> x+421

15

Page 16: Lecture 1 - DePaul University · Web viewThe easiest types of expressions are mathematical expressions, which will have us using the Python interpreter like a calculator. To do this,

NOTE: While I am showing you the eval() function here, we are, for the most part, going to be using a different method for converting between data types. This method is called “casting”.

Working with StringsStrings 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 for 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 StringsLet'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:

>>> name = 'Steve'

>>> name[0]'S'

>>> name[0:2]'St'

>>> name[3:4]'v'

>>> name[1:4]

16

Page 17: Lecture 1 - DePaul University · Web viewThe easiest types of expressions are mathematical expressions, which will have us using the Python interpreter like a calculator. To do this,

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

>>> name[-1]'e'

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

Hint: See the table in Chapter 2 of the Perkovic text for string functions that will help with this.

For one possible solution – and AFTER trying it yourself! – feel free to look at one possible answer via the code below (enlarge it as needed):

#print("Hello world!")#print("This is our second Python class.")

#num = eval(input("Enter your favorite number: "))#print("Three times your number is:", num*3)

s = input("Enter a 3-character string: ")# We assume that s is exactly three characters longprint(s[2] + s[1] + s[0])

17

Page 18: Lecture 1 - DePaul University · Web viewThe easiest types of expressions are mathematical expressions, which will have us using the Python interpreter like a calculator. To do this,

Note: There are always multiple ways of accomplishing 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.

Also note: As mentioned above, we will be moving away from the eval() function in favor of the casting technique.

18