A Crash Course in Python – Introduction – Python as a



A Crash Course in Python – Introduction – Python as a

1 0


Python_Crash_Course


On Github MarcScott / Python_Crash_Course

A Crash Course in Python

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

Contents

Introduction Python calculator Data Types (1) Data Types (2) Data Types (3) Variables Reassigning variables (1) Reassigning variables (2) Strings Printing Input First Test Conditionals Second Test

PyConUK - Programmer Pythonical Song from Hawkz on Vimeo.

Introduction

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.

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

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.

Loading IDLE

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

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

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
						

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:

Operator Description Example + 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

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)

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)

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.

Using Floating point numbers

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

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)

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)
						

Other data types

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

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

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

Variables

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
						

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
						

Reassigning Variables (1)

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.

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

Here's a quick explanation

Did you predict correctly?

Reassigning variables (2)

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
						

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

"" 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"'
						

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

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)

Your first program

Follow along with the video

More Hello World!

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

Input

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
						

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.

Here's what to do.

Your first test.

Task

Create a program that will ask the user to enter two numbers The program should then calculate what percentage the second number is of the first. 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

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
						

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.

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')
						

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

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')