Anda di halaman 1dari 11

Welcome!

Introduction to
Programming

On this course, you will


Learn the principles of how to solve small problems by
writing computer programs

Day 1: Fundamentals
Nick Efford
Twitter: @python33r
Email: N.D.Efford@leeds.ac.uk
G+: http://plus.google.com/+NickEfford

Course Structure

Gain some experience of using a powerful modern


programming language: Python

You will not


Become expert programmers

Learn enough to write very large, complex programs

Learn much about Pythons advanced features

Todays Objectives

Mornings:
Me showing you things
...and you asking questions (hopefully)
Short quizzes and small programming exercises
Short break for coffee, etc

To explore what programs are and what programming a


computer actually means

To consider the idea that programs accept input, process


the input data in some way and generate output

To see how Python programs are created and executed

Afternoons:
Mainly you, doing more extended exercises
Some presentation from me if needed

To learn how Python supports data input, data


representation, numeric calculations and output
generation

Course materials: http://bit.ly/skillsprog

Reading Material

Reading Material

Practical Programming (2nd Ed.)


Gries, Campbell & Montojo
Pragmatic Bookshelf, 2013
http://bit.ly/pracprog

http://bit.ly/interactpython

Getting Python On Your PC

Writing Code

Important: we use Python 3 on this course!


(not the older Python 2)

Anaconda includes a powerful integrated development


environment (IDE) called Spyder

Current version (3.4) is available as a basic distribution


from http://www.python.org

Or you can use a programmers text editor:

You will probably find it more useful to install a more


fully-featured distribution, such as Anaconda
http://repo.continuum.io/anaconda3
(See http://docs.continuum.io/anaconda/install.html for
installation instructions)

Sublime Text 3
http://www.sublimetext.com/3

Notepad++ (Windows only)


http://notepad-plus-plus.org

Many others are available (Vim, Emacs, etc)

Computer Programs

Exercise 1

Giving directions to your house


Recipe for a meal

How would you define a computer program?

Translation Tools

Computer CPUs are primitive devices that process very


simple instructions, so we need to translate our programs
into this low-level form

Interpreters translate program instructions one at a time,


executing the resulting sets of CPU instructions

Compilers translate entire programs, storing the CPU


instructions in a file for later execution

Programming Languages
Human language is far too complex, vague and
imprecise to be translated easily or reliably into
CPU instructions...
...so we need an intermediate representation:
this is what a programming language is

Hello World! in C
#include <stdio.h>
int main(void)
{
printf("Hello World!");
return 0;
}

Hello World! in Pascal

Hello World! in Java


class Hello
{
public static void main(String[] args)
{
System.out.println("Hello World!");
}
}

Hello World! in
Intel Assembly Language

program Hello(output);

section .data

begin
writeln('Hello World!')
end.

msg:
len:

db "Hello World!",0xa
equ $-msg

section .text
global main
main:
mov
mov
mov
mov
int

edx,len
ecx,msg
ebx,1
eax,4
0x80

;
;
;
;
;

length of string
pointer to string
file descriptor (stdout)
system call number (sys_write)
interrupt for system calls

mov
mov
int

ebx,0
eax,1
0x80

; exit code, 0=normal


; system call number (sys_exit)

Hello World! in Python

Exercises 2 & 3

print("Hello World!")

How do we run Python code?


How do we create Python programs?

So why use Python?


Easier/quicker to learn than many other languages
Easier/quicker to turn ideas into working code
Programs tend to be concise, clear and readable
You can do real work with it

hello.py: Analysis

Exercise 4

Program has a single statement

Statement is a function call, calling the print function

The thing we want to print is passed to the function by


including it in the brackets

The thing we are printing is a string of text; strings are


sequences of characters enclosed in quotes (' or ")

How can we handle input from the keyboard?


How does a program remember data that we input?

hello2.py: Analysis

A General Pattern for Programs

everything from # onwards is a


comment, ignored by Python
need to give a
name to users
input so that
we can refer to
it later

1.

Acquire some input

2.

Give names to the inputted values so that we can use them


subsequently in the program

3.

Do some processing of those values

4.

Generate some output

# Program to issue a personalised greeting


person = input("Who are you? ")
print("Hello", person)

can pass multiple items to


print function if they are
separated with commas

input function reads line of


text from keyboard, using
given text as a prompt

input doesnt have to be the


keyboard, output doesnt
have to be printed text!

value associated with


person will be printed,
not the word person!

Giving Names to Values:


Python Variables

A Different Approach:
Variables in C & C++

a = 1

assignment attaches a
name tag to a value

int a = 1;

a variable is like a box;


assigning a value to it puts
that value into the box

a = 2

reassignment moves
tag to a new value
(old value disappears)

a = 2;

reassignment replaces box


contents with new value

b = a

copying to a new variable


attaches another tag to the
value rather than actually
creating a copy of it

int b = a;

copying variable creates a


new box, containing a copy
of the value

Some of Pythons Built-in Data Types

str (string) to represent text

int to represent whole numbers

float to represent numbers with a fractional part

complex to represent complex numbers

bool to represent Boolean values (True or False)

String Representations
'Hello World!'
"Hello World!"

single or double quote allowed


as a delimiter - handy for text
containing apostrophes

"I don't know much Python yet."

"""This is the first line.


This is the second line.
This is the third line."""

triple quotes (' or ")


allow you to create
multi-line strings

Quiz

Integers

Which of these are OK? Which are not, and why?

Represented by the int type, with an unlimited range


(unlike the int of many other languages)

1: ""
Examples:
2: "Goodbye, Cruel World...'
3: 'I don't know much Python yet.'

45
-2
14327830152

decimal (base 10)

0b101101

0b prefix signifies binary (base 2)

4: '"Hello everybody!" said Nick.'

0x2d
0x signifies hexadecimal (base 16)

Floating Point Numbers

Type Conversions

Represented by float type, with limited range & accuracy

int(9.7)

Examples:

float(9)

9.0

int('42')

42

str(42)

42

bool(42)

True

bool(0)

False

44.99
-2.0

notation for 1.572 10-6


(e or E can be used)

1.527e-6
3e14

bool('xyx') True
notation for 3.0 1014
(no decimal point but still a float)

bool('')

False

note: no rounding!
(use round for that)

non-zero values
convert to True

non-empty strings
convert to True

What do you think happens for int('xyz') ?

Arithmetic Operators

Arithmetic Expressions

**

exponentiation (raising to a power)

Values can be combined with operators (and brackets) to form


expressions that Python can evaluate

*
/
//
%

multiplication
division (yielding float result)
division (yielding int result)
remainder

Examples:

+
-

addition
subtraction

Three levels of
precedence here;
** higher than /,
/ higher than +, etc

7**2
2*37.5 + 12
2*(37.5 + 12)
7 / 2
7 // 2
7 % 2

Can you predict the resulting


value and type for each of
these expressions?
Test your predictions
in the Python shell

Arithmetic Expressions

Input of Numbers

Python doesnt care whether you use literal numeric values or


variables representing numeric values...

input function returns a string of text

If we are expecting numeric input, we have to convert that


string into the appropriate numeric type:

Examples:
x = 7
y = 2
print(x**y)

age = int(input("How old are you? "))


distance = float(input("Enter distance: "))

Try entering this code


in the Python shell

total = 1 + 4 + 2
average = total / 3
print(average)

Try entering these lines in


the Python shell, then try
printing the variables

Putting It All Together

Writing The Program

How would you write a program to compute the gravitational


attraction between two user-specified point masses, a userspecified distance apart, according to Newtons law?

1.

Write a comment block (lines beginning with #), giving


purpose of program, author, date

2.

Visualise the steps involved in solving the problem and


write a comment for each of them

3.

Underneath the comment for each step, write a piece of


code that performs the step and test it

Tip 1: use the Python shell


to try out bits of code
Tip 2: take small steps

Using Functions From Modules

Pythons core is quite small; we can access additional


functionality by importing code from a module

Standard Python includes a large number of useful


modules; see http://docs.python.org/3/library/ for more
information on them

A simple example is the math module...

Extra Functionality

Some features are not available in Pythons core or its


standard library of modules, but are provided instead by
third-party modules or packages

Anaconda includes a large number of these, and you will


learn about a few of them on this course

For now, lets consider a simple example: using the PyQt


package to build a very simple graphical user interface
based around dialog boxes...

Exercises 5 & 6

Calling functions from the math module


Writing a program to compute square roots

Hello World! in PyQt

# "Hello World!" using PyQt


import sys
from PyQt4.QtGui import QApplication, QMessageBox
app = QApplication(sys.argv)
QMessageBox.information(None, "Greetings", "Hello World!")
reference to parent
window (non-existent)

title for
dialog box

text of
message

Using PyQt For Input

Use the QInputDialog class


getText method reads a string of text
getInteger & getDouble read numeric values
age, ok = QInputDialog.getInteger(
None, "Age Determination", "Enter your age", min=1)

Summary
We have
Discussed what programming is and seen examples of
different programming languages

Looked at how Python programs can be created and run

Examined the fundamental data types of Python

Explored the idea of giving names to values

Investigated different ways of getting data into and out of


Python programs

Anda mungkin juga menyukai