Fork me on GitHub Home

A Crash Course in Python

Created by Marc Scott / @coding2learn using reveal.js
Creative Commons License
A Crash Course in Python by Marc Scott is licensed under a Creative Commons Attribution 3.0 Unported License.

Contents

  1. Introduction
  2. Python calculator
  3. Data Types (1)
  4. Data Types (2)
  5. Data Types (3)
  6. Variables
  7. Reassigning variables (1)
  8. Reassigning variables (2)
  9. Strings
  10. Printing
  11. Input
  12. First Test
  13. Conditionals
  14. Second Test

PyConUK - Programmer Pythonical Song from Hawkz on Vimeo.

Introduction

Down arrow

What is Python?

Python is a programming language.

A programming language is a language designed to communicate instructions to a computer. Programming languages can be used to create programs that control the behavior of a computer.

Down arrow

It's just text.

Like most programming languages, you can write Python programs using any text editor.

You just need to make sure that you save your files with the extension .py


Down arrow

IDLE

We're going to use an IDE to write our Python programs.

IDE stands for Interactive Development Environment.

An IDE makes coding easier as it can recognise the language you are using and provide hints.

The IDE we'll use is called IDLE. It's a very simple IDE designed to code Python in.

Down arrow

Loading IDLE

Find IDLE on your computer and start it up. You should see something like this.


Down arrow

The Interpreter.

What you are looking at is a Python interpreter. An interpreter lets us write lines of code that are instantly run.

Not all programming languages can be used like this. Some languages require compiling first (where they are translated into a machine language first.). The advantages of an interpreted language is that you can quickly see what your code does. The disadvantage is that your programs will run a slower.

Python as a

calculator

Down arrow

Operators

Python can be used to perform calculations using operators.

Operators are just a word for things like + and -.

We call the the things we're using operators on (in this case numbers) operands.

Try typing the following in the interpreter.


6 + 3
6 - 3
6 * 3
6 / 3
						
Down arrow

Arithmetic operators

Here's a table of the operators that we can use to do some basic maths. For instance if a = 10 and b = 20 then:

OperatorDescriptionExample
+Addition - Adds values on either side of the operator a + b will give 30
-Subtraction - Subtracts right hand operand from left hand operand a - b will give -10
*Multiplication - Multiplies values on either side of the operator a * b will give 200
/Division - Divides left hand operand by right hand operand b / a will give 2
%Modulus - Divides left hand operand by right hand operand and returns remainder b % a will give 0
**Power calculation a**b will give 10 to the power 20
Down arrow

Playing with operators.

Have a play around with operands and operators using the interpreter.

See if you can find a calculation that gives an answer that is plainly wrong.

Data Types (1)

Down arrow

Integers

Integers are whole numbers like 1, 5, 1000, -7.

In some other languages if you perform a calculation on an integer, you always get an integer back.

This doesn't happen with normal division in Python 3, but we can use a special operator to make it happen.


5//2
2//5
10//3
						

The // operator performs an integer division. This can be very useful, and you'll find out why on the next slides.

Data Types (2)

Down arrow

Floating point numbers

Floating point numbers are representations of real numbers like 2.5, 3.7 or 1.0

The representation part is important. Computers (for reasons you'll learn later) struggle with real numbers, so sometimes they are inaccurate.

Down arrow

Using Floating point numbers

When we calculate 5 / 2 the answer is a floating point number (from here on in a float)

Down arrow

The problem with Floats

Floats aren't always accurate. This might seem strange as you'd have thought computers would be precise, but because computers work using binary numbers (1s or 0s), they can't use real numbers precisely. Try the example below in the interpreter.


0.1 + 0.2
						

This is why we should try and limit our use of floats. One way of limiting the use of floats is to use integer division with the // operator.

Data Types (3)

Down arrow

You can always find out what data type you have, by using the type() function.

Try this in your interpreter:


type(5)
type(0.5)
						
Down arrow

Other data types

Use the type function to find out the data types for the following:

  1. "Hello world"
  2. True
  3. False
  4. (1,2,3)

Don't worry too much about these yet, we'll cover them in detail later.

Variables

Down arrow

You may have seen variables before in Scratch.

A variable is a way of storing data.

Try typing the following into you interpreter and hitting enter each time.


a = 6
a
a + a
a - a
						
Down arrow

So what are variables.

Try typing the following into your interpreter, then watch the video on the next slide to understand what you've done.


a = 6
a
b = 3
b
c = a
c
						
Down arrow

Down arrow

Reassigning Variables (1)

Down arrow

We can reassign variables quite easily in Python.

Say we had written the following line of code.


a = 10
						

The we wanted to change a so it represented a different value.

We could then write this:


a = 20
						

Try it out.

Down arrow

Watch the video below and try to predict what will happen.


Down arrow

Here's a quick explanation


Down arrow

Did you predict correctly?


Down arrow

Reassigning variables (2)

Down arrow

We can reassign a variable by
referencing itself.

Try typing the following lines of code into the interpreter.


a = 100
a
a = a + 100
a
						
Down arrow

Typing a = a + 100 each time is a bit time consuming. We can type this instead:


a += 100
						

This is easier, but either way is acceptable.

Strings

Down arrow

"" or ''

Strings are just characters.

We surround strings in "" or ''. So "cat" is a string as is 'dog' While 6 is an integer "6" is a string.

We can either "" or '' to surround a string.

Here's a couple of examples of when "and ' can be useful.


"I'm a student"
'She said "I like this"'
						
Down arrow

Adding Strings

Try typing the following into your interpreter:


6 + 4
'6' + '4'
'6' + 4
						

When you add strings you concatenate them. This is a fancy word for join them.

You'll have noticed (I hope) that when you try and add a string to an integer, you get an error.

Try this:


'hello' + 'world!'
'hello ' + 'world!'
						

Printing

Down arrow

Creating Scripts

In the interpreter, IDLE will feedback whatever we have just entered.

If we type "Hello World!" then the interpreter will spit it out right back at us.

However, if we want to write some code and keep it, we're going top need to create and save a script.

To create an empty file, just go to File and New Window

Let's save it straight away as HelloWorld.py (DON"T FORGET THE .py)

Down arrow

Your first program

Follow along with the video


Down arrow

More Hello World!

Have a go at coding more Hello World! programs as you follow along with the video below.

Input

Down arrow

input

We can use the input function to let the user interact with the program. input lets the user of the program type in strings.

Try creating a new program (New Window) and saving it as giveMeALetter.py

Then type out these lines of code and run your program.


my_char = input("Please type any letter ")
print 'Thanks for the', my_char
						
Down arrow

Now try the following.

An adding machine

We want to make an adding machine, where the user gets to type in two numbers and the program adds them together and displays the result.

Down arrow

Here's what to do.

Your first test.

Down arrow

Task

  1. Create a program that will ask the user to enter two numbers
  2. The program should then calculate what percentage the second number is of the first.
  3. The percentage should be printed out.

Example output from the interpreter is provided below.


>>> 
Give me a number: 200
Give me another: 20
20 is 10% of 200
>>>
						

Once you've done, get your teacher to check your code.

Conditionals

Down arrow

if, else and elif

So far our programs have been pretty linear. Conditionals allow the program to run different bits of code, depending on whether certain conditions have been met.

We use if, elif (short for else-if) and else for conditionals.

An everyday example might be the following.


Look outside
if it is sunny
    pick up sunglasses
else
    pick up umbrella
						
Down arrow

Equality

Before we tackle conditionals, you need to understand the difference between assignment and equality.

In Python, if we write:


foo = 6
						

we are assigning the value 6 to the variable foo

If we write:


foo == 10
						

We are checking if foo is equal to 10 or not.

Watch the video on the next slide and code along with it.

Down arrow

Down arrow

Using equality testing in conditionals

Have a look at the code below. Try it out in a new file called something like password_checker.py


password = 'correct horse battery staple'
pass_attempt = raw_input('What is the password? ')
if pass_attempt == password:
    print ('Correct. Access granted')
else:
    print ('Access Denied')
						
Down arrow

Down arrow

Syntax of Conditionals

The general syntax of conditionals goes like this:


if something == somethingelse:
    do this
elif something == somethingdifferent:
    do this
else:
    do this
					

Notice the : at the end of the conditional line.

Also notice the indentation on the following lines. This indentation is important.

Your Second Test

Down arrow

The Task

Create a computing quiz that asks the user 10 questions and keeps a score of how many they got correct.

The score should be printed out at the end.

Get your teacher to check your program when you have finished.

The first part of the quiz has been done for you.


score = 0
answer1 = raw_input('What is the name of the IDE we are using for Python? ')
if answer1 == 'IDLE':
    print ('Well done')
    score += 1
elif answer1 == 'idle':
    print ('Well done')
    score += 1
else:
    print ('Sorry, that was incorrect')