CSC1015F – Python Chapter2 Michelle Kuttel

Slides:



Advertisements
Similar presentations
Adapted from John Zelle’s Book Slides
Advertisements

Python Programming: An Introduction to Computer Science
CSC 110 Writing simple programs [Reading: chapter 2] CSC 110 C 1.
Vahé Karamian Python Programming CS-110 CHAPTER 2 Writing Simple Programs.
Introduction to Python
Chapter 2 Writing Simple Programs
Python. What is Python? A programming language we can use to communicate with the computer and solve problems We give the computer instructions that it.
Python.
Python Programming Fundamentals
Introduction to Python
Python Programming, 2/e1 Python Programming: An Introduction to Computer Science Chapter 2.
Python Programming, 2/e1 Python Programming: An Introduction to Computer Science Chapter 1 Computers and Programs.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
CS 127 Writing Simple Programs.  Stages involved  Analyze the problem  Understand as much as possible what is trying to be solved  Determine Specifications.
CPTR 124 Review for Test 1. Development Tools Editor Similar to a word processor Allows programmer to compose/save/edit source code Compiler/interpreter.
Chapter 2 Overview of C Part I J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National Taipei University.
1 CSC 221: Introduction to Programming Fall 2012 Functions & Modules  standard modules: math, random  Python documentation, help  user-defined functions,
Input, Output, and Processing
Computer Science 101 Introduction to Programming.
Guide to Programming with Python Chapter One Getting Started: The Game Over Program.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Chapter 0 Getting Started. Objectives Understand the basic structure of a C++ program including: – Comments – Preprocessor instructions – Main function.
CSC 110 Using Python [Reading: chapter 1] CSC 110 B 1.
Variables, Expressions and Statements
Software Development. Software Development Loop Design  Programmers need a solid foundation before they start coding anything  Understand the task.
Introduction to Python Dr. José M. Reyes Álamo. 2 Three Rules of Programming Rule 1: Think before you program Rule 2: A program is a human-readable set.
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
Trinity College Dublin, The University of Dublin GE3M25: Computer Programming for Biologists Python Karsten Hokamp, PhD Genetics TCD, 03/11/2015.
1 Printing in Python Every program needs to do some output This is usually to the screen (shell window) Later we’ll see graphics windows and external files.
2. WRITING SIMPLE PROGRAMS Rocky K. C. Chang September 10, 2015 (Adapted from John Zelle’s slides)
Python Let’s get started!.
1. COMPUTERS AND PROGRAMS Rocky K. C. Chang September 6, 2015 (Adapted from John Zelle’s slides)
JavaScript Introduction and Background. 2 Web languages Three formal languages HTML JavaScript CSS Three different tasks Document description Client-side.
Today… Python Keywords. Iteration (or “Loops”!) Winter 2016CISC101 - Prof. McLeod1.
Python Programming, 2/e1 Python Programming: An Introduction to Computer Science Chapter 2.
1 C Syntax and Semantics Dr. Sherif Mohamed Tawfik Lecture Two.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
Getting Started With Python Brendan Routledge
Part 1 Learning Objectives To understand that variables are a temporary named location to store data and that programmers work with different data types.
Python Programming Module 1 Computers and Programs Python Programming, 2/e1.
PROBLEM SOLVING WARM-UP Fill in the spaces using any operation to solve the following (!, (), -/+,÷,×): = 6.
Chapter 2 Writing Simple Programs
Fundamentals of Programming I Overview of Programming
Software Development.
Topics Designing a Program Input, Processing, and Output
Introduction to Programming
Python: Experiencing IDLE, writing simple programs
CS170 – Week 1 Lecture 3: Foundation Ismail abumuhfouz.
Python Let’s get started!.
Introduction to Python
Python Programming: An Introduction to Computer Science
Python Programming: An Introduction to Computer Science
Presented By S.Yamuna AP/IT
Variables, Expressions, and IO
Statement atoms The 'atomic' components of a statement are: delimiters (indents, semicolons, etc.); keywords (built into the language); identifiers (names.
Functions CIS 40 – Introduction to Programming in Python
Introduction to Python
CISC101 Reminders Quiz 1 grading underway Assn 1 due Today, 9pm.
Topics Designing a Program Input, Processing, and Output
A look at Python Programming Language 2018.
Topics Introduction to Value-returning Functions: Generating Random Numbers Writing Your Own Value-Returning Functions The math Module Storing Functions.
15-110: Principles of Computing
CISC101 Reminders All assignments are now posted.
Topics Designing a Program Input, Processing, and Output
Topics Designing a Program Input, Processing, and Output
Beginning Python Programming
COMPUTER PROGRAMMING SKILLS
12th Computer Science – Unit 5
Chopin’s Nocturne.
PYTHON - VARIABLES AND OPERATORS
Presentation transcript:

CSC1015F – Python Chapter2 Michelle Kuttel

Programming languages  A program is a sequence of instructions telling a computer what to do.  Human languages still don’t work for this  Ambiguous and imprecise  E.g. “They are hunting dogs.”  Programming languages express computations in an exact and unambiguous way  Precise SYNTAX (form) and SEMANTICS (meaning) 2

Origins of the Python language  Created by Dutch computer programmer Guido van Rossum in the early 1990’s  Benevolent Dictator for Life (BDFL)  Intellectual property now owned by the Python Software Foundation (PSF)  We are using Python Version 3  Free and well documented  runs everywhere  Clean syntax 3

Integrated Development Environment (IDE)  Graphical interface with menus and windows, much like a word processor  We recommend Wingware 101  free, scaled-down Python IDE designed for use in teaching introductory programming classes.  It omits many features found in Wing IDE Professional and makes simplifications appropriate for beginners.omits many features  you are welcome to use any other tools – e.g. IDLE  even a separate text editor and interpreter if you wish to simply do things the hard way  Michelle likes to do this sometimes… 4

Python expressions Programs are made up of commands (or statements) that a computer executes or evaluates. One kind of statement is an expression statement, or expression. 5

Elements of programs: Expressions  Expressions are fragments of code that produce or calculate new data values, such as  Literals  e.g. 3.9, “hello”, 1  Variables  e.g. x  Simple expressions combined with operators, e.g:  5+2  x**2  “bat”+”man”  e.g. mathematical expressions like:  >>>  will be evaluated as 7. 6

Python interactive shell The >>> part is called a prompt, because it prompts us to type something. 7

Elements of programs: Variables and assigment x=3 x+4  x is a variable  A variable is used to name a value so that we can refer to it later an assignment statement assigns a value to a variable 8

Elements of programs: Assignment statements  One of the most important kinds of statement in Python. e.g.: x=5 x=x+1  Basic form: = x 6 6 x

Elements of programs: Names  We name:  Modules  Functions  Variables  Examples of valid names:  X  y  happy  dazed_and_Confused  Dazed_and_Confused2 10

Elements of programs: Names  BUT you can’t use Python keywords (reserved words) as names. These are: False None True and as assert break class continue def del elif else except finally for from global if import in is lambda nonlocal not or pass raise return try while with yield 11

Checkpoint height = 1.69 weight = 71.5 weight/(height*height) From this Python code, give an example of:  a variable  an assignment statement  a literal 12

Comments  And text on a line after the ‘#” symbol will be ignored by the Python interpreter: # algorithm to calculate BMI height = 1.69 weight = 71.5 weight/(height*height) #calculates BMI  It is essential to include comments to explain your code to others (and your future self!) 13

Elements of programs: Output statements  The print function will display text to the screen  e.g. >>> print( " Hello " ) >>> Hello  e.g. # algorithm to calculate BMI height = 1.69 weight = 71.5 BMI = weight/(height*height) #calculates BMI print("Body mass index = ",BMI) 14

Checkpoint # file BobBill.py Bob="Bob" Bill="Bill" Bob=Bill Bill=Bill*3 print(Bob,Bill) From this code, give an example of:  a variable  a literal  an expression  an assignment statement 15

Checkpoint: What is the output of this code? # file BobBill.py Bob="Bob" Bill="Bill" Bob=Bill Bill=Bill*3 print(Bob,Bill) 16

Elements of programs: More about print  print is a built in function with a precise set of rules for its syntax and semantics  e.g. two forms: print(,,…, ) print()  By default, print puts a single blank space between the displayed values 17

More about “print()” function  To print a series of values separated by spaces: print("The values are", x, y, z)  To suppress or change the line ending, use the end=ending keyword argument. e.g.: print("The values are", x, y, z, end=‘’)  To change the separator character between items, use the sep=sepchr keyword argument. e.g. print("The values are", x, y, z,sep=’*’) 18

Escape sequences Escape sequences are special characters that represent non-printing characters  tabs, newlines e.g: \a - bell (beep) \b – backspace \n – newline \t – tab \’ – single quote \” – double quote \v - vertical tab 19

Checkpoint: What is the exact output of this code? x=20 y=30 z=40 print(x) print(y,'\n',z) 20

Checkpoint: What is the exact output of this code? x=20 y=30 z=40 print("The values are", x, y, z, end='!!!',sep='!***') 21

Elements of programs: Input statements  The purpose of an input statement is to get some information from the user and store it into a variable.  In Python, input is accomplished using an assignment statement combined with a special expression called input. This template shows the standard form: = input( ) Here, prompt is usually some text asking the user for input e.g. weather = input(“What is the weather like today?”) 22

Elements of programs: Input statements  the input statement treats whatever the user types as an expression to be evaluated. e.g. n = input("Please enter a number: ") personA = input(“What is your name?”) 23

Checkpoint: What is the exact output of this code? name = input("What is your name? ") print("Hellooooo", name*3, end='!!!',sep='…') 24

Elements of programs: Input statements and numbers the input expression is evaluated as a string (text)  this must be converted into a number if you are going to do math  text (strings) and numbers are handled differently by the computer – more about this later!  eval() is a Python function that converts a string into a number  eval(“20”) -> 20 25

Elements of programs: Input statements and numbers Useful example using eval… # algorithm to calculate BMI, using input height = input("Type in your height: ") weight = input("Type in your weight: ") height=eval(height) #change a string into a number weight=eval(weight) #change a string into a number BMI = weight/(height*height) #calculates BMI print("Body mass index = ",BMI) 26

Saving programs to file  If you type them in directly, programs definition are lost when you quit the shell  So, we usually type programs into a separate file, called a module, or script #file: greet3.py person = “Bob” threeTimes = person*3 print("Hello", threeTimes) print("Oops.... ”) 27

Where to use comments  Brief description, author, date at top of function.  Brief description of purpose of each method (if more than one).  Short explanation of non-obvious parts of code within methods. #My very first program #Author: Michelle Kuttel #date 21/2/

Simultaneous assignment  Can assign several values at once: personA, personB, personC =“Tom”, “Dick”, “Harry” x,y = 10,20 sum, diff = x+y, x-y x,y = y,x 29

Checkpoint: What is the output of this code? x,y = 10,20 x,y = y,x print(x,y) 30

Python first function def hello(): print(“Hello”) print(“I love CSC1015F”)  Defines a new function called hello  Indentations show that the lines below hello belong to the function  Invoked like this: hello() 31

Python second function def hello2(): name = input("What is your name? ") print("Hellooooo", name*3, end='!!!',sep='…') 32

Parameters  Functions can have changeable parameters (or arguments) that are placed within parenthesis. E.g. def greet(person): print(“hello”, person) print(“How are you?”) n = input(”What is your name?”) greet(n) 33

Checkpoint def greet(person): print(“hello”, person) print(“How are you?”) n = input(”What is your name?”) greet(n) From this code, give an example of:  a variable  a literal  an expression  an assignment statement  a parameter  a function 34

Checkpoint: What is the exact output of this code? # function checkpoint OneTwoThree.py def A(word1, word2, word3): print(word3,word2,word1,sep='...',end='STOP') A("green","orange","red") 35

Checkpoint: What is the exact output of this code? # function checkpoint OneTwoThree.py def A(word1, word2, word3): print(word3,word2,word1,sep='...',end='STOP') print(“Testing…”) x,y,z="green","orange","red" A(x,y,z) A(z*2,y*2,x*2) 36

Example program: Miles-to-kilometres converter  You’re visiting the USA and distances are all quoted in miles  I mile = 1.61 km  Write a program to do this conversion  Algorithm conforms to a standard pattern:  Input, Process, Output (IPO)  Ask user for input in miles, convert to kilometers, output result by displaying it on the screen 37

Algorithms and Pseudocode  Pseudocode is just precise English that describes what a program does  Communicate the algorithm without all the details e.g. 38

Algorithms and Pseudocode  Pseudocode is just precise English that describes what a program does  Communicates the algorithm without all the details e.g. Input the distance in miles (call it miles ) Calculate kilometres as miles x 1.61 Output kilometres The next step is to convert this into a Python program 39

Miles.py #miles.py # A program to convert miles to kilometres # by: Michelle Kuttel def main(): miles = eval(input("What is the distance in miles? ")) kilometres = miles* 1.61 print("The distance in kilometres is",kilometres,"km.") main() 40

Breakdown of Miles.py #miles.py # A program to convert miles to kilometres # by: Michelle Kuttel def main(): miles = eval(input("What is the distance in miles? ")) kilometres = miles* 1.61 print("The distance in kilometres is",kilometres,"km.") main()  Defines a function called main (which has a special meaning) 41

Breakdown of Miles.py #miles.py # A program to convert miles to kilometres # by: Michelle Kuttel def main(): miles = eval(input("What is the distance in miles? ")) kilometres = miles* 1.61 print("The distance in kilometres is",kilometres,"km.") main() 42

Breakdown of Miles.py miles = eval(input("What is the distance in miles? "))  eval() is a Python function that converts a string into a number  eval(“20”) -> 20  for now, think of a string as a word or sentence (more on strings later)  the input statement treats whatever the user types as an expression to be evaluated 43

Breakdown of Miles.py #miles.py # A program to convert miles to kilometres # by: Michelle Kuttel def main(): miles = eval(input("What is the distance in miles? ")) kilometres = miles* 1.61 print("The distance in kilometres is",kilometres,"km.") main()  An expression which assigns a value to the variable kilometres using the multiplication operator 44

Breakdown of Miles.py #miles.py # A program to convert miles to kilometres # by: Michelle Kuttel def main(): miles = eval(input("What is the distance in miles? ")) kilometres = miles* 1.61 print("The distance in kilometres is",kilometres,"km.")  main()  An output statement 45

Breakdown of Miles.py #miles.py # A program to convert miles to kilometres # by: Michelle Kuttel def main(): miles = eval(input("What is the distance in miles? ")) kilometres = miles* 1.61 print("The distance in kilometres is",kilometres,"km.") main()  Calls the main method automatically when this module is run 46

More Python statements in future lectures… We also also have statements to:  Perform selections  Iterate (loop) 47

 This work is licensed under a Creative Commons Attribution-ShareAlike 2.5 South Africa License. 48