Download part 1 notes - Newcastle University

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
 Introduction to Programming with Python – Session 1 Notes Nick Cook, School of Computing Science, Newcastle University Contents 1. Introduce IDLE and simple values ................................................................................. 1 2. Simple output ............................................................................................................... 2 3. Variables and assignment ............................................................................................. 2 4. Simple Input .................................................................................................................. 4 5. Programming challenges .............................................................................................. 5 6. Excel and programming ................................................................................................ 5 7. Turtle spirograph example ........................................................................................... 6 8. Resources ..................................................................................................................... 6 1. Introduce IDLE and simple values Start up IDLE and give brief overview of menus Point out >>> prompt for typing and interpretation of commands (python code) Do together and explain as go along: 01| >>> 2 + 2
02| 4
03| >>> 17 – 9
04| 9
05| >>> 16 / 4
06| 4.0
# Note: "true" division -> floating point
number
07| >>> 1 + 1
08| 2
09| >>> 'a' + 'b'
10| 'ab'
11| >>> '1' + '2'
12| '12'
Note: •
•
•
•
Different types of values Lines 01, 03, 05 and 07 are integer arithmetic Line 05 is true division resulting in floating point number (line 06) Lines 09 and 11 add strings of characters together (string concatenation: appending one string to another) © Newcastle University, 2013 1 Question: what happens if try 1 + '2'?
13| >>> 1 + '2'
14| Traceback (most recent call last):
15|
File "<pyshell#0>", line 1, in <module>
16|
1 + '2'
17| TypeError: unsupported operand type(s) for +: 'int'
and 'str'
Cannot add a string to an integer (see line 17). What about unquoted strings? 18| >>> bob
19| Traceback (most recent call last):
20|
File "<pyshell#5>", line 1, in <module>
21|
bob
22| NameError: name 'bob' is not defined
Without quotes bob is just a name that has not been defined (has not been assigned a value – see line 22). 2. Simple output If a string is typed into the IDLE shell, it is evaluated and echoed to the shell. 01| >>> 'bob'
02| 'bob'
The shell interprets the expression and echoes it. To output from a program, use the print command (or function). 03| >>> print(1)
04| 1
05| >>> print('1')
06| 1
Execution of lines 03 and 05, outputs a string representation of the value passed to the print() function. The print() function does not evaluate the value passed to it, it just converts it to a string (if necessary) and outputs it to standard output (the shell window). The output is not quoted because output from print()is always a string of (mostly) human readable characters. Traditionally, everyone's first program is 'Hello World'. In python, this is as simple as: 07| >>> print('Hello World')
08| Hello World
So far we have just been using direct interpretation in the shell of fixed values (1, 'bob' etc.). To be useful, programs use variables that can be manipulated, used in calculations and reused (similar to the contents of a cell in Excel). 3. Variables and assignment Variables have a name, a value and a type (string, integer etc.). Assignment means giving a named variable a value of some type, e.g.: © Newcastle University, 2013 2 give the variable named bob the value 2 which is an integer (its type) Defining and assigning to a variable allocates space in computer memory for a value of the given type. The variable refers to the location in memory. In python the equals sign (=) is the assignment operator. = gives a value to a variable. In IDLE type: 01| >>> a = 2
Note: there is no echo but a has been assigned the value 2, type a: 02| >>> a
03| 2
The shell evaluates a and echoes 2. Type: 04| >>> print(a)
05| 2
The print() function outputs the string representation of a which is 2. a is just a name. A variable can have any name you like (apart from reserved keywords or special characters). For a simple integer used in a calculation, a (or x or y) can be a sensible name. But always consider using meaningful names, e.g.: 06| >>> alice = 2
07| >>> numberOfSides = 4
numberOfSides is a meaningful name for the number of sides of a shape. We now have three variables, a, alice and numberOfSides. Question: what happens if we add a to alice?
08| >>> alice + a
09| 4
The two values of alice and a are added together. What do we expect from print(numberOfSides)? 10| >>> print(numberOfSides)
11| 4
Can also assign one variable to another, giving a variable the value of another variable, e.g: 12| >>> numberOfSides = alice
13| >>> print(numberOfSides)
14| 2
printNumberOfSides is given the value of alice. Assignment always works to the left. The variable on the left hand side of the equals sign is given the value on the right hand side. In python, you can re-­‐assign to a variable •
•
15|
16|
change the value of the variable and change the type of the variable >>> x = 2
# x is given the value 2 (an integer)
>>> x = 'two' # x now has the value 'two' (a string)
© Newcastle University, 2013 3 Assignment quiz •
•
•
Do question 1 together. Then on own or in groups, class completes the quiz on paper, using trace tables if necessary and for practice (explain trace table for question 1 on whiteboard) Then load and run python version of the quiz from o http://www.ncl.ac.uk/computing/outreach/resources/programming/python
/intro2python o Show how to load and run python program from file 4. Simple Input Recap: have covered the IDLE shell, variables and assignment, now looking at simple input Python has an input() function to get user input. Use the function to ask the user for some input. The result of executing the function is the character string that the user inputs, which can be assigned to a variable. 01|
02|
03|
04|
05|
>>> name = input('What is your name? ')
# type nick in response to question
What is your name? nick
>>> print(name)
nick
The name variable is assigned the result of asking'What is your name? '. Question: What type do you expect name to be? •
It is a string – the input function returns a string of characters because it is a string of characters that the user types at the keyboard. Question: If we do: 06| >>> age = input('What is your age? ')
What type do you expect age to be? •
07|
08|
09|
It is also a string, even if the user inputs digits, as follows: What is your age? 12
>>> age
'12'
input() does not attempt any interpretation of the string of characters typed by the user. It just returns them. In a program they may be converted to a number.
10| >>> age = input('What is your age? ')
11| # type 52 in response
12| What is your age? 52
13| >>> age
14| '52'
15| >>> age + 1
16| Traceback (most recent call last):
17|
File "<pyshell#8>", line 1, in <module>
© Newcastle University, 2013 4 18|
age + 1
19| TypeError: Can't convert 'int' object to str
implicitly
Line 15 generates a type error (see line 19) because age is not a number (or integer), therefore 1 cannot be added to it. We have to do type conversion (or casting) to change the user input to a number, e.g.: 20| >>> age = input('What is your age? ')
21| # type 52 in response
22| What is your age? 52
23| >>> age
24| '52'
25| >>> int(age) + 1
26| 53
Question: What happens if the user does not input a string of digits when a number is expected? 27| >>> age = input('What is your age? ')
28| # type fifty-two in response
29| What is your age? fifty-two
30| >>> int(age) + 1
31| Traceback (most recent call last):
32|
File "<pyshell#13>", line 1, in <module>
33|
int(age) + 1
34| ValueError: invalid literal for int() with base 10:
'fifty-two'
The type conversion in line 30 generates a value error (see line 34) because 'fifty-­‐two' is not a valid string of digits. Validation of user input will be covered in a later session. 5. Programming challenges Do challenges 1 to 6 from Mark Clarkson's Python Programming Challenges •
•
•
Just write programs directly in the IDLE shell If there is an error, try to get used to working out what the Traceback error messages mean and start again and, of course, ask for help If the shell hangs, use Shell -­‐> Restart Shell to restart the shell. If that doesn't work, quit IDLE and start again 6. Excel and programming If you know how to use Excel, you can program. Excel has variables, assignment, arithmetic, types, type conversion, string concatenation, etc. Enter the following into an Excel spreadsheet. A B 1 1 2 © Newcastle University, 2013 C D = A1 + B1 = text(A1, 0) & text(B1, 0) 5 Assignment: A1 = 1
B1 = 2
Arithmetic using the + operator: C1 = A1 + B1
•
•
•
For the given values of A1 and B1, the value of C1 is 3 The value of C1 will change if either A1 or B1 change A1, B1 and C1 are all number variables Type conversion using the text() function and string concatenation using the & operator: D1 = text(A1, 0) & text(B1, 0)
•
D1 is a string variable that is given the result of casting the values of A1 and B1 to strings and concatenating the result using Excel's string concatenation operator (&). The python equivalent is: d1 = str(a1) + str(b1)
•
For the given values of A1 and B1, the value of D1 is '12' 7. Turtle spirograph example As a taster of where we are going by the end of the course. Download turtles1demo.py from http://www.ncl.ac.uk/computing/outreach/resources/programming/python/intro2p
ython/ •
Demonstrate loading and running turtles1demo.py 8. Resources • Powerpoint handout for this session: http://www.ncl.ac.uk/computing/outreach/resources/programming/python/intro2p
ython/intro2python-­‐01-­‐handout.pdf • Other material from Newcastle University Introduction to Python CPD: http://www.ncl.ac.uk/computing/outreach/resources/programming/python/intro2pytho
n • Mark Clarkson's Introduction to Python resources including textbook, workbooks, example code and GCSE controlled assessment: http://www.ncl.ac.uk/computing/outreach/resources/protected/mwclarkson-­‐
resources.zip • Other Python resources: http://www.ncl.ac.uk/computing/outreach/resources/programming/python/ • Python Web site: http://www.python.org/ © Newcastle University, 2013 6