0% found this document useful (0 votes)
2 views

python-part-2-notes

The document provides notes for Session 2 of an Introduction to Programming with Python course, covering data types, program writing, and operators. It includes examples of string manipulation, arithmetic, comparison, and logical operations, as well as instructions for using the IDLE editor to write and execute Python programs. The notes emphasize the importance of syntax highlighting and the convention of using the '.py' file extension for Python scripts.

Uploaded by

v5jyw66v97
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

python-part-2-notes

The document provides notes for Session 2 of an Introduction to Programming with Python course, covering data types, program writing, and operators. It includes examples of string manipulation, arithmetic, comparison, and logical operations, as well as instructions for using the IDLE editor to write and execute Python programs. The notes emphasize the importance of syntax highlighting and the convention of using the '.py' file extension for Python scripts.

Uploaded by

v5jyw66v97
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

 

   

Introduction  to  Programming  with  Python  –  Session  2  Notes  


Nick  Cook,  School  of  Computing  Science,  Newcastle  University    

Contents  
1.   Data  types  .....................................................................................................................  1  
2.   Writing  a  program  ........................................................................................................  3  
3.   Selection  .......................................................................................................................  5  
4.   Arithmetic  operators  ....................................................................................................  6  
5.   Comparison  operators  ..................................................................................................  7  
6.   Logical  (boolean)  operators  ..........................................................................................  7  
7.   Exercises  and  challenges  ..............................................................................................  8  
8.   Resources  .....................................................................................................................  8  

1. Data  types  
See  Session  2  Powerpoint  for  overview  of  data  types.  
In  IDLE  shell,  output  strings:  
01| >>> print('single quoted')
02| single quoted
03| >>> print("double quoted")
04| double quoted
05| >>> print("Nick's laptop") # include ' in string
06| Nick's laptop
07| >>> # line 08 uses single quoting to include " in strings
08| >>> print('say "hello"', '\n', 'say "goodbye"')
09| say "hello"
10| say "goodbye"
Note  space  separator  because  by  default  print('x','y','z')  adds  space  between  
the  list  of  values  (comma-­‐separated  parameters).  E.g.  print('x','y','z') outputs  
the  string  'x y z'.  
Output  numbers  and  use  str()  to  cast  a  number  to  a  string,  and    int()  to  cast  a  string  
to  a  number:  
11| >>> number = 2
12| >>> # number + number in line 13 is integer arithmetic
13| >>> print('number + number:', number + number)
14| number + number: 4
15| >>> # str(number) + str(number) in line 17 is
16| >>> # string concatenation (adding two strings)

©  Newcastle  University,  2013     1  


   

17| >>> print('number + number:', str(number) + str(number))


18| number + number: 22
19| >>> snumber = '2'
20| >>> # snumber + snumber in line 21 is string concatentation
21| >>> print('snumber + sumber:', snumber + snumber)
22| snumber + snumber: 22
23| >>> # int(snumber) + int(snumber) in line 25
24| >>> # is integer arithmetic
25| >>> print('snumber + snumber:', int(snumber) + int(snumber))
26| snumber + snumber: 4
Examples  of  integers  and  floats:  
27| >>> # casting float to int in lines 29-34 returns the
28| >>> # integer part without rounding
29| >>> int(1.2)
30| 1
31| >>> int(1.5)
32| 1
33| >>> int(1.99999)
34| 1
35| >>> # the division operator / results in a float
36| >>> 10 / 3
37| 3.3333333333333335
38| >>> # which can be truncated by casting
39| >>> int(10 / 3)
40| 3
41| >>> # the // operator does integer division
42| >>> 10 // 3
43| 3
44| >>> # the % operator results in the remainder after
45| >>> # integer division
46| >>> 10 % 3
47| 1
Note  the  mathematical  relationship  between  integer  division  and  remainder,  for  two  
numbers  n  and  m:     n  ==    (n  //  m)  *  m  +  (n  %  m).  
See  Sections  4  to  6  for  summary  of  arithmetic,  comparison  and  logical  operators.  
Comments:    
48| >>> # comment
49| >>> 2 # comment
50| 2
The  whole  of  line  48  is  a  comment  (beginning  with  a  #)  that  is  not  treated  as  executable  
code  by  the  shell.  In  line  49,  the  text  from  the  #  to  the  end  of  the  line  is  ignored.  
Example  boolean  values,  comparisons  and  casting  using  bool():  
51| >>> b = number > 1 # remember number is 2
52| >>> b
53| True
54| >>> b = number < 1
55| >>> b

©  Newcastle  University,  2013     2  


   

56| False
57| >>> bool(1)
58| True
59| >>> bool(number)
60| True
61| >>> bool(-1)
62| True
63| >>> bool('hello')
64| True
65| >>> bool(0) # 0 is False
66| False
67| >>> bool(0.0)
68| False
69| >>> bool('False') # the string 'False' is True
70| True
71| >>> bool(False) # False is False
72| False
73| >>> bool(True) # True is True
74| True

2. Writing  a  program  
In  IDLE  
  File  -­‐>  New  Window  
Opens  a  new  syntax  highlighting  text  editor  window.  Python  program  files  are  just  ordinary  
text  files  that  contain  python  code  that  can  be  interpreted  by  a  python  interpreter.  So,  any  
text  editor  can  be  used  to  write  a  python  program.  The  IDLE  editor  is  just  one  editor  that  
"understands"  python  syntax  and  can  highlight  that  syntax  and  also  provide  hints  on  
function  parameters  and  results.  There  are  other  editors,  and  programming  environments,  
that  also  understand  python  syntax  and  may  give  more  or  less  hints  on  writing  correct  
python  code.  
When  running  a  program  (or  module)  in  IDLE,  the  text  is  interpreted  as  python  code.  
Assuming  it  is  syntactically  correct,  it  is  then  executed  and  program  output  appears  in  the  
IDLE  shell  window.  
It  is  convention  to  give  python  program  files  the  extension  ".py"  (e.g.  helloworld.py).  This  is  
not  mandatory.  The  python  interpreter  will  attempt  to  interpret  and  execute  the  text  in  
any  text  file  whatever  its  extension  (e.g.  helloworld.txt).  One  difference  is  that  syntax  
highlighting  editors  (including  the  IDLE  editor)  may  only  highlight  syntax  in  files  with  the  
"correct"  extention  (.py).    

©  Newcastle  University,  2013     3  


   

 
Figure  1  –  Python  shell  and  helloworld.py  and  helloworld.txt  editor  windows  
Figure  1  shows  three  windows,  from  top  to  bottom:  a  Python  Shell,  a  helloworld.py  editor  
window,  and  a  helloworld.txt  editor  window.  In  the  first  editor  window  (helloworld.py),  
python  syntax  is  highlighted  (print('hello world')).  In  the  second  editor  window  
(helloworld.txt),  the  syntax  is  not  highlighted  –  all  text  is  black  (print('hello
world'))  .  Both  files  can  be  executed,  with  the  same  output  in  the  pyton  shell.  
To  return  to  our  first  program  …  
In  IDLE,  use:  
File  -­‐>  New  Window  
to  open  a  new  editor  window.  
Use:  
  File  -­‐>  Save  As  …  
to  save  the  file  to  a  new  file  (helloword.py).  
In  the  editor  window,  type:  
# my first program
print('hello world')
Notice  how  the  colour  of  text  changes  as  the  editor  interprets  the  syntax.  The  colours  used  
for  different  program  elements  may  vary  from  platform  to  platform  and  are  user-­‐
configurable.  

©  Newcastle  University,  2013     4  


   

Use:  
File  -­‐>  Save  
to  save  the  file.  
In  the  editor  window,  use:  
Run  -­‐>  Run  Module  
to  execute  the  program  (with  output  appearing  in  the  shell  window).  
You  can  also  use  the  shortcut  F5  to  run  a  program.  
Follow  the  same  process  for  writing  all  programs  using  IDLE.  

Class  exercises  
Do  challenges  7,  8  and  9  of  Python  Programming  Challenges.  
Note:  python  programs  can  be  executed  in  IDLE  (as  demonstrated).  They  can  also  be  
executed  using  any  python  interpreter  (e.g.  using  the  python  command  from  the  command  
line  or  by  a  Web  server  that  includes  or  can  invoke  a  python  interpreter).  

3. Selection  
Use  selection  to  choose  between  alternative  actions.  
Examples  on  whiteboard:  
If it is forecast rain
Take bus to work
Otherwise
Walk
If it is forecast rain
Take umbrella
Otherwise, if it is forecast sunny
Take sun hat
If it is forecast rain
Take umbrella
Otherwise, if is forecast sunny
and it is a holiday
Wear shorts and take sun hat

We  make  decisions  based  on  one  or  more  true/false  statements  about  the  world  (or  a  
program).  The  true/false  statements  are  conditions.  Selection  is  also  called  conditional  
logic.  In  programming  we  use  if  statements  for  conditional  logic.  
Basic  form  of  the  if  statement:  
if condition:
# do action 1
else:
# do action 2

©  Newcastle  University,  2013     5  


   

Note  the  importance  of  the  colon  and  indentation  to  demarcate  blocks  of  code.  These  are  
part  of  python  syntax.    
Work  through  3.1a  (IF  …  ELSE)  and  3.1b  (IF  …  ELIF  …  ELSE)  on  p.  13  of  An  Introduction  to  
Python  with  the  whole  class.  

Class  exercises  
Do  3.1c  (IF  …  ELIF  ….  ELIF  …  ELSE)  on  p.  14  of  An  Introduction  to  Python,  followed  by  
challenges  12  and  13  of  Python  Programming  Challenges.  
Challenge  12  needs  the  time.sleep()  function  to  pause  a  program:  
import time # import time module (only import once)
time.sleep(10) # pause for 10 seconds
In  addition,  challenge  13  needs  the  random.randint() function  to  generate  a  random  
number:  
import random # import random module
# generate random number between 0 and 100
rn = random.randint(0, 100)

4. Arithmetic  operators  
 
Operator   Description   Usage   Example   Evaluates  to  
+ Addition   lhs + rhs 7 + 3 10
– Subtraction   lhs – rhs 7 – 3 4
* Multiplication   lhs * rhs 7 * 3 21
/ Division   lhs / rhs 7 / 3 2.33333333
(floating  point)     33333335
// Division  (integer)   lhs // rhs 7 // 3 2
% Modulus  (integer   lhs % rhs 7 % 3 1
remainder)  
** Power  (index)   lhs ** rhs 7 ** 3 343

Order  of  operation  


BIDMAS  
• Brackets  
• Indices  
• Division  and  Multiplication.  Calculate  in  order  starting  from  the  left.  
• Addition  and  Subtraction.  When  only  addition  and  subtraction  remain  in  the  sum,  
calculate  in  order  starting  from  the  left.  
   

©  Newcastle  University,  2013     6  


   

5. Comparison  operators  
The  result  of  comparison  is  always  either  True  or  False  (evaluates  to  either  True  or  
False).  Double  equals  (==)  is  used  for  the  equals  to  comparison.  A  single  equals  (=)  is  
used  for  assignment.  
 
Operator   Description   Usage   Example   Evaluates  to  
== Equal  to   lhs == rhs 5 == 5 True
4 == 5 False
!= Not  equal  to   lhs != rhs 8 != 5 True
8 != 8 False
> Greater  than   lhs > rhs 10 > 3 True
3 > 10 False
3 > 3 False
< Less  than     lhs < rhs 5 < 8 True
8 < 5 False
8 < 8 False
>= Greater  than  or   lhs >= rhs 5 >= 5 True
equal  to   5 >= 1 True
5 >= 6 False
<= Less  than  or  equal   lhs <= rhs 7 <= 7 True
to   7 <= 8 True
7 <= 6 False

6. Logical  (boolean)  operators  

Operator   Description   Usage   Example   Evaluates  to  


not Logical   not rhs not True False
negation   not False True
or Logical  OR  (true   lhs or rhs True or True True
if  either  side  is   True or False True
true,  false   False or True True
otherwise)   False or False False

and Logical  AND   lhs and rhs True and True True
(true  if  both   True and False False
sides  are  true,   False and True False
false  otherwise)   False and False False
   

©  Newcastle  University,  2013     7  


   

7. Exercises  and  challenges  


• From  Mark  Clarkson's  Introduction  to  Python:  all  of  Section  1,  Sections  2.1  to  2.4,  
and  Section  3.1  
• From  Python  Programming  Challenges:  challenges  1  to  13  (challenge  13  does  not  
require  iteration,  but  the  use  of  iteration  would  improve  the  solution)  
• From  Python  Programming  Challenges  Book  2:  challenges  2.1  to  2.5  

8. Resources  
• Powerpoint  handout  for  this  session:  
http://www.ncl.ac.uk/computing/outreach/resources/programming/python/intro2python
/intro2python-­‐02-­‐handout.pdf  
• Other  material  from  Newcastle  University  Introduction  to  Python  CPD:  
http://www.ncl.ac.uk/computing/outreach/resources/programming/python/intro2python  
• 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     8  

You might also like