• No results found

Computers. An Introduction to Programming with Python. Programming Languages. Programs and Programming. CCHSG Visit June Dr.-Ing.

N/A
N/A
Protected

Academic year: 2021

Share "Computers. An Introduction to Programming with Python. Programming Languages. Programs and Programming. CCHSG Visit June Dr.-Ing."

Copied!
8
0
0

Loading.... (view fulltext now)

Full text

(1)

An Introduction to Programming with Python

CCHSG Visit June 2014

Dr.-Ing. Norbert Völker

Computers

 Many “computing devices” are embedded

 Can you think of computers/ computing devices you may have in your home? Or which are used in shops?

Programs and Programming

 Programs determine what computers do.

“Software”

 Written by programmers, then “compiled” and “run” on the computer

 Airbus A380 avionics: more than 100 million lines of code

 Can you think of some programs running on a computer or a mobile phone?

Programming Languages

 There are (unfortunately) lots of them

Basic, C, C++, C#, Cobol, Java, JavaScript, Python, SQL, …

 But luckily most of them share certain basic constructs/

concepts

These are like the ABC of programming

 In our mini-course, we will use Python 3

It is a reasonably beginner-friendly language

(2)

Five Fundamental Programming Concepts

1) Simple values and operators: numbers, booleans and strings 2) Variables and assignments

3) Control flow: conditional statements and loops 4) Lists

5) Functions

1. Simple Values and Operators:

Numbers, Booleans and Strings

Numbers and Arithmetic Operators

 Integer numbers int

42, 0, -301, …

 Floating point numbers: float

7.92, 0.0, -12.0, 9e6

 Four arithmetic operations: +, -, *, /

 We can use the Python interpreter as a fancy calculator (1 + 2.3)*4

 Special operators: // ("floor" division that yields an integer) and % (modulo operator yields the remainder of division)

5 / 3 5 // 3 5 % 3

Booleans and Comparison Operators

 Two logical truth values: True, False

Called “booleans”

 They come up frequently as the result of comparison operators (<, <=, ==, !=, >=, >):

3 < 5 4 == 3.1 -1 != 77

 Boolean expressions can be combined using logical operators

not, and, or

 What is the value of the following boolean expressions?

(1 < -1) or not True or (2 == 0) ((1 > -1) and False) or (2 != 0)

(3)

Strings

 A string is a sequence of characters ("text")

 String literals are enclosed either in matching single or double quote symbols:

'Hi!'

"Always look at the bright side"

"12"

 They can be concatenated using the + -operator

"Hello " + "Linda!"

 Some general sequence operations that also work on strings:

s[i] ith item of s, origin 0 s[i:j] slice of s from i to j len(s) length of s

2. Variables and Assignments

And print() Function

Variables and Assignments

 Non-trivial programs consist of a number of steps

How can we remember interim results?

 A variable has a name and it can be assigned a value x = 42

y = x - 21.5

greeting = "Hello Linda!"

isEmpty = len(greeting) == 0

 You can think of a variable as storing a value for later use

 A variable can be reassigned a new value x = x + 1

 Such a re-assignment does not change the values of other variables

Breaking Down Arithmetic Calculations

 Calculations can be simplified by breaking them down into a sequence of assignments.

 Example (derived from a 1968 O-Level Maths question)

A small factory makes 2700 golf balls each week

The raw material for each ball costs £1.35

Other expenses amount to £2850 per week

The balls are sold to a retailer at £2.50 each

 Calculate the weekly profit

 How would you calculate this in an exam?

(4)

Profit Calculation in Python

production = 2700 costPerItem = 1.35 fixedCost = 2850 salesPrice = 2.50

profit = production * (salesPrice - costPerItem) - fixedCost

 How does this Python solution compare to solving the question on paper or on a calculator?

print() Function

 When we run Python programs from a file, there is no output in the console by default.

 We can invoke the print() function in order to display informative messages.

 Examples:

print("Hello Linda!")

print("Profit per week:", profit)

 Each print() invocation starts a new line, and its output is normally all on one line

 We can insert the special "newline character" \n in order to get line breaks

print("First line\nSecond line")

3. Control Flow: Conditional Statements and Loops

Decision making and iteration

Control Flow

straight-line control flow

control flow with branching and loop

true

true false

false boolean1

boolean2

stmt3

stmt2 stmt1

stmt1

stmt2

stmt3

(5)

Conditional Statement

 Evaluate a boolean expression:

If it is true, execute some statement(s)

If it is false, execute some other statement(s)

 Python syntax:

if …:

else:

 Special case: missing else-branch

Results in statement(s) guarded by a condition

 Python also has an elif-statement if you need to make a choice between more than two branches

Examples

if profit > 0:

print ("Factory is making a profit!") else:

print ("Factory is not making a profit!")

if production < 0:

print ("Warning: production negative") print ("Please check your numbers!")

while Loops

 Iterate some statement (s) as long as a condition is fulfilled.

while … :

 As the syntax suggests, the condition is checked before the statements in the body of the loop are carried out

 If the condition is false to start with, then the loop body is not executed

Loop Example: Multiplication Table

counter = 0 n = 7

while (counter < 12):

print (counter * n) counter = counter + 1

(6)

Loop Example: Adding up Numbers

### Adding up numbers

### Can you guess the meaning of the += operator?

counter = 0 n = 100 sum = 0

while (counter <= 100):

sum += counter counter += 1 print("sum = ", sum)

4. Lists

Lists

 One of Python's inbuilt sequence data structures

 Values ("items") are separated by commas and enclosed in square brackets

myList = [2,3,5,8,13,21,33]

 List elements can be accessed and updated by indexing

Warning: first element has index 0

 Example:

x = myList[2] + myList[4]

myList[6] = 34

 Python comes with many useful functions and operators on lists, please see literature

Iterating over Elements of a List

 Python also has a for-loop to iterate over all elements of a list (or other sequences)

for … in … :

 Example: sum up elements of list

sum = 0

for item in myList:

sum += item print(sum)

(7)

Iterating over a Range of Numbers

 Recall our earlier while-loop program to add up numbers from 1 to 100

 This can be rewritten more elegantly using a for-loop and a number range.

sum = 0

for item in range(1,101):

sum += item print(sum)

5. Functions

Invocation, imports, definition input()

Using Existing Functions

 The Python distribution comes with lots and lots of functions

 Some are built-in and immediately available

len(), min(), max(), sorted(), sum(), …

 Other functions are organised in modules

these need to be imported before you can use them

 Example: module random implements pseudo-random number generators; it has a function randint(a,b) that generates a random int value x such that a <= x <= b

from random import randint for x in range (1,10):

print(randint(1,6))

Defining Functions

 Programmers can define their own functions (and modules)

These can perform arbitrary computations

They may be dependent on some function parameters

They can return a result (like a mathematical function), or they may just "do something" like printing to the console

 Function definition syntax:

def fctname (parameters):

# function body

# one or more return statements

(8)

Function Definition Example

 Recall our earlier golf ball factory example

 We define a function which computes profit in dependency of the number p of golf balls produced:

def profit (p):

costPerItem = 1.35 fixedCost = 2850 salesPrice = 2.50

result = p * (salesPrice - costPerItem) - fixedCost return result

for p in [2000,2500,3000]:

print("Products:",p,"profit:",profit(p))

Interactive Programs and input()

 Many programs are interactive. When they run, they

Request some input from the user

Respond with some output

 Function input() displays some text ("prompt") and then reads one line from the keyboard.

Program will block until user hits return- or enter-key

 Typical usage

myVar = input("Please enter … ")

 This stores input as a string in variable myVar

It can be converted to a number using functions int() or float()

### Interactive "profit calculation" program

### salesPrice, costPerItem and fisedCost

### Program will run until the user enters a -1

### Note the conversion from input string to an int number

### Can you guess what happens if the input is not an int?

def profitInteractive():

p=0

while (p != -1):

p = int(input("Please enter a number or -1 to quit:\n")) profit = p * (salesPrice - costPerItem) - fixedCost if (p != -1): print("Profit = ", profit)

Concluding Remarks

 We have covered a lot of ground in this lecture

In our Year 1 programming module CE151, these topics are spread out over several weeks of teaching!

 For more details on Python, please see online documentation and tutorials

 We will do some exercises in the lab sessions

There will be several staff members to help you

Please ask questions if you get stuck!

 Programming is a craft

It requires practice

References

Related documents