CS 115 Lecture 3 A first look at Python Taken from notes by Dr. Neil Moore.

Slides:



Advertisements
Similar presentations
Introduction to Programming
Advertisements

PROGRAMMING IN VISUAL BASIC PART 1
CS0007: Introduction to Computer Programming Console Output, Variables, Literals, and Introduction to Type.
Programming in Visual Basic
 2005 Pearson Education, Inc. All rights reserved Introduction.
Introduction to C Programming
CS16 Week 2 Part 2 Kyle Dewey. Overview Type coercion and casting More on assignment Pre/post increment/decrement scanf Constants Math library Errors.
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types.
Chapter 2 Basic Elements of Fortan
If You Missed Last Week Go to Click on Syllabus, review lecture 01 notes, course schedule Contact your TA ( on website) Schedule.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
XP 1 Working with JavaScript Creating a Programmable Web Page for North Pole Novelties Tutorial 10.
8 November Forms and JavaScript. Types of Inputs Radio Buttons (select one of a list) Checkbox (select as many as wanted) Text inputs (user types text)
Python Programming Chapter 2: Variables, expressions, and statements Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
Introduction to C Programming
Computer Science 101 Introduction to Programming.
UNIT 3 TEMPLATE AND EXCEPTION HANDLING. Introduction  Program errors are also referred to as program bugs.  A C program may have one or more of four.
EGR 2261 Unit 4 Control Structures I: Selection  Read Malik, Chapter 4.  Homework #4 and Lab #4 due next week.  Quiz next week.
JavaScript – Part II Data Types and Operations George Mason University June 3, 2010.
Introduction to Python
Computer Science 101 Introduction to Programming.
The Java Programming Language
Program A computer program (also software, or just a program) is a sequence of instructions written in a sequence to perform a specified task with a computer.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 2 Input,
Documentation and Comments. What’s a comment? A comment is a simple form of documentation. Documentation is text that you the programmer write to explain.
Input, Output, and Processing
Chapter 2 Overview of C++. A Sample Program // This is my first program. It calculates and outputs // how many fingers I have. #include using namespace.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 2 Chapter 2 - Introduction to C Programming.
Constants Numeric Constants Integer Constants Floating Point Constants Character Constants Expressions Arithmetic Operators Assignment Operators Relational.
Introduction to Programming with RAPTOR
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
1 Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
© 2004 Pearson Addison-Wesley. All rights reserved ComS 207: Programming I Instructor: Alexander Stoytchev
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
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.
COIT29222 Structured Programming 1 COIT29222-Structured Programming Lecture Week 02  Reading: Textbook(4 th Ed.), Chapter 2 Textbook (6 th Ed.), Chapters.
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.
Programming Errors. Errors of different types Syntax errors – easiest to fix, found by compiler or interpreter Semantic errors – logic errors, found by.
Python Let’s get started!.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 2 - Introduction to C Programming Outline.
1 Week 5 l Primitive Data types l Assignment l Expressions l Documentation & Style Primitive Types, Assignments, and Expressions.
Controlling Program Flow with Decision Structures.
 2007 Pearson Education, Inc. All rights reserved. A Simple C Program 1 /* ************************************************* *** Program: hello_world.
While loops. Iteration We’ve seen many places where repetition is necessary in a problem. We’ve been using the for loop for that purpose For loops are.
Chapter 4: Variables, Constants, and Arithmetic Operators Introduction to Programming with C++ Fourth Edition.
An Introduction to Programming with C++ Sixth Edition Chapter 5 The Selection Structure.
CS 115 Lecture 5 Math library; building a project Taken from notes by Dr. Neil Moore.
OPERATORS IN C CHAPTER 3. Expressions can be built up from literals, variables and operators. The operators define how the variables and literals in the.
Quiz 1 A sample quiz 1 is linked to the grading page on the course web site. Everything up to and including this Friday’s lecture except that conditionals.
1 Lecture 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line of Text 2.3Another Simple C Program: Adding.
CS 115 A First Look at Python
CS170 – Week 1 Lecture 3: Foundation Ismail abumuhfouz.
Chapter 2 - Introduction to C Programming
The Selection Structure
Variables, Expressions, and IO
Chapter 2 - Introduction to C Programming
CS 115 A First Look at Python
Exceptions and files Taken from notes by Dr. Neil Moore
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
Designing and Debugging Batch and Interactive COBOL Programs
Selection CIS 40 – Introduction to Programming in Python
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
Introduction to C++ Programming
Exceptions and files Taken from notes by Dr. Neil Moore
CS 115 A First Look at Python
Boolean Expressions to Make Comparisons
For loops Taken from notes by Dr. Neil Moore
Subject:Object oriented programming
Taken from notes by Dr. Neil Moore and Dr. Debby Keen
Presentation transcript:

CS 115 Lecture 3 A first look at Python Taken from notes by Dr. Neil Moore

Getting Python and WingIDE Instructions for installing Python and WingIDE 101 are on the web page: We’ll use WingIDE today. Hint: use a big font (18 or 20 point) for labs! It is easier both for us and for your teammates to read it!

Changing the font/size in WingIDE Start with Edit →Preferences Under “User Interface”, select “Fonts” – May be in a different location on Mac version To the right you see “Display Font/Size”: – Click the button for “Use selected Font/size”, then click the “Change” button – Select a size (18 or 20) and click “OK”. Below that choice, you see “Editor Font/Size” (controls the code’s font and size): – Either do the same steps as above… – Or select “Match Display Font/Size” – Some people prefer a monospace font for code Consolas, Lucida Console, Courier New, …

A first Python program, with bugs # compute the greatest common divisor (GCD) of two numbers. def main(): # Inputs: two positive integers (whole numbers) a and b. a = input(“Please enter first number: “) b = input(“Please enter another number: “) #1. Repeat as long as b is not zero while b != 0: #1.1. If a > b, then set a <- (a – b) if a > b: a = a – b # 1.2. Otherwise, set b <- (b – a) else: b = b – b #2. Output a as the answer print(“The GCM of your numbers is”,a) main()

Structure of a Python program def main(): – This is the first line of the “main function” where the program does all its work For now – More about functions in chapter 5 – Python does not need a main function, but use on in all code in this class! It’s good practice for later. Indentation and blocks. – Code is arranged in indented blocks. – The body of the main function is one block. – It can have several blocks inside it. The last line in the file is main() – This is the call to the main function. – It is not inside the main function! The line (the call) is not indented at all! – If you forget this line, the program does nothing when run!

Documentation and comments Syntax: Comments in Python start with a # character and extend to the end of the line. – A variant of a comment starts and ends with 3 single quotes. This version can include multiple lines, even paragraphs or pages. Semantics: Does nothing: ignored by the Python interpreter entirely. Why would we want to do that? Comments are for humans, not the computer. – Your teammates – Your boss (or instructor or grader …) You can communicate with your grader while they are grading! – Yourself next week! Or next month!

Where to use comments Comments don’t usually need to say how you are doing something or what you are doing. – That is what the code is for. Instead, they should say why. – BAD: counter = 0 # set variable to zero – GOOD: counter = 0 # initialize number of lines If the comment is long, put it on a line of its own before the code statement. – That way you don’t have to scroll horizontally to read it all. In general, try to keep code lines less than 80 characters. Less than that on team labs, where you are using a big font.

Header Comments – Name, , section number – Purpose of the program – Date completed – Preconditions: inputs to the program And what you assume is true about the inputs – Postconditions: outputs of the program And what you can guarantee about the outputs – Reference(s) or Citations when you received or gave assistance TA Name and Tutor Name and Partner’s name and and section URL and date you read the page

Kinds of Errors Back to our program – it has several errors right now. – Syntax errors – Semantic (logic) errors – Run-time errors

Syntax errors These are the easiest kind to find and fix Syntax is the set of rules that say how to write statements in the language – Programming languages are very rigid about syntax rules – Misspelling, incorrect punctuation, bad grammar, etc. are errors – Humans can probably figure out what you meant when you have syntax errors in English For computers this is a VERY difficult task The interpreter (or compiler) will give you an error message. – Translator programs are NOT “smart” sometimes. Their indication of where they think the error IS is not always right. – If they say it’s in line 10, make sure to look in line 9 or 8 or 7 … – Don’t bother to look after the line they indicate. – If there are comments between lines, skip those and look above them.

Semantic errors Also known as logic errors Semantics = meaning – The semantics of a program is what does it make the computer do when it is executed: what changes does it make in memory, what does it output… A semantics error is usually the program not doing what you want it to do – It always does what you tell it to! – Maybe you multiplied instead of dividing – Or you used the wrong variable or constant

Semantic errors The interpreter won’t detect these for you! So how do we find them? – Testing! – Making a test plan: what to test, provided input, expected output. – Coming up with a good set of test cases is one of the important parts of programming – By writing up test cases, you have to dig in and understand the desired behavior of the program

Run-time errors These occur when the program or interpreter encounters a situation it can’t handle – Usually causes the program to halt with an error message “crash” – It’s not detected until the situation actually happens! Often caused by the environment (operating system): – A file is not found – Network connection closed – Out of memory – A Storage device runs out of room Sometimes they are caused by programming errors: – Using a string where a number was expected – Using an undefined variable Some languages allow for catching and handling these errors by using exception handling (we’ll do a bit at the end of the semester)

Fixing bugs Let’s fix the bugs in our program – Syntax error: missing indentation – Run-time error: input is a string not a number – Semantic error: wrong formula for b – Semantic error: output message says “GCM”

Fixed Python program # compute the greatest common divisor (GCD) of two numbers. def main(): # Inputs: two positive integers (whole numbers) a and b. a = input(“Please enter first number: “) b = input(“Please enter another number: “) #1. Repeat as long as b is not zero while b != 0: #1.1. If a > b, then set a <- (a – b) if a > b: a = a – b # 1.2. Otherwise, set b <- (b – a) else: b = b – a #2. Output a as the answer print(“The GCD of your numbers is”,a) main()

Variables A variable is a “slot” or “holder” or “location” that refers to a value – a and b were variables in our program – A value is something like 42 or “Hello” – Variables are stored in RAM – They can refer to different values as the program runs (they are “vary-able”) Assignment (the equals sign) makes a variable refer to a new value – A variable is a fundamental building block of most programming languages.

Properties of a variable It has a name – one that means something – Also called an “identifier” It has a value – what is in the variable – In Python, the value of a variable is an object. It has a type – what kind of value – Integer, string, floating-point number, boolean, … Scope – where in the program is the name valid or accessible? – In Python, scope goes from the definition to the end of the block that the definition is in. – Can have variables with the same name as long as their scopes don’t overlap. They’re entirely unrelated variables!

Rules for Identifiers An identifier is a sequence of letters, digits and underscores (_) – “Alphanumeric” characters – Case sensitive: students and Students and STUDENTS are all different in Python – It cannot start with a digit (Python thinks that it is a number, although a badly formatted number) – Cannot be a reserved word (if, while, else, etc.) These are usually dark blue in WingIDE.

Rules for Identifiers Valid examples: x, size, name2, long_name, CamelCase, _ugly BAD: 2bad4u, no spaces, no-punctuation! Just because it’s legal doesn’t mean it’s a good name. – Avoid single-letter variables Except in loop counters or simple math equations – And names like “thing” and “number” aren’t any better – they don’t say what they mean – Better names are “lineCounter” or “num_students”

Can variable properties change? The name and scope of a variable never change. – If you think it did, it’s probably a different variable In a “dynamically typed” language like Python, the value and type of a variable can change – With an assignment statement: score = 0.0 score = “incomplete” In a “statically typed” language like C++, the type cannot change. In Python, it’s less confusing if each variable has ONE type. It gets a type when created and the type does not change. One common style: include the type in the variable name – Like “user_lst” or “name_str” or “hours_int”

The Assignment operator Syntax: variable = expression – Must be a single variable on the left Semantics: Calculates the value of (evaluates) the right hand side (RHS) then uses that value to change (replace) the value of the variable on the left hand side (LHS). This statement is not the same thing as an equation in math! – In math, x = x + 1 has no sensible solution – But in Python, x = x + 1 means “add 1 to x”. – Instead of “equals”, it’s better to read it as “gets” or … – “Assign x + 1 to x” or “Assign x with/from x + 1”. Although it looks trivial, it is where much of the processing of the program takes place! It is the most used statement to manipulate items in memory.

The Assignment operator Order matters! – The two steps are always done in the same order – First evaluate the right hand side – Then change only the variable on the left hand side – x + 1 = x # Syntax Error! If the LHS variable doesn’t already exist in this scope, it is created. – “Initialization”: give a variable its initial value Rule of Thumb: a variable has to appear on the left hand side of an assignment before it appears on the right hand side (not 100% true but very nearly)

Example of assignment: swapping Suppose we have two variables and want to swap their values. This means that each variable’s new value is the other variable’s old value. The code should look something like this: x = 10 y = 42 # do something print(x, y) # should print Will this work? x = y y = x print(x, y) No! it prints out We lost the old value of x!

Two Solutions to swapping This one works in any language – You need a third variable (temp) temp = x x = y y = temp This one works only in Python but it’s cute! x, y = y, x It works by making “implicit tuples” on each side and assigning corresponding values to variables on the left hand side.

Basic Arithmetic The expression on the right hand side of the assignment operator can be an arithmetic expression. Some arithmetic operators in Python are: – ** (exponentiation, “raise to the power of”) – * (multiply), / (divide) – +, - (add and subtract) These are listed in order from higher precedence to lower precedence Of course you can use parentheses to make the order you want explicit: total = price * (tax + 100) / 100 More details next lecture