Statements 2. a operator= b a = a operator b

Similar documents
Python I. Some material adapted from Upenn cmpe391 slides and other sources

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

Flow Control: Branches and loops

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Introduction to Python

Review Sheet for Midterm #1 COMPSCI 119 Professor William T. Verts

Some material adapted from Upenn cmpe391 slides and other sources

Sequence types. str and bytes are sequence types Sequence types have several operations defined for them. Sequence Types. Python

ENGR 102 Engineering Lab I - Computation

Lecture Transcript While and Do While Statements in C++

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Python Intro GIS Week 1. Jake K. Carr

Visualize ComplexCities

Python in 10 (50) minutes

Test #2 October 8, 2015

Outline. 1 If Statement. 2 While Statement. 3 For Statement. 4 Nesting. 5 Applications. 6 Other Conditional and Loop Constructs 2 / 19

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

Introduction to Concepts in Functional Programming. CS16: Introduction to Data Structures & Algorithms Spring 2017

YOLOP Language Reference Manual

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

age = 23 age = age + 1 data types Integers Floating-point numbers Strings Booleans loosely typed age = In my 20s

Functions, Scope & Arguments. HORT Lecture 12 Instructor: Kranthi Varala

Chapter 2: Functions and Control Structures

Introduction to Computer Programming CSCI-UA 2. Review Midterm Exam 1

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

CSI33 Data Structures

Control and Environments Fall 2017 Discussion 1: August 30, Control. If statements. Boolean Operators

Control Structures. CIS 118 Intro to LINUX

CONTROL AND ENVIRONMENTS 1

Advanced Python. Executive Summary, Session 1

CIS192 Python Programming. Robert Rand. August 27, 2015

The second statement selects character number 1 from and assigns it to.

XQ: An XML Query Language Language Reference Manual

Sketchpad Graphics Language Reference Manual. Zhongyu Wang, zw2259 Yichen Liu, yl2904 Yan Peng, yp2321

History Installing & Running Python Names & Assignment Sequences types: Lists, Tuples, and Strings Mutability

Python Evaluation Rules

Lab 5 - Repetition. September 26, 2018

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration

Programming to Python

CS1 Lecture 3 Jan. 18, 2019

Basic Syntax - First Program 1

61A Lecture 2. Wednesday, September 4, 2013

Java Methods. Lecture 8 COP 3252 Summer May 23, 2017

Lecture 19: Functions, Types and Data Structures in Haskell

SCoLang - Language Reference Manual

Using Scala in CS241

CS1 Lecture 3 Jan. 22, 2018

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

Python review. 1 Python basics. References. CS 234 Naomi Nishimura

CS 61A Control and Environments Spring 2018 Discussion 1: January 24, Control. If statements. Boolean Operators

Control and Environments Fall 2017 Discussion 1: August 30, 2017 Solutions. 1 Control. If statements. Boolean Operators

CS Summer 2013

Programming in Python

Python as a First Programming Language Justin Stevens Giselle Serate Davidson Academy of Nevada. March 6th, 2016

THE IF STATEMENT. The if statement is used to check a condition: if the condition is true, we run a block

Control Structures 1 / 17

CS 2316 Exam 1 Spring 2013

KS5-HE Transition Guide Checkpoint Task Instructions and answers for teachers

Python: common syntax

Python: Functions. Thomas Schwarz, SJ Marquette University

Programming Basics and Practice GEDB029 Decision Making, Branching and Looping. Prof. Dr. Mannan Saeed Muhammad bit.ly/gedb029

SECOND EDITION SAMPLE CHAPTER. First edition by Daryl K. Harms Kenneth M. McDonald. Naomi R. Ceder MANNING

G Programming Languages - Fall 2012

C ONTROL AND H IGHER O RDER F UNCTIONS

Accelerating Information Technology Innovation

Accelerating Information Technology Innovation

Loops and Conditionals. HORT Lecture 11 Instructor: Kranthi Varala

CSCE 314 TAMU Fall CSCE 314: Programming Languages Dr. Flemming Andersen. Haskell Functions

CIS192: Python Programming Data Types & Comprehensions Harry Smith University of Pennsylvania September 6, 2017 Harry Smith (University of Pennsylvani

Overview of the Ruby Language. By Ron Haley

Lists, loops and decisions

Shell CSCE 314 TAMU. Haskell Functions

Data Structures (list, dictionary, tuples, sets, strings)

Sequence Types FEB

Sequence of Characters. Non-printing Characters. And Then There Is """ """ Subset of UTF-8. String Representation 6/5/2018.

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

All written answers are limited to their question boxes. Make sure all answers are easily legible.

Computing with Numbers

Compound Data Types 1

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015

61A Lecture 3. Friday, September 5

EXPRESSIONS, STATEMENTS, AND FUNCTIONS 1

PYTHON. Varun Jain & Senior Software Engineer. Pratap, Mysore Narasimha Raju & TEST AUTOMATION ARCHITECT. CenturyLink Technologies India PVT LTD

SAMPLE CHAPTER. Naomi Ceder MANNING. Foreword by Nicholas Tollervey

Text Input and Conditionals

4.2 Function definitions the basics

BoredGames Language Reference Manual A Language for Board Games. Brandon Kessler (bpk2107) and Kristen Wise (kew2132)

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Spring 2018 Discussion 7: March 21, Introduction. 2 Primitives

MEIN 50010: Python Flow Control

Loops and Files. Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

Programming with Python

Typescript on LLVM Language Reference Manual

Implementing an Algorithm for Boomerang Fraction Sequences in Python

And Parallelism. Parallelism in Prolog. OR Parallelism

The Warhol Language Reference Manual

LOOPS. Repetition using the while statement

The SPL Programming Language Reference Manual

18.1. CS 102 Unit 18. Python. Mark Redekopp

Transcription:

Statements 2 Outline Note: i=i+1 is a valid statement. Don t confuse it with an equation i==i+1 which is always false for normal numbers. The statement i=i+1 is a very common idiom: it just increments by one the value pointed by variable i. The shorthand for this is: i += 1. Similarly, i=i-1 can be written with i-=1 The binary operators + - * / // % & ^ >> << ** have also corresponding augmented assignment operators += -= *= /= //= %= &= = ^= >>= <<= **= The following forms are equal a operator= b a = a operator b

Doing repetitive things: loops 1 In Python there are two kinds of loops: while and for A while loop repeats a set of statements while a given condition holds Example: i=1 while i*i < 1000: print "Square of", i, "is", i*i i=i+1 print "Finished printing all the squares below 1000"

Doing repetitive things: loops 2 This while loop repeated two statements: the print statement and the assignment statement, which increments the value of variable i by one. The block of staments that is subjected to a compound statement, like the while statement, are denoted by indentation Indentation means that a line is started with a sequence of whitespaces, usually this is a sequence of four space characters All statements in the same block must start at the same column

Doing repetitive things: loops 3 The last print statement has less indentation than the previous two lines, which means the block of statements has ended Another way to repeat statements is with the for statement Example: sum=0 for i in [0,1,2,3,4,5,6,7,8,9]: sum=sum+i print "The sum is", sum

Doing repetitive things: loops 4 The for loop executes the statements in the block as many times as there elements in the sequence given after the keyword in And at each iteration, the variable i has another value from the sequence The elements of the sequence are guaranteed to be iterated in order In the previous example the sequence happened to be a list, which is a basic data structure of Python. The list is one example of sequences Even more generally, instead of a sequence the elements can come from an iterable. They are a generalisation of a sequence.

The break statement Sometimes, when we are executing a loop, we want to stop the iteration, even when all elements have not been iterated or when the while condition still holds This can be achieved by executing the break statement in the loop body This stops the loop and continues execute whatever comes after the loop

Continue continue is another loop control statement This statement stops the execution of statements of the loop body that follow the continue statement The execution then continues from the beginning of the loop body, and if the loop is a for loop, the next value in the sequence will be processed

break example Outline for i in [1,2]: print i print "hello" break print "bye" print "The for loop just finished"

continue example Outline for i in [1,2]: print i print "hello" continue print "bye" print "The for loop just finished"

Making decisions: the if statement 1 Let s say we want to find the absolute value of a number x given by user The absolute value is x itself if it is non-negative, or if x is negative then the absolute value is its opposite: -x

Making decisions: the if statement 1 Let s say we want to find the absolute value of a number x given by user The absolute value is x itself if it is non-negative, or if x is negative then the absolute value is its opposite: -x We can express this decision with the if statement: import sys str=sys.stdin.readline() x=int(str) print "The absolute value of", x, "is" if x >= 0: print x else: print -x

Making decisions: the if statement 2 The if statement is a compound statement like for and while statements But the if statement can have several blocks of statements subjected to it: In the previous example there was one block in the if-clause, and one block in the else-clause

Making decisions: the if statement 3 Generic form of an if statement is: if condition1: statement1_1 statement1_2... elif condition2: statement2_1 statement2_2...... else: statementn_1 statementn_2...

Making decisions: the if statement 4 Example: c=-5 if c > 0: print "c is positive" elif c<0: print "c is negative" else: print "c is zero" Python doesn t have a switch-case statement, but the if/elif/else statement can be used to imitate switch-case

An else clause at the end of a loop The block under else is executed always when the loop wasn t stopped by the break statement Example: for c in "alongstring": if c == q : break else: print "Character q not found"

Functions 1 The loop structures of Python allow block of statements to be reused So, instead of writing print "Hoorray!" print "Hoorray!" print "Hoorray!" we can write for i in range(3): print "Hoorray!" But it would be nice to be able to use a block of statements also elsewhere in the source code, not just during the execution of the loop

Functions 2 A function is a block of statements, and we can refer to it by a name A function also has an interface, so we can give parameters to it and receive a value from it. Because the behaviour of a function can depend on the parameters given to it, the resulting function is even more reusable. Python functions can be like mathematical functions that only compute a new value based on given rules and the parameters Or the functions can in addition have side-effects

Functions 3: function definition A function definition looks like this: def function_name(param1,..., paramn, dparam1=expr1,...,dparamm=exprm): "Documentation of the function goes here" statement1... statementk return expression

Functions 4 The parameter names can be used in the statements of the block With the return statement a function can return a value back to the caller of the function. The return statement is not mandatory since a function doesn t need to return a value. The line that defines the function name and its parameters is called the signature of the function. After the signature there is an optional documentation string. This exists to give information about the function to a user. This information can be retrieved with the call help(function name)

Functions 5: calling a function When Python sees a function definition, it just stores the function. It doesn t execute the statements yet. The execution of a function is triggered by a function call When Python sees a function call function name(expr1,..., exprl) the parameters of the function are bound to the values of the expressions given in the function call. And then the statements are executed After this the value of the function call expression is bound to the value returned by the function.

Functions 6: optional parameters In the function definition some of the parameters were given a default value: dparam=expression These are optional parameters, they can only appear after the mandatory parameters If in a function call some of the optional parameters from the end are left out, they are given the default parameter values For example, if the signature is f(a, b=1, c=2), and the call is f(0,2), then the parameter values are a=0, b=2, c=2.

Functions 7: named arguments Normally the function call arguments correspond to function parameters in the same order (positional arguments). The order can be changed using named arguments in the function call. For example, the function call f(0,c=3) will result in the parameter bindings a=0,b=1,c=3. The named arguments in the function call must come after any positional arguments

Sequences A list is a dynamic collection of values/objects that are stored in order An example of a list with 4 values: [2, 100, hello, 1.0] A tuple is fixed length, immutable, ordered container. Elements of tuple are separated by commas and written between parentheses A singleton (3,), a pair (1,3), and a triple (1, hello,1.0) are examples of tuples As we can see, both lists and tuples can contain values of different type Lists, tuples and strings are called sequences in Python, and they have several commonalities

Common features of sequences The length of any sequence can be found with the len function min and max functions find the minimum and maximum element of a sequence, and sum adds all the elements of a sequence of numbers together Sequences can be concatenated with the + operator, and repeated with the * operator: "hi"*3=="hihihi" Since sequences are ordered, we can refer to the elements of a sequence by integers using the bracket notation: "abcd"[2]=="c" Note that the indexing begins from 0 Negative integers start indexing from the end: -1 refers to the last element, -2 refers to the second last, and so on