You are on page 1of 37

Mastering Programming in Python

Lesson 1
An introduction to Computer Science and Python 3

www.teachyourselfpython.com

100s of other resources are available from

www.teachingcomputing.com

In this lesson you will

First things first, BE INSPIRED! ..and get some perspective!

Learn about the language: Python


How to download Python 3 (and Pygame)
create your very own chat bot in Python!
learn about variables, sequence, programs, Alan Turing and Artificial
Intelligence
Big Ideas: DNA Coding and Intelligent Design
Challenge yourself to see if you can extend your code!
Random number and item generation
Suggested videos: History of Computing
Learn about mathematical and comparison operators
Learn about the importance of Indentation in Python

*For this series we


assume students
know how to open,
save and run a
python module.
Version: Python 3

Series Overview

Introduction to the language, SEQUENCE variables, create a Chat bot


SELECTION (if else statements)
ITERATION (While loops)
Introducing For Loops
Challenges and tasks for Mastering Iteration
Use of Functions/Modular Programming
Introducing Lists /Operations/List comprehension
Tuples, sets, lists, dictionaries
Use of Dictionaries
Doing things with strings
File Handling Reading, writing, appending text files
Working with CSV files
Practical Programming (plenty of engaging scenarios, challenges
and tasks to get you thinking) *Also how to approach a project
abstraction and decomposition (examples of design, create, test)
Consolidation of all your skills useful resources
Includes Computer Science theory and Exciting themes for every
lesson including: Quantum Computing, History of Computing,
Future of storage, Brain Processing, Systems life Cycle, Testing and more

Information/Theory/Discuss
Task (Code provided)
Challenge (DIY!)
Suggested Project/HW

*Please note that each lesson is not bound to a specific time (so it can be taken at your own pace)

First things first Be inspired!


Before you start you need to be inspired by the wonderful
world of Computer Science and know that learning how to
program is going to be an amazing journey!
You need to pay attention, persevere, and practice. Soon
youll be good enough to create your own apps, games
and who knows what else!
The potential in this field is HUGE! Technology and
software is crucial to our every day lives. You can help
people, solve problems in small or big ways, and yes there
is also a lot of money to be made!

A big percentage of the worlds millionaires and billionaires


were computer scientists.

So much to think about! What will the future look like?

INFORMATION IS POWER! .and learning how to code is going to give you power.
How will you use it? Be inspired and you will really enjoy TeachingYourselfPython!

Any ideas how these two pictures are connected?

?
John Von Neumann was an amazing man (left). He was a child prodigy and legend has it he made his secondary
school maths teacher weep at his sheer genius even at that young age! Here he is with one of the worlds first
computers it was called the MANIAC.

The Maniac and the Hydrogen bomb!

>
The Maniac was the computer that was used to perform the calculations that led to the creation of the atomic bomb.
The devastation that followed is something you would have read all about .
So . information is POWER but how we use that power is what is really important! Quantum Computing is
another emerging field that has great potential but also very great security risks. Well come to that in a later lesson.

Computer Science has also changed the world for good!


Computer Science has revolutionised the way the health
service works. Advances in all areas of medicine are
rapidly moving ahead thanks to clever software.

Sophisticated Computer Software helps keep us safe.


Heres a chap sitting at some air traffic control screens.
Millions of apps are used to help people. Think of the
simple bus finder app. A simple but wonderful creation!
Video conferencing for business or just skyping your
grandma communication has been hugely advanced
thanks to applications like SKYPE.

Dating sites and apps have helped millions find love


online! Without the internet they may have never found
each other!

In small and big ways, computer science is continually providing opportunities to do good, solve problems and
change the world. Every field imaginable is now reliant on Computer Science. Lots to think about! Once youre a
competent computer programmer, what will you use your skills to do?

Getting started for the absolute beginner


Skip this if you have already installed python

https://www.python.org/downloads/
We have downloaded Python 3.4.3

You can read more about the


difference between Python 2 and 3
on the site.

Getting started for the absolute beginner


Skip this if you have already installed python

Visit the following site to


download python. The version
we use in these tutorials is:
Python 3.4.3
Once youve followed the
instructions and have python
on your computer, create a
short cut on your desktop (if
possible).
Open the IDLE SHELL and
create a new file (module)
see screenshot on the right.

You are ready to start programming in python,


Remember to save all files with the ending.py

Did you know?

Guido van Rossum, the creator of


Python

Guido van Rossum, the guy on the right, created python!


He is a Dutch computer programmer and completed his
degree in the university of Amsterdam
He was employed by Google from 2005 until December
2012, where much of his time was spent developing the
Python language. In 2013, Van Rossum started working
for Dropbox.
Python is intended to be a highly readable language. It
has a relatively uncluttered visual layout, frequently using
English keywords where other languages use punctuation.
An important goal of the Python developers is making Python fun to use. This is
reflected in the origin of the name which comes from Monty Python

Want to create your own games?


You may also want to download Pygame. Pygame is basically a library of commands
that will help writing games be much easier.
Run the Python installer downloaded
from:
ProgramArcadeGames.com/python3.4.3.msi
http://programarcadegames.com/python
-3.4.3.msi
Run the Pygame installer downloaded
from:
http://programarcadegames.com/pygam
e-1.9.2a0.win32-py3.4.msi

What is a program anyway?


The very simplest definition is that: a program is just a
sequence of instructions.
Many algorithms (in our brain) are
inbuilt
We eat, drink, speak, respond and
appear to have been preprogrammed to do so. There is Free
will too, but thats a more
philosophical discussion.
DEFINITION: Algorithm = sequence of

Each of your cells contains what


we call the DNA CODE.

Interesting facts about DNA Code


The DNA code in your cells is like a library of instructions. It is
probably the most complex code we have ever come across. Is
a programmer behind it?
The letters of the genetic alphabet
A, T, G, and C are meaningless on
their own, but they are combined
into useful instructions in genes.

The anatomy of a typical program


Think about your very own brain: We dont often realize it but
our brains are pretty awesome. The brain is storing values and
processing data (as well as producing outputs) all the time.
Ever wondered how a lump of flesh (your brain) stores data?!
You can think of any program or
system as being comprised of these
three parts:
INPUT PROCESSING - OUTPUT
Inputs need to be stored, and thats
what we are looking at in this first
lesson. In Computing, we need

Consider the following example:


By simply looking at the screen, your brain has now STORED these
two values.

1
5

Number 1

4
7

Number 2

But how do we get a programming language to remember


values?
The key word you need to remember is VARIABLE (or identifier)

A useful analogy
Variables are like storage boxes that can hold or store values in
them.

47

Variable Name:

NumberToStore

Joe

FirstName

In programming, we need to DECLARE Variables, also called


Identifiers
Numbertostore = 47

Task 1: Creating a Chat Bot using variables


1. Open a Python
Module
2. Copy and paste the
code on the right into
the module >>
3. Run the program to
see what it does
4. See if you can add
additional variables to
make it do more!

Copy and paste the code below


#This is a chatbot and this is a comment, not executed by the program
#Extend it to make the computer ask for your favourite movie and respond
accordingly!
print('Hello this is your computer...what is your favourite number?')
#Declaring our first variable below called 'computerfavnumber' and storing
the value 33
computerfavnumber=33
#We now declare a variable but set the variable to hold whatever the *user*
inputs into the program
favnumber=input()
print(favnumber + '...is a very nice number indeed. So...what is your name?')
name=input()
print('what a lovely name: ' + name + '...now, I will reveal what my favourite
number is:')
print (computerfavnumber)

Online chat bots you can check out!


http://www.mitsuku.com/ http://chatwithigod.com/

Try chatting with these bots. Can you tell you are not talking to a
real person. How do you know? How could the program be

Artificial Intelligence and the Turing Test


The Turing test is a test, developed by Alan Turing in
1950, of a machine's ability to exhibit intelligent behaviour
equivalent to, or indistinguishable from, that of a human.
If you were chatting with a
computer would you be able to tell
the difference between it and a
real human being?
How?
What makes us different?
Will computers ever truly think?

A picture of the young Alan


Turing

Recent Developments in AI
You may find Wikipedias timeline of AI interesting reading (see link
below)
https://en.wikipedia.org/wiki/Timeline_of_artificial_intelli
Googles artificial
gence
intelligence (AI)
software has been
developed to the
point that it is ready
to go head to head
with the worlds
highest ranked GO
This is seen
as a pivotal moment for AI, similar to IBMs DEEP BLUE
player.
beating Gary Kasparov at chess!

Random Generation of stuff in Python


Random numbers are used A LOT in Computer science. Especially in gaming!
There is no such thing as
a truly random
number ...or thats what
experts say any way. But
Python allows you to
generate random stuff by
importing a code library
that does this for you!

OM
RAND
T
OUTPU

*see if you can incorporate something random into your Chabot

The examples above generate random numbers and random items from a list.

Challenge: Extend the code and get


someone to try out your program!
Some suggestions but get
creative with your own
ideas!
1. Get the computer to ask the
user what his/her favourite
movie is and then respond
2. Declare a few other integer
variables and carry out an
addition!
3. Ask the user to think of a
colour in their head. Get the
computer to randomly
generate a colour from a
list.
4. What else will you do!?

Copy and paste the code below


#This is a chatbot and this is a comment, not executed by the program
#Extend it to make the computer ask for your favourite movie and respond
accordingly!
print('Hello this is your computer...what is your favourite number?')
#Declaring our first variable below called 'computerfavnumber' and storing
the value 33
computerfavnumber=33
#We now declare a variable but set the variable to hold whatever the *user*
inputs into the program
favnumber=input()
print(favnumber + '...is a very nice number indeed. So...what is your name?')
name=input()
print('what a lovely name: ' + name + '...now, I will reveal what my favourite
number is:')
print (computerfavnumber)

More on data types/variables in Python


Python has five standard data types (that can be
declared)

Python has four standard data


types (that can be declared)

NUMBERS
STRING
LIST
TUPLE
DICTIONARY

INT (signed integers)


LONG (long integers also
represented in hex or octal)
FLOAT (floating point real
numbers)
COMPLEX (complex numbers)

In this lesson you can primarily focus on declaring


numbers and strings.
Counter = 100 An integer assignment
Pounds = 124.5 A floating point
Name = Joe Bloggs A string

Here are some examples of


numbers
Int
10

long
51924361

float
0.0

complex
3.14

Things you can do with strings.


Watch this demo video

It is helpful to know some of the handy things


you can do with Strings. Just google Python 3
documentation and check out the official
tutorial. In a nutshell however, you can:

Print strings to new lines


concatenate strings (stick them together!)
access individual characters in strings
Slicing: obtaining substrings from strings
Finding
the length of a string
https://docs.python.org/3.4/tutorial/introduction.html
#strings

Go to https://docs.python.org/3.4/tutorial/introduction.html#strings to try more examples yourself!

List of common mathematical operators


Can you fill in the
blanks?
Operat
or

Operatio
n
?
?
?
?
?
?
?

Example
s

Code

List of common comparison operators


Can you fill in the
blanks?
Operat
or

Meaning
?
?
?
?
?
?

Increment Operators
Incrementing is something that we will be using a lot as seen below
you can also shorthand the code:
Operator

Shorthand

Predict the
output
?

Defining input correctly whats wrong?


The following code which asks you how many weeks pregnant you are, and
calculates how many months that translates into, doesnt work. Any idea why?

Defining input correctly the solution!


We need to tell the computer that we are working with numbers. You can do that by
specifying that the input is either a FLOAT float() or a plain old INTEGER int()

In Python, INDENTATION matters!


In Python you can have blocks of code grouped together. You know when one block
begins and ends by checking out the indentation of the lines of code.
There are some simple rules for blocks (indentation)
1. When the indentation increases this indicates the BEGINNING of a block
2. Blocks can contain other blocks!
3. When the indentation decreases to a zero, blocks end!
Note the examples below:
if password == moose:
print("If password is moose, this will
print.")
print(This will print too")
print("And this.")
print(this will confuse the
computer)

Block 1 = Line
4
Block 2 = Line
Block 36 = Line
8

Useful Videos to watch on covered topics


Exploring Artificial Intelligence today

https://youtu.be/poLZqn2_dv4

Recommended video on Python Variables

https://youtu.be/667ZeuZ0Q8M

An entertaining history of Computing


Triumph of the Nerds Part 1/2/3
Triumph of the Nerds Part 1
Triumph of the Nerds Part 2
Triumph of the Nerds Part 3

Important Note on Software Development


Every time you code a solution, its good practice to get in the
habit of DESIGNING, CODING, TESTING
You wouldnt just start coding a massive software system for
the government without designing it (planning) firstand you
wouldnt ever pass on something you had coded without
testing it!

DESIGN
CODE

So remember, when you are given a challenge.


DESIGN (this could include flow charts or pseudocode)
CODE (this is the actual coding and implementation)
TEST (white box and black box) Prove the solution works!

TEST

An Example

DESIGN

TEST

CODE

DESIGN (this could include flow charts or pseudocode)

Example Test Table


Name of
Test

Test Data

Expected
Output

Actual
Output

Testing for
correct
name input

John

Validated

Validated
Test was
successful

Testing for
numeric
input
validation

Only
Numbers
allowed

J was
accepted.
Test
FAILED

CODE (this is the actual coding and implementation)

TEST (white box and black box) Prove the solution works!

What next? Be inspired to learn!


The field of Computing and Computer Science is at the
forefront of everything that is happening today.
Just think about it where would we be without
computers and software?
And whats more, things are moving FAST! The advances
in technology are stunning. And the capacity to make
money, innovate and most of all help people, is HUGE!
As you follow along in this series, youll be introduced to a
number of exciting concepts that will hopefully inspire
you. Were also going to start programming in earnest.
Get ready for a very exciting journey! Itll be worth it.

YOU can start here! By


learning how to
program! And reading
around the subject and
taking an interest in past,
current and future
developments

Suggested Project / HW / Research


Create a research information point on Alan Turing.
Basic facts about him
Achievements
Turing Test
His involvement in code breaking at Bletchley park
*You may also want to watch some CS related movies!
High level languages use variables as memory locations but how does a
computer, at its very lowest level (Binary 1s and 0s) store information? Write a
short essay, based on your research, to explain how computers store
Numbers
Text
Images
Sound/Video

Useful links and additional reading


http://www.python-course.eu/variables.php
http://www.programiz.com/python-programming/variables-datatypes
http://www.tutorialspoint.com/python/python_variable_types.htm
https://en.wikibooks.org/wiki/Python_Programming/Variables_and_Strings

You might also like