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



Similar documents
We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

Introduction to Python

Exercise 1: Python Language Basics

CSCE 110 Programming I Basics of Python: Variables, Expressions, and Input/Output

Exercise 4 Learning Python language fundamentals

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

6.170 Tutorial 3 - Ruby Basics

Chapter 2 Writing Simple Programs

Introduction to Java

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

Introduction to Python

Python Lists and Loops

JavaScript: Introduction to Scripting Pearson Education, Inc. All rights reserved.

Introduction to Python

1 Introduction. 2 An Interpreter. 2.1 Handling Source Code

Computational Mathematics with Python

Unix Shell Scripts. Contents. 1 Introduction. Norman Matloff. July 30, Introduction 1. 2 Invoking Shell Scripts 2

VHDL Test Bench Tutorial

Python Programming: An Introduction to Computer Science

Introduction to Java. CS 3: Computer Programming in Java

Sources: On the Web: Slides will be available on:

Informatica e Sistemi in Tempo Reale

Chapter 3 Writing Simple Programs. What Is Programming? Internet. Witin the web server we set lots and lots of requests which we need to respond to

Outline Basic concepts of Python language

Object Oriented Software Design

Object Oriented Software Design

ESPResSo Summer School 2012

Chapter 15 Functional Programming Languages

Microsoft Access 3: Understanding and Creating Queries

Visual Logic Instructions and Assignments

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

PYTHON Basics

Thomas Jefferson High School for Science and Technology Program of Studies Foundations of Computer Science. Unit of Study / Textbook Correlation

CSC 221: Computer Programming I. Fall 2011

Moving from CS 61A Scheme to CS 61B Java

Variables, Constants, and Data Types

Welcome to Introduction to programming in Python

University of Hull Department of Computer Science. Wrestling with Python Week 01 Playing with Python

Writing Simple Programs

Computer Science 217

CS106A, Stanford Handout #38. Strings and Chars

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Computational Mathematics with Python

Using Files as Input/Output in Java 5.0 Applications

The C Programming Language course syllabus associate level

Computational Mathematics with Python

J a v a Quiz (Unit 3, Test 0 Practice)

Fundamentals of Java Programming

WAYNESBORO AREA SCHOOL DISTRICT CURRICULUM INTRODUCTION TO COMPUTER SCIENCE (June 2014)

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

High-Level Programming Languages. Nell Dale & John Lewis (adaptation by Michael Goldwasser)

QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall

Database Programming with PL/SQL: Learning Objectives

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

Problem Solving Basics and Computer Programming

Pseudo code Tutorial and Exercises Teacher s Version

Python Loops and String Manipulation

McGraw-Hill The McGraw-Hill Companies, Inc.,

Python Programming: An Introduction to Computer Science

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

Python Programming: An Introduction to Computer Science

Contents. 9-1 Copyright (c) N. Afshartous

Chapter 2: Elements of Java

Example of a Java program

Chapter One Introduction to Programming

PHP Tutorial From beginner to master

Oracle Database: SQL and PL/SQL Fundamentals

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

Computer Programming I & II*

LEARNING TO PROGRAM WITH PYTHON. Richard L. Halterman

Lecture 2 Notes: Flow of Control

River Dell Regional School District. Computer Programming with Python Curriculum

Computer Programming I

VISUAL GUIDE to. RX Scripting. for Roulette Xtreme - System Designer 2.0

CS 106 Introduction to Computer Science I

CS101 Lecture 24: Thinking in Python: Input and Output Variables and Arithmetic. Aaron Stevens 28 March Overview/Questions

Summit Public Schools Summit, New Jersey Grade Level / Content Area: Mathematics Length of Course: 1 Academic Year Curriculum: AP Computer Science A

Programming and Software Development CTAG Alignments

CS 2112 Spring Instructions. Assignment 3 Data Structures and Web Filtering. 0.1 Grading. 0.2 Partners. 0.3 Restrictions

Oracle SQL. Course Summary. Duration. Objectives

Java Basics: Data Types, Variables, and Loops

Lab 9 Access PreLab Copy the prelab folder, Lab09 PreLab9_Access_intro

Lecture 5: Java Fundamentals III

Duration Vendor Audience 5 Days Oracle End Users, Developers, Technical Consultants and Support Staff

Some programming experience in a high-level structured programming language is recommended.

Oracle Database: SQL and PL/SQL Fundamentals NEW

OpenOffice.org 3.2 BASIC Guide

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

Hands-On Python A Tutorial Introduction for Beginners Python 3.1 Version

PL / SQL Basics. Chapter 3

Computer Programming Tutorial

Simulation Tools. Python for MATLAB Users I. Claus Führer. Automn Claus Führer Simulation Tools Automn / 65

Python Programming: An Introduction to Computer Science

#820 Computer Programming 1A

CS177 MIDTERM 2 PRACTICE EXAM SOLUTION. Name: Student ID:

PostgreSQL Functions By Example

Oracle Database: SQL and PL/SQL Fundamentals

Scanner sc = new Scanner(System.in); // scanner for the keyboard. Scanner sc = new Scanner(System.in); // scanner for the keyboard

Transcription:

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