Download presentation
Presentation is loading. Please wait.
1
Python 3.x Programming Key Stages 1-5 (OCR/AQA)
Continuing Professional Development in Computer Science Secondary School Teachers Python 3.x Programming Key Stages 1-5 (OCR/AQA) Session-1 (of 5) October – November 2017
2
Course Introduction Procedural programming concepts
Develop programming skills in Python 3.x Sequence I/O, variables, data types, arithmetic and converting data Selection If-else, function calls Iteration For, While, nesting Compound Types tuples, lists, dictionaries Files I/O, strings, exceptions
3
Course Introduction Computational thinking Structured development
Pseudocode, Structured English Analysis and design of programs Incremental development
4
Environment Python v3.x Use v3.5 or above Incompatible with v2.x
Edit code in IDLE (Integrated Environment) Possible to edit in Notepad(++) and paste to IDLE interpretation, execution, debugging Represent algorithms as structured code
5
Programming Constructs
Sequence print statements and input statements Selection (branching) if, if…else, break, continue statements Iteration (repetition) while and for statements These constructs apply to ‘data types’
6
Data Types Strings (collection of characters) Numeric (Integer, Float)
No ‘char’ type: It’s a string length = 1 in Python Case sensitive! Numeric (Integer, Float) There is no ‘longint’ or ‘double’ type in Python Compound (Lists, Tuples, Dictionaries) Equivalent to the ‘array’ type
7
Output of Strings print() function
Must have parentheses Strings are enclosed in quotes use a consistent ‘house style’ (PEP0008) Default output is left justified exactly what is between the quotes. See Appendix-03 Style-1 Style-2 print (‘Hello World’) print (“Hello World”) Hello World outputs left-justified with any other characters that are between the quotes
8
Output of strings Escape Sequences
Sess1_Example-1.py print (“Hello World”) Hello World print (“\tHello World”) print (“Hello \nWorld”) Hello World print (“Hello \”World\””) Hello “World” print (“Hello \\World”) Hello \World Also see Appendix-03 for managing quotes and escape chars Use a ‘\’ character to escape special chars \t for a single tab \n for a newline \” for a quote \\ for a backslash
9
Output of strings More control
Sess1_Example-1.py cont’d print (“Hello”) print (“World”) Hello World print (“Hello”,end””) Hello World print (“A very “ \ “very long line”) A very very long line # print a blank line print() Suppress the newline char: end=“” Splitting a long line (\) Comments (#) Output a blank line
10
Input of strings input ( ) function
Must have parentheses halts execution until user enters data and presses return key A variable holds the input (see appendix-01) Data is assigned to the variable with ‘=‘ No reserved words used for variable names (appendix-02) Sess1_Example-2.py # ‘=‘ is the assignment operator – it isn’t the equals operator (==) userName = input(“Enter Your Name: “) test1 print (“Hello”,userName) Hello test1 There are no spaces between the quotes: The comma is a ‘separator’. It will put a space in the output for us
11
Sess1_Exercise-1_Menu Load
Sess1_Exercise-1_Menu_Question.py Finish the code to output the menu as shown right Prompt user for input Echo back what they entered Answer is in Sess1_Exercise-1_Menu_Solution.py Main Menu D: Division M: Multiplication A: Addition S: Subtraction X: Exit Enter an Option:
12
I/O of strings String Methods
Further control of output can be done with string methods. The methods are ‘called’ using dot notation Practice with the following – study the output name = (“test ONE”) print (name) print (name.upper() ) print (name.lower() ) print (name.title() ) print (name.replace(“one”, “FIVE”) ) #”one” is not a typo #Methods are similar to functions but can’t be called on their own. They must be called via a function (like print() ) using dot notation 12
13
I/O of strings String Concatenation (+)
Used to ‘join’ variables or variables with literals Practice the following: word1 = “Bat” word2 = “man” print (word1,word2) #comma puts a space in print (word1 + word2 #concatenation of 2 vars print (word1+” and Robin”) #concatenation of a var and literal 13
14
Numbers Operations BODMAS applies to Python Addition (+)
Subtraction (-) Multiplication (*) e.g. print (3*2) 6 Exponent (**) e.g. print (3**2) 9 Equality (==) Not the same as the assignment operator (=) print (1 == 2) False print (1 == 1) True Division (/, //, %) – see next slide
15
Numbers Operations Division (/): or ‘integer’ or ‘true’
x/y gives untruncated float result (field width 18 inc d.pt) when x or y is integer or float Floor (//): or ‘DIV’ gives a truncated integer (the ‘whole’ part – always rounded down, e.g 3 and 3.66 3 and 3.753) x//y gives integer result when x and y both integer x//y gives truncated float result when x or y is float Remainder: (%): or ‘modulo’ or ‘MOD’ gives remainder x%y gives integer when x and y both integer x%y gives truncated float when x or y is integer x%y gives untruncated float when both are float
16
Doing maths on strings gives an error
I/O on Integers All input defaults to a string Doing maths on strings gives an error #ask user to input their age age_Now = input ("Enter your age in years: ") 21 #add 10 to the input ageInTen = (age_Now + 10) print (ageInTen) Traceback (most recent call last): File "H:/My Documents/Teaching/Teaching /COMP101_ /COMP101_Support/age.py", line 3, in <module> ageInTen = age+10 TypeError: Can't convert 'int' object to str implicitly The input of “21” by the user is a STRING Because it’s a string, we can’t do maths on it – so we get an error when this line executes
17
I/ O on Integer - casting
How to change a string to an integer Doing maths on integers is okay #ask user to input their age age_Now = int(input ("Enter your age in years: ")) 21 #add 10 to the input ageInTen = (age_Now + 10) print (ageInTen) 31 This makes “21” into the number 21 Now 21 is a number (it’s an integer here) – it works! Output is 31 You don’t have to put brackets round the calculation, but it can help clarity
18
Doing maths on floats is okay
I/O on Float - casting How to change a string to a float Doing maths on floats is okay #ask user to input their age age_Now = float(input ("Enter your age in years: ")) 21 #add 10 to the input ageInTen = (age_Now + 10) print (ageInTen) 31.0 This makes “21” into the number 21.0 Now 21.0 is a number (it’s a float here) – it works! You don’t have to put brackets round the calculation, but it can help clarity
19
Constants Constants Python doesn’t handle constants
treats all declarations as variables can be changed! Some languages allow constant declaration CONST pi = 3.142; pi stays as for the duration of the program error is thrown on attempts to change it A Python ‘workaround’ is to capitalise the variable name – then remember not to change it!
20
Arithmetic Addition (+) and Subtraction (-) Sess1_Example-3.py
#addition: user input not shown for clarity num1 = int(input(“Enter first num: “)) num2 = float(input(“Enter next num: “)) answer = (num1+num2) print (“Sum =“,answer) #subtraction: user input not shown for clarity num1 = float(input (“Enter first num: “)) answer = (num1-num2) print (“Result =“,answer) Whenever a float is used, output will be a float Whenever a float is used, output will be a float
21
Arithmetic cont. Multiplication (*) and Exponent (**)
Sess1_Example-4.py #multiplication: user input not shown for clarity num1 = int(input (“Enter first num: “)) num2 = int(input(“Enter next num: “)) answer = (num1*num2) print (“Product =“,answer) #exponent: user input not shown for clarity num1 = int(input(“Enter first num: “)) result = (num1**num2) print (“Solution =“,result) If both integer, output is integer. If float used anywhere, output will be a float If both integer, output is integer. If float used anywhere, output will be a float
22
Arithmetic cont. True division (/), Floor division (//)
Sess1_Example-5.py #true division – answer always a float num1 = int(input(“Enter first num: “)) 10 num2 = int(input(“Enter next num: “) 3 result = (num1/num2) print (“Solution =“,result) Solution = #Floor division – answer is integer if both integer, else truncated float result = (num1//num2) Solution = 3 Field width = 18 inc d.pt
23
I/O Numbers Operations
Division Modulo (%) – outputs the remainder Sess1_Example-6.py #integer modulo c = 10 d = 3 print(c%d) 1 #float(decimal) modulo e = 7.5 f = 2.4 print(e%f) Can be used as test for divisibility: if x%y = 0 then x is divisible by y
24
Exercise-2_floatingBarge
Load: Sess1_Exercise-2_Barge_Question.py (Answer is in: Sess1_Exercise-2_Barge_Solution.py) Develop and implement a Python program which, given a barge defined in terms of inputs for length(L), breadth(B) and height(H), outputs the associated draft. Breadth(B) weight of iron = 1.06kg per square metre surface area = (2 * height) * (length + breadth) + (length * breadth) mass of barge = surface area of barge * weight of iron draft = mass of barge / (length*breadth)
25
Sess1_Example-7.py Import Modules (Classes)
Importing Modules Python comes with pre-built “modules” (classes). We can import these and call the functions that they contain. Functions are called using a dot operator. Sess1_Example-7.py Import Modules (Classes) #import the math module – all functions come with it import math num = int(input(“Enter a number: “)) 16 #use the sqrt function from within the math module answer = math.sqrt(num) print(answer) 4.0 print (math.pi) dot operator for module.function
26
Importing Modules cont.
Sess1_Example-8.py #import the math module – all functions come with it import math import time num = float(input(“Decimal number: “)) 16.2 print(math.floor(num)) 16 myTime = time.time() print (myTime)
27
Simulate throwing a single dice
Sess1_Example-9.py #Throw a single dice to output a random number within a given range (usually 1 to 6) #import ‘random’ module #use ‘randint’ function from within ‘random’ module import random #set the maximum number to be generated max_Number = 6 #randint function generates integers 1 and 6 inclusive dice_Throw = (random.randint(1,max_Number)) #output print (dice_Throw)
28
Sess1_Exercise-3_dice I/O and Import
Write a program to allow a single user to throw two dice, one after the other Add the total of the two dice and output this back to the user Hints: import random; don’t cheat and set the random range as 1-12! Answer is in: Sess1_Exercise-3_dice.py Pseudocode Initialise variables 1.1 var max = 6 1.2 total = 0 1.3 die_1, die_2 = 0 Input (from system) 2.1 die1=random(1,max) 2.2 die2=random(1,max) 3. total = die1 + die2 4. print total
29
string input - we did not use ‘int’ to convert it
Standard Functions Some functions are available as standard and do not need to be imported, e.g., len - returns the length of its string argument, does not work on integer input Example-10 len() nums = input("Enter some numbers: ") 74982 print(len(nums)) 5 course_Name = input("Enter course: ") Computing print(len(course_Name)) 9 string input - we did not use ‘int’ to convert it
30
Formatted Output - Integers {:value}.format(value)
.format function is used with print() to control output Sess1_Example-11_Formatting.py stud_Id = 123 #output number 123 as a signed integer(d) #in a field width of 5 spaces print (“Student number{:5d}”.format(stud_Id)) Student number 123 #Two spaces in front of number 123 as it takes up three of the 5 five spaces in the output format. If number was negative, the minus sign would take up another space of the field width
31
Formatted Output cont. Sess1_Example-12_Position.py
#students paying for a school trip #input student Id and amount paid sId = int(input(“Enter student id: “)) sPay = float(input(“Enter payment: “)) #pass arguments by position #sId is first in argument list so is passed to {:5d} #sPay is second in argument list so is passed to {:5.2f} print (“Id{:5d},has paid {:5.2f}”.format(sId,sPay))
32
Sess1_Exercise-4 Formatted Output
Amend Sess1_Exercise-2.py b) Inform the user what values they entered for L, B, H and tell them what the draft will be. Have a practice with some formatting for output, or just keep it simple Some suggested solutions are in: Sess1_Exercise-4_Solution.py
33
Sequence Summary Sequence operations run once
Users can input ANY data type other than the one prompted for – so we have to trust the user to enter a number if asked and hope they don’t enter a string etc Sensible prompts can help, and sometimes the output (especially numeric) may need to be formatted to be useful and understood
34
Appendix-01 Variables for input
Prompt for input needs a user-defined variable to hold the input. Variable names are case-sensitive and can be made up from: ‘A’ - ’Z’; ‘a’ - ’z’; _ ; 0-9 (e.g. longName_01) can’t start with a number and no spaces allowed usually maximum 15 characters long (not critical) Any name you choose but no reserved words
35
Appendix-02 Reserved Words
and, as , assert break class, continue def, del elif, else, except False, finally, for, from global if, import, in, is lambda none, nonlocal, not or pass raise, return True, try while, with yield
36
Appendix-03 Advanced String Handling
Within your program, you wish to prompt the user with the following message: Create a new directory called “C:\\names” Solutions – see over 36
37
Appendix-03 cont’d Advanced String Handling
Try the following solutions – escape char used print (‘ Create a new directory called “C:\names” ’) # \n within the nested quotes is the escape character for newline Create a new directory called "C: ames" print (“Create a new directory called ” C:\\names “) #\\ means escape the next character – so we output a single ‘\’ Create a new directory called "C:\names" 37
38
Appendix-03 cont’d Advanced String Handling
Try the following solutions – escape char used print (“Create a new directory called ” C:\\\names “) # the first ‘\’ escapes the second ‘\’ so we output a single ‘\’ # the third ‘\’ escapes character n so we get a newline Create a new directory called "C:\ ames" print (“Create a new directory called ” C:\\\\names “) # The first ‘\’ escapes the second ‘\’ so we output a single ‘\’. The third ‘\’ escapes the fourth ‘\’ so we output another single ‘\’ Create new a directory called "C:\\names" Got it!! 38
39
Appendix-03 cont’d Advanced String Handling
Try the following alternatives – no escape char needed e) print (‘ Create new directory called ” C:\\names “ ‘) # the use of single quotes around the entire string does not conflict with the double quotes within the substring Create a new directory called "C:\\names" f) print (‘’’ Create new directory called ” C:\\names “ ‘’’) #the use of triple quotes around the entire string does not conflict with the double quotes within the substring. Useful if single quotes are present in the string also 39
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.