An Introduction to Python for KS4!

Similar documents
Downloaded from Chapter 2. Functions

Expressions and Variables

Python Intro GIS Week 1. Jake K. Carr

Introduction to Computer Programming CSCI-UA 2. Review Midterm Exam 1

CSCE 110 Programming I Basics of Python: Variables, Expressions, Input/Output

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

CS 102 Lab 3 Fall 2012

Table of Contents EVALUATION COPY

Try typing the following in the Python shell and press return after each calculation. Write the answer the program displays next to the sums below.

VBScript: Math Functions

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python

CSCE 110 Programming I

Python review. 1 Python basics. References. CS 234 Naomi Nishimura

Getting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an . Michigan State University CSE 231, Fall 2013

A453 Task 1: Analysis: Problem: Solution:

What did we talk about last time? Examples switch statements

Chapter 1. Data types. Data types. In this chapter you will: learn about data types. learn about tuples, lists and dictionaries

CS 1110, LAB 2: FUNCTIONS AND ASSIGNMENTS

MICROPROCESSOR SYSTEMS INTRODUCTION TO PYTHON

roboturtle Documentation

Java for Python Programmers. Comparison of Python and Java Constructs Reading: L&C, App B

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

Python Programming Exercises 1

CONDITION CONTROLLED LOOPS. Introduction to Programming - Python

Chapter 3 : Computer Science. Class XI ( As per CBSE Board) Data Handling. Visit : python.mykvs.in for regular updates

Variable Manipulator Driver. Installation and Usage Guide. Revision: 1.0 Date: Monday, July 10, 2017 Authors: Alan Chow

Jython. secondary. memory

Introduction to Python

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

CSC Software I: Utilities and Internals. Programming in Python

egrapher Language Reference Manual

Variables, Functions and String Formatting

Python Games. Session 1 By Declan Fox

Programming Training. Main Points: - Python Statements - Problems with selections.

Python Unit

Python Input, output and variables

Getting Started. Excerpted from Hello World! Computer Programming for Kids and Other Beginners

Let's Look Back. We talked about how to create a form in HTML. Forms are one way to interact with users

Hello World! Computer Programming for Kids and Other Beginners. Chapter 1. by Warren Sande and Carter Sande. Copyright 2009 Manning Publications

Professor: Sana Odeh Lecture 3 Python 3.1 Variables, Primitive Data Types & arithmetic operators

If Statements, For Loops, Functions

Lesson 3: Basic Programming Concepts

Python Input, output and variables. Lecture 22 COMPSCI111/111G SS 2016

How To Think Like A Computer Scientist, chapter 3; chapter 6, sections

Math Day 2 Programming: How to make computers do math for you

ASCII Art. Introduction: Python

Introduction to Python (All the Basic Stuff)

ENGR 102 Engineering Lab I - Computation

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

Introduction to Computer Programming in Python Dr. William C. Bulko. Data Types

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration

C Functions. 5.2 Program Modules in C

MITOCW watch?v=0jljzrnhwoi

ECS Baruch Lab 5 Spring 2019 Name NetID (login, like , not your SUID)

And Parallelism. Parallelism in Prolog. OR Parallelism

Programming to Python

Using Classes. GEEN163 Introduction to Computer Programming

VARIABLES. Aim Understanding how computer programs store values, and how they are accessed and used in computer programs.

Introduction to Scientific Python, CME 193 Jan. 9, web.stanford.edu/~ermartin/teaching/cme193-winter15

Princess Nourah bint Abdulrahman University. Computer Sciences Department

Chapter 2 Input, Processing and Output. Hong Sun COSC 1436 Spring 2017 Jan 30, 2017

CHAPTER 3: CORE PROGRAMMING ELEMENTS

Introduction to Python

Introduction to C Language

Detailed guide for learning to program in Python 3

BB4W. KS3 Programming Workbook INTRODUCTION TO. BBC BASIC for Windows. Name: Class:

Introduction to Python, Cplex and Gurobi

Revision of Basics of Python

! Widely available. ! Widely used. ! Variety of automatic checks for mistakes in programs. ! Embraces full set of modern abstractions. Caveat.

Ch.2: Loops and lists

BASIC ELEMENTS OF A COMPUTER PROGRAM

Intro to Python & Programming. C-START Python PD Workshop

CSC Web Programming. Introduction to JavaScript

CSI31 Lecture 5. Topics: 3.1 Numeric Data Types 3.2 Using the Math Library 3.3 Accumulating Results: Factorial

CHAPTER 2: Introduction to Python COMPUTER PROGRAMMING SKILLS

Built-in Types of Data

Preview from Notesale.co.uk Page 3 of 79

Lesson #3. Variables, Operators, and Expressions. 3. Variables, Operators and Expressions - Copyright Denis Hamelin - Ryerson University

Exam 1 Format, Concepts, What you should be able to do, and Sample Problems

The Very Basics of the R Interpreter

Decisions, Decisions. Testing, testing C H A P T E R 7

The float type and more on variables FEB 6 TH 2012

Expressions. Eric McCreath

PIC 10A. Lecture 3: More About Variables, Arithmetic, Casting, Assignment

Long (or LONGMATH ) floating-point (or integer) variables (length up to 1 million, limited by machine memory, range: approx. ±10 1,000,000.

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

Shell / Python Tutorial. CS279 Autumn 2017 Rishi Bedi

A variable is a name for a location in memory A variable must be declared

There are two ways to use the python interpreter: interactive mode and script mode. (a) open a terminal shell (terminal emulator in Applications Menu)

Course Outline. Introduction to java

KS5-HE Transition Guide Checkpoint Task Instructions and answers for teachers

Programming Basics. Part 1, episode 1, chapter 1, passage 1

Python 2. KS3 Programming Workbook. Name. ICT Teacher Form. Taking you Parseltongue further. Created by D.Aldred P a g e 1

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG

SECTION 1: INTRODUCTION. ENGR 112 Introduction to Engineering Computing

The Big Python Guide

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

Computer Programming : C++

Lecture 4. Defining Functions

Transcription:

An Introduction to Python for KS4 Python is a modern, typed language - quick to create programs and easily scalable from small, simple programs to those as complex as GoogleApps. IDLE is the editor that comes free with Python. There are other text editors that will work, including Textastic for the ipad. When you start Python on the Mac you get the following window: Notice the warning about TkInter. The above installation had the latest 8.6.1 version of tcltk running. This can occur on some installs on Macs and can have issues with some graphical applications but, for applications up to GCSE level, it is not an issue. The next step to writing your python code is to launch the editor window. Click File>New File and a blank window will open. Print() and Input() Commands Type the following, using the print() command: print ( Hello Cornwall ) Now File>Save and call it Hello.py, saving to desktop. Next, click Run>Run Module and the following should happen. Note that the program runs in the shell window.

Now. Looking at the code we typed: print ( Hello Cornwall ) print Hello Cornwall In Python 2, this would have been written as: In both, you can see that outputted text must be enclosed within quotes. Note that smart quotes fail and so copying and pasting code from a word processor can cause errors. This is really common with students so one to watch out for. Taking the code to the next step, we want to ask the user for their name and then print out a welcome. Edit the code in the editor window to read: name = null name = input ( What is your name? ) print ( Hello,name,. Welcome to Cornwall ) Save the code as HelloName.py and run. You should see the following: Here we have introduced a text variable, name to store the input. Although it is not strictly necessary to declare it at the start, it is a good habit for the students to get into. \n - introduce a line break \t - insert a tab \\ - insert a backslash \ - insert a speech mark There are special characters that we can enter into text to improve flow and presentation.

It is possible to use single speech marks, and so avoid having to \ speech marks. This can be confusing for students, so I wouldn t recommend its introduction early on. print( Hello, he said. ) could be used to replace print( \ Hello\, he said. )

Maths Functions Python can be used like a calculator. This is a good opportunity to introduce integer and floating point variables at the same time. * Multiply If we add an extra line at the start of the program, we can also add more functions, such as trigonometry. import math This brings in a new module. Modules are extra Python commands that can be added and a lot are installed along with the standard Python files. Some useful ones are: math.e Inserts e These extra functions are extremely useful in the GCSE Controlled Assessments. Variables + Add % Modulus - Subtract ** Raise to the power / Divide // Divide (Integer Part) math.sin() Sine of an angle math.floor() Integer part of a decimal math.cos() Cosine of an angle math.sqrt() Square Root math.tan() Tangent of an angle math.pi Inserts Pi To use these functions, we need to be able to define variables. name = null Text String correct = set([ y, yes ]) Sets score = 1 Integer correct = ( y, yes ) Tuple (read-only list) g = 9.81441 Floating Point letters = [ a, b, c ] List Sets, Tuples and Lists have an Index, starting with 0, that can refer to elements in the values. For example: mylist = [ a, b, c ] print (mylist[1]) would print out b, as this is at the second position with index value of 1. A dice randomiser could be of the form: import random throws = ( 1, 2, 3, 4, 5, 6 ) choice = random.randint(1,6) print(throws[choice])

So a simple program involving other variable types might have a form: x = 0 y = 0 m = 0 c = 0 print( For a linear equation of y=mx+c, please enter m and c ) m = int(input( m: )) c = int(input( c: )) print( Now enter the value of x that you want to process ) x = int(input( x: )) y=(m*x)+c print( Y =,y) Note the introduction of the int() conversion. input() always returns a string. We want an integer here. Students often forget the second closing ) so one to watch out for. Try the above code for yourself. The nice thing is that this introduces variables, input, process and output. Now. The above is a little inefficient. It would be nice to calculate a range of y values for a series of x. We can modify the above code like this: x = 0 y = 0 m = 0 c = 0 print( For a linear equation of y=mx+c ) print( please enter m and c ) m = int(input( m: )) c = int(input( c: )) x = -5 while x < 6: y=(m*x)+c print( X:,x,,Y:,y) x+=1 print( Finished ) I have included the code from IDLE to show the handy way that it uses colour to show correct syntax. Note the tabbing for the while loop. This also introduces a condition x < 6 and a simple incremental addition to a variable x+=1. When we used BASIC, we might have written x=x+1 to add one to a counter. A final variable type is the Dictionary. These are another type of list but, this time, you supply the index value. For example: elements = {1: Hydrogen, 2: Helium, 3: Lithium, 4: Beryllium } The index value is called the Key and the item in quotes is called the Value.

Operators > Greater Than < Less Than >= Greater Than or Equal <= Less Than or Equal = Not Equal == Exactly Equal Note how we use a single equal sign to assign a value but a double equal sign to check equivalence. For example: a=1 b=1 while a == b: print ( Equal )

Comments If we use a # tag at the start of a line, the line is not compiled and so is a comment. We use these to annotate a program #define variables a=1 # Start a Loop while a = 0: print(a)

Modules As said earlier, modules bring extra commands. import math This module gives us extended mathematical functions import random math.sin() Sine of an angle math.floor() Integer part of a decimal math.cos() Cosine of an angle math.sqrt() Square Root math.tan() Tangent of an angle math.pi Inserts Pi math.e This module gives us a range of random items to use in other calculations random.randint(a,b) Inserts e Random integer between a and b random.choice(list) random.randrange(start, stop, step) Random string from a list Random number within a range random.random() Random decimal number between 0.0 and 1.0

Selection When we ask a user for an input, it is often useful to define the action, based on their response. For this we use IF statements in programming. In Python we have IF, ELIF and ELSE. For example answer1 = null answer1 = input ( What is your choice? y/n ) if answer1 == y : print( Yes ) else: print( No ) or goodchoices = set([ y, yes ]) answer1 = input ( What is your choice? y/n ) if answer1 in goodchoices: print( Good Choice ) else: print( Bad Choice ) words = ['cat', 'dog', mouse'] for w in words: print ( Word: w,,length:,len(w)) We can also use lists with another selection tool - FOR. Look at this example: This loop would cycle through the list, printing the length of the words in the list, using the len() command. The result would be: Word: cat, Length: 3 Word: dog, Length: 3 Word: mouse, Length: 5

Functions We can make programs more efficient by collecting parts of a program together and turning it into a function. Lets look at this program again: x = 0 y = 0 m = 0 c = 0 print( For a linear equation of y=mx+c ) print( please enter m and c ) m = int(input( m: )) c = int(input( c: )) x = -5 while x < 6: y=(m*x)+c print( X:,x,,Y:,y) x+=1 print( Finished ) x =0 y = [] m = 0 c = 0 counter = 0 #The Function def linear(m,c): counter = 0 x = -5 while counter < 11: y=(m*x)+c print( X:,x,,Y:,y) x+=1 counter+=1 #End of the function print( For a linear equation of y=mx+c ) print( please enter m and c ) m = int(input( m: )) c = int(input( c: )) linear(m,c) print( Finished ) Lets look at this program again. The def command defines the function here. The function is passed the two values of m and c using the function name - note that you cannot use the name of any built in command as a function name.

Menus A simple menu for a choice could use the techniques that we have seen up until now: level = input( Please enter your choice - a, b or c: ) while level = a and level = b and level = c : level = input( Sorry, your choice must be - a, b or c: ) This gives us some sort of validation checking on a menu option. Next we will see some further code examples, all of which have examples useful for GCSE coursework tasks.

Extra lists - adding and removing list elements mylist = ['Bob','Sue','Rita'] index = 0 myextra = 'Null' size = len(mylist) for index in range(0,size): print (index+1,':',mylist[index]) print ("Add names to the list") print ("Type Stop to stop") while myextra = 'Stop': myextra = input("add a name> ") mylist.append(myextra) mylist.remove('stop') index = 0 print ("Your new list of names is") size = len(mylist) for index in range(0,size): print (index+1,':',mylist[index]) import random Making random names. Useful for game characters. FirstNames = ['Bob','Sue','Rita','Sam','George','Degory','Thomasina'] LastNames = ['Smith','Jones','Roberts','Willa','Curnow','Mitchell'] WholeName = "" rounds = int(input("how many names would you like? ")) while rounds > 0: WholeName = random.choice (FirstNames) + " " + random.choice (LastNames) print (WholeName) rounds -= 1 print ( End") Countdown loop with Play Again choice launchagain = True counter = 10 validchoice = set(['y','y','yes','yes']) while launchagain == True: counter = 10 print ("Countdown>",counter) while counter >1: counter -= 1 print ("Countdown>",counter) print ("Launch") launchchoice = input("would you like to launch another rocket? (y/n)") launchagain = launchchoice in validchoice print ("Thanks for launching rockets. )

Random Captain Generator for Sports This code combines all of the elements that we have seen and is a useful demonstration for GCSE Coursework tasks. It also shows effective use of commenting. # Import any functions we need import random # Initialise our variables # Set the captain player number to 0 captain = 0 # Set the number of players to 0 players = 0 # Set the While loop value to True playagain = True # Define any functions we need # The function is called 'captainizer'. This is fed the number of players (players) when called def captainizer (players): # Create a random integer between 1 and the number of players. captain = random.randint(1,players) # Return the number of the captain using the variable name 'captain' return captain # Print a welcome message to the users print (""" Welcome Which sport would you like? 1 Football 2 Rugby 3 Double's Tennis """) # Begin the body of the programme. The While statement continues until False while playagain: # We are going to give users a choice of sports. This is in case people do not know how many should be on a team # This can be expanded easily with more sports. # Ask the user which sport they would like sportchoice = input ("Choose your sport, 1,2 or 3") # Sport Choice Sections # Check for sport and initialise variable with number of players, call the captainizer function and output the value to the screen # Whilst this code could be simplified, this method makes adding new sports very quick. # Choice 1 if sportchoice == "1": players = 11 captain = captainizer (players) print ("Out of ",players,", your Captain is player number ",captain) #Choice 2 elif sportchoice == "2": players = 15

captain = captainizer (players) print ("Out of ",players,", your Captain is player number ",captain) #Choice 3 elif sportchoice == "3": players = 2 captain = captainizer (players) print ("Out of ",players,", your Captain is player number ",captain) #Trap if no valid choice is made. else: print ("You didn't choose a valid sport") # Output the results to a file try: #Open a file with name "captain.txt" and place in append mode captainfile = open("captain.txt", "a") try: # Text String captainfile.write("your Captain is player number ") # Note that you cannot output numbers without turning them into a text string captainfile.write(str(captain)) #T ext String captainfile.write(" out of ") # Note that you cannot output numbers without turning them into a text string captainfile.write(str(players)) # Text String captainfile.write(" players") # Text String captainfile.write("\n") finally: # Close the file captainfile.close() except IOError: pass # Now we test for whether the user wants another go # Set the while look value to True, just to be sure. playagain = True # Ask the user if they want to play again playagain = input("do you want to choose another captain? (y/n)") # never assume they will do as they are told. Strip out all capitals and allow y and yes to be valid answers to play again playagain = playagain.strip().lower() in ('y','yes') # Now we say goodbye print ("Thank you for playing") quit