Computers An Introduction to Programming with Python CCHSG Visit June 2014 Dr.-Ing. Norbert Völker 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 Programming Languages 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 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 Can you think of some programs running on a computer or a mobile phone? 1
Five Fundamental Programming Concepts 1) Simple values and operators: numbers, booleans and strings 2) Variables and assignments 3) Control flow: conditional statements and loops 1. Simple Values and Operators: Numbers, Booleans and Strings 4) Lists 5) Functions Numbers and Arithmetic Operators Booleans and Comparison 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 remainderof division) 5 / 3 5 // 3 5 % 3 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) 2
Strings A stringis 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] ithitem of s, origin 0 s[i:j] slice of sfrom ito j len(s) length of s 2. Variables and Assignments And print() Function Variables and Assignments Breaking Down Arithmetic Calculations Non-trivial programs consist of a number of steps How can we remember interim results? A variablehas 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 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? 3
Profit Calculation in Python print() Function production = 2700 costperitem = 1.35 fixedcost = 2850 salesprice = 2.50 profit = production * (salesprice - costperitem) - fixedcost 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) How does this Python solution compare to solving the question on paper or on a calculator? 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") Control Flow boolean1 false 3. Control Flow: Conditional Statements and Loops stmt1 stmt1 true stmt2 Decision making and iteration stmt2 boolean2 true stmt3 false stmt3 straight-line control flow control flow with branching and loop 4
Conditional Statement Examples 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 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 Loop Example: Multiplication Table 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 counter = 0 n = 7 while (counter < 12): print (counter * n) counter = counter + 1 5
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 Iterating over Elements of a List 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 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) 6
Iterating over a Range of Numbers Recall our earlier while-loop program to add up numbers from 1to 100 This can be rewritten more elegantly using a for-loop and a number range. 5. Functions sum = 0 for item in range(1,101): sum += item print(sum) Invocation, imports, definition input() Using Existing Functions Defining 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 importedbefore you can use them Example: module randomimplements pseudo-random number generators; it has a function randint(a,b) that generates a random intvalue xsuch that a <= x <= b from random import randint for x in range (1,10): print(randint(1,6)) 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 7
Function Definition Example Interactive Programs and input() 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)) 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 8