Impera've Programming

Size: px
Start display at page:

Download "Impera've Programming"

Transcription

1 Impera've Programming Python Programs Interac)ve Input/Output One- Way and Two- Way if Statements for Loops User- Defined Func)ons Assignments Revisited and Parameter Passing

2 Python program line1 = 'Hello Python developer...' A Python program is a sequence of Python statements Stored in a text file called a Python module Executed using an IDE or from the command line line2 = 'Welcome to the world of Python!' print(line1) print(line2) line1 = 'Hello Python developer...' line2 = 'Welcome to the world of Python!' print(line1) print(line2) hello.py $ python hello.py Hello Python developer Welcome to the world of Python!

3 Built- in func'on print() Func)on print() prints its input argument to the IDLE window The argument can be any object: an integer, a float, a string, a list, o Strings are printed without quotes and to be read by people, rather than to be interpreted by Python, The string representa)on of the object is printed print(0) 0 print(0.0) 0.0 print('zero') zero print([0, 1, 'two']) [0, 1, 'two']

4 Built- in func'on input() Func)on input() requests and reads input from the user interac)vely It s (op)onal) input argument is the request message Typically used on the right side of an assignment statement When executed: 1. The input request message is printed 2. The user enters the input 3. The string typed by the user is assigned to the variable on the ley side of the assignment statement name = input('enter your name: ') Enter your name: Michael name 'Michael' ========= RESTART ============= Enter your first name: Michael Enter your last name: Jordan Hello Michael Jordan... Welcome to the world of Python! first = input('enter your first name: ') last = input('enter your last name: ') line1 = 'Hello + first + '' + last + ' ' print(line1) print('welcome to the world of Python!') input.py

5 Built- in func'on eval() Func)on input() evaluates anything the user enters as a string What if we want the user to interac)vely enter non- string input such as a number? Solu)on 1: Use type conversion Solu)on 2: Use func)on eval() o Takes a string as input and evaluates it as a Python expression age = input('enter your age: ') Enter your age: 18 age '18' int(age) 18 eval('18') 18 eval('age') '18' eval('[2,3+5]') [2, 8] eval('x') Traceback (most recent call last): File "<pyshell#14>", line 1, in <module> eval('x') File "<string>", line 1, in <module> NameError: name 'x' is not defined

6 Exercise Write a program that: 1. Requests the user s name 2. Requests the user s age 3. Computes the user s age one year from now and prints the message shown Enter your name: Marie Enter your age: 17 Marie, you will be 18 next year! name = input('enter your name: ') age = int(input('enter your age: ')) line = name + ', you will be ' + str(age+1) + ' next year!' print(line)

7 Exercise Write a program that: 1. Requests the user s name 2. Requests the user s age 3. Prints a message saying whether the user is eligible to vote or not Need a way to execute a Python statement if a condi)on is true

8 One- way if statement if <condition>: <indented code block> <non-indented statement> if temp > 86: print('it is hot!') print('be sure to drink liquids.') print('goodbye.') The value of temp is temp > 86: True print('it is hot!') False print('be sure to drink liquids.') Print('Goddbye.')

9 Exercises Write corresponding if statements: a) If age is greater than 62 then print 'You can get Social Security benefits b) If string 'large bonuses' appears in string report then print 'Vacation time! c) If hits is greater than 10 and shield is 0 then print "You're dead..." age report hits = = 45= 12'no bonuses this year' if shield age 'large > = 62: 0bonuses' in report: if hits print('you print('vacation > 10 and can shield get time!') Social == 0: Security benefits') print("you're dead...") age report = 65= 'large bonuses this year' You're if age 'large dead... > 62: bonuses' in report: hits, print('you print('vacation shield = 12, can 2get time!') Social Security benefits') if hits > 10 and shield == 0: print("you're dead...") You Vacation can get time! Social Security benefits

10 Indenta'on is cri'cal if temp > 86: print('it is hot!') print('drink liquids.') print('goodbye.') if temp > 86: print('it is hot!') print('drink liquids.') print('goodbye.') temp > 86: True temp > 86: True print('it is hot!') print('it is hot!') False False print('drink liquids.') print('drink liquids.') print('goddbye.') print('goddbye.')

11 Two- way if statement if <condition>: <indented code block 1> else: <indented code block 2> <non-indented statement> The value of temp is if temp > 86: print('it is hot!') print('be sure to drink liquids.') else: print('it is not hot.') print('bring a jacket.') print('goodbye.') False temp > 86: True print('it is not hot!') print('it is hot!') print('bring a jacket.') print('be sure to drink liquids.') print('bring a jacket.')

12 Exercise Write a program that: 1) Requests the user s name 2) Requests the user s age 3) Prints a message saying whether the user is eligible to vote or not Enter your name: Marie Enter your age: 17 Marie, you can't vote. ============RESTART================ Enter your name: Marie Enter your age: 18 Marie, you can vote. name = input('enter your name: ') age = eval(input('enter your age: ')) if age < 18: print(name + ", you can't vote.") else: print(name + ", you can vote.")

13 Execu'on control structures The one- way and two- way if statements are examples of execu)on control structures Execu)on control structures are programming language statements that control which statements are executed, i.e., the execu)on flow of the program The one- way and two- way if statements are, more specifically, condi)onal structures Itera)on structures are execu)on control structures that enable the repe))ve execu)on of a statement or a block of statements The for loop statement is an itera)on structure that executes a block of code for every item of a sequence

14 for loop Executes a block of code for every item of a sequence If sequence is a string, items are its characters (single- character strings) name = char = char = char = char = char = 'A p p l e' 'A' 'p' 'p' 'l' 'e' name = 'Apple' for char in name: print(char) A p p l e

15 for loop Executes a code block for every item of a sequence Sequence can be a string, a list, Block of code must be indented for <variable> in <sequence>: <indented code block > <non-indented code block> word = 'stop' for word in ['stop', 'desktop', 'post', 'top']: if 'top' in word: print(word) print('done.') word = word = word = 'desktop' 'post' 'top' stop desktop top Done.

16 Introduc)on to Compu)ng Using Python Built- in func'on range() Func)on range() is used to iterate over a sequence of numbers in a specified range To iterate over the n numbers 0, 1, 2,, n- 1 for i in range(n): To iterate over the n numbers i, i+1, i+2,, n- 1 for i in range(i, n): To iterate over the n numbers i, i+c, i+2c, i+3c,, n- 1 for i in range(i, n): for i in range(4): range(0): range(1): range(0, range(2, 3): 2): 6): 16, 4): 10): print(i)

17 Exercise Write for loops that will print the following sequences: a) 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 b) 1, 2, 3, 4, 5, 6, 7, 8, 9 c) 0, 2, 4, 6, 8 d) 1, 3, 5, 7, 9 e) 20, 30, 40, 50, 60

18 Defining new func'ons A few built- in func)ons we have seen: abs(), max(), len(), sum(), print() New func)ons can be defined using def def: func)on defini)on keyword f: name of func)on def f(x): res = x** return res x: variable name for input argument abs(-9) 9 max(2, 4) 4 lst = [2,3,4,5] len(lst) 4 sum(lst) 14 print() def f(x): res = 2*x + 10 return x** f(1) 11 f(3) 19 f(0) 10 return: specifies func)on output

19 print() versus return def f(x): res = x** return res def f(x): res = x** print(res) f(2) 14 2*f(2) 28 f(2) 14 2*f(2) 14 Traceback (most recent call last): File "<pyshell#56>", line 1, in <module> 2*f(2) TypeError: unsupported operand type(s) for *: 'int' and 'NoneType' Func)on returns value of res which can then be used in an expression Func)on prints value of res but does not return anything

20 Defining new func'ons The general format of a func)on defini)on is a c def <function name> (<0 or more variables>): <indented function body> b Let s develop func)on hyp() that: Takes two numbers as input (side lengths a and b of above right triangle ) Returns the length of the hypotenuse c hyp(3,4) 5.0 import math def hyp(a, b): res = math.sqrt(a**2 + b**2) return res

21 Exercise Write func)on hello() that: takes a name (i.e., a string) as input prints a personalized welcome message Note that the func)on does not return anything hello('julie') Welcome, Julie, to the world of Python. def hello(name): line = 'Welcome, ' + name + ', to the world of Python. Python.' print(line)

22 Exercise Write func)on rng() that: takes a list of numbers as input returns the range of the numbers in the list The range is the difference between the largest and smallest number in the list rng([4, 0, 1, -2]) 6 def rng(lst): res = max(lst) - min(lst) return res

23 Comments and docstrings Python programs should be documented So the developer who writes/maintains the code understands it So the user knows what the program does Comments help(f) Help on function f in module main : f(x) def f(x): res = x** return res # compute result # and return it def f(x): 'returns x**2 + 10' res = x** return res Docstring def f(x): 'returns x**2 + 10' res = x** # compute result return res # and return it help(f) Help on function f in module main : f(x) returns x**2 + 10

24 Assignment statement: a second look a b c d A variable does not exist before it is assigned 'three' <variable> = <expression> [1, 2, 3] a 1. <expression> is evaluated and its value put into an object of appropriate type 2. The object is assigned name <variable> a Traceback (most recent call last): File "<pyshell#66>", line 1, in <module> a NameError: name 'a' is not defined a = 3 b = c = 'three' d = [1, 2] + [3]

25 Mutable and immutable types a b c d 'three' [1, 2, 7, 3] The object (3) referred to by variable a does not change; instead, a refers to a new object (6) Integers are immutable a 3 a = 6 a 6 d [1, 2, 3] d[1] = 7 d [1, 7, 3] The object ([1, 2, 3]) referred to by d changes Lists are mutable

26 Assignment and mutability a b c d 9 3 [1, 7, 3] 9] 'three' a c and b d refer to the same integer list object object a 6 b 3.3 b = a b 6 a = 9 b 6 c = d c [1, 7, 3] d[2] = 9 c [1, 7, 9] a The now list refers that c to refers a new to object changes; (9); d b refers s)ll refers to the to same the old list object, (6) so it changes too Because integers lists are are mutable, immutable, a change a change to d to affects a does c not affect the value of b

27 Swapping values Have: a b tmp Want: a b a 3 b 6 tmp a, b = b = a= b b, a b = a a = tmp

28 Immutable parameter passing a x shell Func)on call g(a) 3 5 def g(x): x = 5 a = 3 g(a) Func)on Variable x g() inside did g() not, refers and cannot, to the modify object a the refers value to of a in the interac)ve shell. As if we executed x = a This is because a refers to an immutable object.

29 Mutable parameter passing lst l shell Func)on call h(lst) [1,2,3] [5,2,3] def h(l): l[0] = 5 lst = [1,2,3] h(lst) Func)on Variable l h() inside did h() modify refers the to value the object of lst lst in the refers interac)ve to shell. This As if is we because executed lst l and = lst l refer to an mutable object.

30 Exercise Write func)on swapfs() that: takes a list as input swaps the first and second element of the list, but only if the list has at least two elements The func)on does not return anything mylst = ['one', 'two', 'three'] swapfs(mylst) mylst ['two', 'one', 'three'] mylst = ['one'] swapfs(mylst) mylst ['one'] def swapfs(lst): if len(lst) > 1: lst[0], lst[1] = lst[1], lst[0]

Execu&on Control Structures

Execu&on Control Structures Execu&on Control Structures Condi)onal Structures Itera)on Pa9erns, Part I Two- Dimensional Lists while Loop Itera)on Pa9erns, Part II One- way if statement if :

More information

Introduction to Python

Introduction to Python Introduction to Python Reading assignment: Perkovic text, Ch. 1 and 2.1-2.5 Python Python is an interactive language. Java or C++: compile, run Also, a main function or method Python: type expressions

More information

Hello, World! An Easy Intro to Python & Programming. Jack Rosenthal

Hello, World! An Easy Intro to Python & Programming. Jack Rosenthal An Easy Intro to Python & Programming Don t just buy a new video game, make one. Don t just download the latest app, help design it. Don t just play on your phone, program it. No one is born a computer

More information

CSc 120. Introduc/on to Computer Programing II. Adapted from slides by Dr. Saumya Debray. 01- a: Python review

CSc 120. Introduc/on to Computer Programing II. Adapted from slides by Dr. Saumya Debray. 01- a: Python review CSc 120 Introduc/on to Computer Programing II Adapted from slides by Dr. Saumya Debray 01- a: Python review python review: variables, expressions, assignment 2 python basics x = 4 y = 5 z = x + y x 4 y

More information

Programming to Python

Programming to Python Programming to Python Sept., 5 th Slides by M. Stepp, M. Goldstein, M. DiRamio, and S. Shah Compiling and interpreting Many languages require you to compile (translate) your program into a form that the

More information

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

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D 1/58 Interactive use $ python Python 2.7.5 (default, Mar 9 2014, 22:15:05) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information.

More information

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

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D 1/60 Interactive use $ python Python 2.7.5 (default, Mar 9 2014, 22:15:05) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information.

More information

61A Lecture 2. Friday, August 28, 2015

61A Lecture 2. Friday, August 28, 2015 61A Lecture 2 Friday, August 28, 2015 Names, Assignment, and User-Defined Functions (Demo) Types of Expressions Primitive expressions: 2 add 'hello' Number or Numeral Name String Call expressions: max

More information

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

Sequence types. str and bytes are sequence types Sequence types have several operations defined for them. Sequence Types. Python Python Sequence Types Sequence types str and bytes are sequence types Sequence types have several operations defined for them Indexing Python Sequence Types Each element in a sequence can be extracted

More information

Lecture 4. Defining Functions

Lecture 4. Defining Functions Lecture 4 Defining Functions Academic Integrity Quiz Reading quiz about the course AI policy Go to http://www.cs.cornell.edu/courses/cs11110/ Click Academic Integrity in side bar Read and take quiz in

More information

University of Texas at Arlington, TX, USA

University of Texas at Arlington, TX, USA Dept. of Computer Science and Engineering University of Texas at Arlington, TX, USA Part of the science in computer science is the design and use of data structures and algorithms. As you go on in CS,

More information

CS177 Python Programming. Recita4on 2 - Compu4ng with Numbers

CS177 Python Programming. Recita4on 2 - Compu4ng with Numbers CS177 Python Programming Recita4on 2 - Compu4ng with Numbers Outline Data types. Variables Math library. Range Func4on What is data (in the context of programming)? Values that are stored and manipulated

More information

Here n is a variable name. The value of that variable is 176.

Here n is a variable name. The value of that variable is 176. UNIT II DATA, EXPRESSIONS, STATEMENTS 9 Python interpreter and interactive mode; values and types: int, float, boolean, string, and list; variables, expressions, statements, tuple assignment, precedence

More information

Lists, loops and decisions

Lists, loops and decisions Caltech/LEAD Summer 2012 Computer Science Lecture 4: July 11, 2012 Lists, loops and decisions Lists Today Looping with the for statement Making decisions with the if statement Lists A list is a sequence

More information

(Func&onal (Programming (in (Scheme)))) Jianguo Lu

(Func&onal (Programming (in (Scheme)))) Jianguo Lu (Func&onal (Programming (in (Scheme)))) Jianguo Lu 1 Programming paradigms Func&onal No assignment statement No side effect Use recursion Logic OOP AOP 2 What is func&onal programming It is NOT what you

More information

Not-So-Mini-Lecture 6. Modules & Scripts

Not-So-Mini-Lecture 6. Modules & Scripts Not-So-Mini-Lecture 6 Modules & Scripts Interactive Shell vs. Modules Launch in command line Type each line separately Python executes as you type Write in a code editor We use Atom Editor But anything

More information

Lecture 4: Basic I/O

Lecture 4: Basic I/O Lecture 4: Basic I/O CS1068+ Introductory Programming in Python Dr Kieran T. Herley Department of Computer Science University College Cork 2017-2018 KH (21/09/17) Lecture 4: Basic I/O 2017-2018 1 / 20

More information

Introduction to: Computers & Programming: Review prior to 1 st Midterm

Introduction to: Computers & Programming: Review prior to 1 st Midterm Introduction to: Computers & Programming: Review prior to 1 st Midterm Adam Meyers New York University Summary Some Procedural Matters Summary of what you need to Know For the Test and To Go Further in

More information

CSI31 Lecture 5. Topics: 3.1 Numeric Data Types 3.2 Using the Math Library 3.3 Accumulating Results: Factorial

CSI31 Lecture 5. Topics: 3.1 Numeric Data Types 3.2 Using the Math Library 3.3 Accumulating Results: Factorial CSI31 Lecture 5 Topics: 3.1 Numeric Data Types 3.2 Using the Math Library 3.3 Accumulating Results: Factorial 1 3.1 Numberic Data Types When computers were first developed, they were seen primarily as

More information

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A DEBUGGING TIPS COMPUTER SCIENCE 61A 1 Introduction Every time a function is called, Python creates what is called a stack frame for that specific function to hold local variables and other information.

More information

Chapter 5 Functions (Part 2) Hong Sun COSC 1436 Fall, 2017 Oct 18, 2017

Chapter 5 Functions (Part 2) Hong Sun COSC 1436 Fall, 2017 Oct 18, 2017 Chapter 5 Functions (Part 2) Hong Sun COSC 1436 Fall, 2017 Oct 18, 2017 Defining and Calling a Void Function Function Name Roles: python requires that you follow the same rules that you follow when naming

More information

Teaching London Computing

Teaching London Computing Teaching London Computing A Level Computer Science Topic 3: Advanced Programming in Python William Marsh School of Electronic Engineering and Computer Science Queen Mary University of London Aims Further

More information

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

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming Intro to Programming Unit 7 Intro to Programming 1 What is Programming? 1. Programming Languages 2. Markup vs. Programming 1. Introduction 2. Print Statement 3. Strings 4. Types and Values 5. Math Externals

More information

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming 2017 Table of contents 1 2 Integers and floats Integer int and float float are elementary numeric types in. integer >>> a=1 >>> a 1 >>> type (a) Integers and floats Integer int and float

More information

Control flow statements

Control flow statements Control flow statements It is important to make decisions in programming about how your code will be looked at. You may need to be selective, iterative or repetitive with the code statements. Python provides

More information

CS177 Python Programming. Recitation 2 - Computing with Numbers

CS177 Python Programming. Recitation 2 - Computing with Numbers CS177 Python Programming Recitation 2 - Computing with Numbers Outline Data types. Variables Math library. Range Function What is data (in the context of programming)? Values that are stored and manipulated

More information

Lab 1: Course Intro, Getting Started with Python IDLE. Ling 1330/2330 Computational Linguistics Na-Rae Han

Lab 1: Course Intro, Getting Started with Python IDLE. Ling 1330/2330 Computational Linguistics Na-Rae Han Lab 1: Course Intro, Getting Started with Python IDLE Ling 1330/2330 Computational Linguistics Na-Rae Han Objectives Course Introduction http://www.pitt.edu/~naraehan/ling1330/index.html Student survey

More information

The Practice of Computing Using PYTHON

The Practice of Computing Using PYTHON The Practice of Computing Using PYTHON William Punch Richard Enbody Chapter 6 Lists and Tuples 1 Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Data Structures 2 Data Structures

More information

CHAPTER 2: Introduction to Python COMPUTER PROGRAMMING SKILLS

CHAPTER 2: Introduction to Python COMPUTER PROGRAMMING SKILLS CHAPTER 2: Introduction to Python COMPUTER PROGRAMMING SKILLS 1439-1440 1 Outline 1. Introduction 2. Why Python? 3. Compiler and Interpreter 4. The first program 5. Comments and Docstrings 6. Python Indentations

More information

Introduction to Python Code Quality

Introduction to Python Code Quality Introduction to Python Code Quality Clarity and readability are important (easter egg: type import this at the Python prompt), as well as extensibility, meaning code that can be easily enhanced and extended.

More information

Fundamentals of Programming (Python) Getting Started with Programming

Fundamentals of Programming (Python) Getting Started with Programming Fundamentals of Programming (Python) Getting Started with Programming Ali Taheri Sharif University of Technology Some slides have been adapted from Python Programming: An Introduction to Computer Science

More information

Introduction to Bioinformatics

Introduction to Bioinformatics Introduction to Bioinformatics Variables, Data Types, Data Structures, Control Structures Janyl Jumadinova February 3, 2016 Data Type Data types are the basic unit of information storage. Instances of

More information

Basic Python Revision Notes With help from Nitish Mittal

Basic Python Revision Notes With help from Nitish Mittal Basic Python Revision Notes With help from Nitish Mittal HELP from Documentation dir(module) help() Important Characters and Sets of Characters tab \t new line \n backslash \\ string " " or ' ' docstring

More information

2

2 2 3 4 5 6 Open a terminal window and type python If on Windows open a Python IDE like IDLE At the prompt type hello world! >>> 'hello world!' 'hello world!' Python is an interpreted language The interpreter

More information

Chapter 5 Functions. Dr. Zhang COSC 1436 Summer, 2018 June 19, 2018

Chapter 5 Functions. Dr. Zhang COSC 1436 Summer, 2018 June 19, 2018 Chapter 5 Functions Dr. Zhang COSC 1436 Summer, 2018 June 19, 2018 while Loop Repetition Review A Condition-Controlled Loop Causes a statement or set of statements to repeat as long as a condition is true.

More information

Module 3: Strings and Input/Output

Module 3: Strings and Input/Output Module 3: Strings and Input/Output Topics: Strings and their methods Printing to standard output Reading from standard input Readings: ThinkP 8, 10 1 Strings in Python: combining strings in interesting

More information

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python CS95003 - Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / 2014 Subjects 1) Beginning with Python 2) Variables 3) Strings 4) Basic arithmetic operators 5) Flow control 6) Comparison

More information

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

Python I. Some material adapted from Upenn cmpe391 slides and other sources Python I Some material adapted from Upenn cmpe391 slides and other sources Overview Names & Assignment Data types Sequences types: Lists, Tuples, and Strings Mutability Understanding Reference Semantics

More information

Introduction to Python (All the Basic Stuff)

Introduction to Python (All the Basic Stuff) Introduction to Python (All the Basic Stuff) 1 Learning Objectives Python program development Command line, IDEs, file editing Language fundamentals Types & variables Expressions I/O Control flow Functions

More information

NESTED IF STATEMENTS AND STRING/INTEGER CONVERSION

NESTED IF STATEMENTS AND STRING/INTEGER CONVERSION LESSON 15 NESTED IF STATEMENTS AND STRING/INTEGER CONVERSION OBJECTIVE Learn to work with multiple criteria if statements in decision making programs as well as how to specify strings versus integers in

More information

Lists How lists are like strings

Lists How lists are like strings Lists How lists are like strings A Python list is a new type. Lists allow many of the same operations as strings. (See the table in Section 4.6 of the Python Standard Library Reference for operations supported

More information

Python 1: Intro! Max Dougherty Andrew Schmitt

Python 1: Intro! Max Dougherty Andrew Schmitt Python 1: Intro! Max Dougherty Andrew Schmitt Computational Thinking Two factors of programming: The conceptual solution to a problem. Solution syntax in a programming language BJC tries to isolate and

More information

Common Loop Algorithms 9/21/16 42

Common Loop Algorithms 9/21/16 42 Common Loop Algorithms 9/21/16 42 Common Loop Algorithms 1. Sum and Average Value 2. Coun4ng Matches 3. Promp4ng un4l a Match Is Found 4. Maximum and Minimum 5. Comparing Adjacent Values 9/21/16 43 Sum

More information

ECS Baruch Lab 3 Spring 2019 Name

ECS Baruch Lab 3 Spring 2019 Name ECS 102 - Baruch Lab 3 Spring 2019 Name I. You can't ask a computer to do something you can't do. Now it is your turn to step through a program, without a computer. DO NOT ENTER THIS PROGRAM ON THE COMPUTER.

More information

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

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

Getting Started with Python

Getting Started with Python Fundamentals of Programming (Python) Getting Started with Python Sina Sajadmanesh Sharif University of Technology Some slides have been adapted from Python Programming: An Introduction to Computer Science

More information

A Func'onal Introduc'on. COS 326 David Walker Princeton University

A Func'onal Introduc'on. COS 326 David Walker Princeton University A Func'onal Introduc'on COS 326 David Walker Princeton University Thinking Func'onally In Java or C, you get (most) work done by changing something temp = pair.x; pair.x = pair.y; pair.y = temp; commands

More information

Final Exam(sample), Fall, 2014

Final Exam(sample), Fall, 2014 Final Exam(sample), Fall, 2014 Date: Dec 4 th, 2014 Time: 1.25 hours (1.00 a.m. 2:15 p.m.) Total: 100 points + 20 bonus Problem 1 T/F 2 Choice 3 Output Points 16 16 48 4 Programming 20 5 Bonus 20 Total

More information

Outline. Simple types in Python Collections Processing collections Strings Tips. 1 On Python language. 2 How to use Python. 3 Syntax of Python

Outline. Simple types in Python Collections Processing collections Strings Tips. 1 On Python language. 2 How to use Python. 3 Syntax of Python Outline 1 On Python language 2 3 4 Marcin Młotkowski Object oriented programming 1 / 52 On Python language The beginnings of Pythons 90 CWI Amsterdam, Guido van Rossum Marcin Młotkowski Object oriented

More information

Programming for Engineers in Python. Recitation 1

Programming for Engineers in Python. Recitation 1 Programming for Engineers in Python Recitation 1 Plan Administration: Course site Homework submission guidelines Working environment Python: Variables Editor vs. shell Homework 0 Python Cont. Conditional

More information

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

Review Sheet for Midterm #1 COMPSCI 119 Professor William T. Verts Review Sheet for Midterm #1 COMPSCI 119 Professor William T. Verts Simple Data Types There are a number of data types that are considered primitive in that they contain only a single value. These data

More information

Getting Started Values, Expressions, and Statements CS GMU

Getting Started Values, Expressions, and Statements CS GMU Getting Started Values, Expressions, and Statements CS 112 @ GMU Topics where does code go? values and expressions variables and assignment 2 where does code go? we can use the interactive Python interpreter

More information

A Little Python Part 1. Introducing Programming with Python

A Little Python Part 1. Introducing Programming with Python A Little Python Part 1 Introducing Programming with Python Preface Not a complete course in a programming language Many details can t be covered Need to learn as you go My programming style is not considered

More information

Lab 4 Fruitful Functions

Lab 4 Fruitful Functions Lab 4 Fruitful Functions September 19, 2018 1 ME 30 Lab 4 - Functions and Style Description and Summary: >A function in programming is a block of code that performs some task. Functions are a way to organize

More information

Lab 6: Data Types, Mutability, Sorting. Ling 1330/2330: Computational Linguistics Na-Rae Han

Lab 6: Data Types, Mutability, Sorting. Ling 1330/2330: Computational Linguistics Na-Rae Han Lab 6: Data Types, Mutability, Sorting Ling 1330/2330: Computational Linguistics Na-Rae Han Objectives Data types and conversion Tuple Mutability Sorting: additional parameters Text processing overview

More information

Exercise: The basics - variables and types

Exercise: The basics - variables and types Exercise: The basics - variables and types Aim: Introduce python variables and types. Issues covered: Using the python interactive shell In the python interactive shell you don t need print Creating variables

More information

Begin to code with Python Obtaining MTA qualification expanded notes

Begin to code with Python Obtaining MTA qualification expanded notes Begin to code with Python Obtaining MTA qualification expanded notes The Microsoft Certified Professional program lets you obtain recognition for your skills. Passing the exam 98-381, "Introduction to

More information

List of squares. Program to generate a list containing squares of n integers starting from 0. list. Example. n = 12

List of squares. Program to generate a list containing squares of n integers starting from 0. list. Example. n = 12 List of squares Program to generate a list containing squares of n integers starting from 0 Example list n = 12 squares = [] for i in range(n): squares.append(i**2) print(squares) $ python3 squares.py

More information

Control Structures. A program can proceed: Sequentially Selectively (branch) - making a choice Repetitively (iteratively) - looping

Control Structures. A program can proceed: Sequentially Selectively (branch) - making a choice Repetitively (iteratively) - looping Control Structures A program can proceed: Sequentially Selectively (branch) - making a choice Repetitively (iteratively) - looping Conditional Execution if is a reserved word The most basic syntax for

More information

https://lambda.mines.edu Why study Python in Principles of Programming Languages? Multi-paradigm Object-oriented Functional Procedural Dynamically typed Relatively simple with little feature multiplicity

More information

Programming for Engineers in Python. Autumn

Programming for Engineers in Python. Autumn Programming for Engineers in Python Autumn 2011-12 Plan Administration: Course site Homework submission guidelines Working environment Python: Variables Editor vs. shell Homework 0 Python Cont. Conditional

More information

Strings. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

Strings. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington Strings CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1 Strings Store Text In the same way that int and float are designed to store numerical values,

More information

BBM 101 Introduc/on to Programming I Fall 2014, Lecture 3. Aykut Erdem, Erkut Erdem, Fuat Akal

BBM 101 Introduc/on to Programming I Fall 2014, Lecture 3. Aykut Erdem, Erkut Erdem, Fuat Akal BBM 101 Introduc/on to Programming I Fall 2014, Lecture 3 Aykut Erdem, Erkut Erdem, Fuat Akal 1 Today Introduc/on to Programming Basic Concepts Developing Algorithms Crea

More information

CS1 Lecture 3 Jan. 22, 2018

CS1 Lecture 3 Jan. 22, 2018 CS1 Lecture 3 Jan. 22, 2018 Office hours for me and for TAs have been posted, locations will change check class website regularly First homework available, due Mon., 9:00am. Discussion sections tomorrow

More information

Python for Non-programmers

Python for Non-programmers Python for Non-programmers A Gentle Introduction 1 Yann Tambouret Scientific Computing and Visualization Information Services & Technology Boston University 111 Cummington St. yannpaul@bu.edu Winter 2013

More information

Python Programming. Introduction Part II

Python Programming. Introduction Part II Python Programming Introduction Part II Type Conversion One data type > another data type Example: int > float, int > string. >>> a = 5.5 >>> b = int(a) >>> print(b) 5 >>>> print(a) 5.5 Conversion from

More information

Introduction to Python

Introduction to Python Introduction to Python CB2-101 Introduction to Scientific Computing November 11 th, 2014 Emidio Capriotti http://biofold.org/emidio Division of Informatics Department of Pathology Python Python high-level

More information

Python language: Basics

Python language: Basics Python language: Basics The FOSSEE Group Department of Aerospace Engineering IIT Bombay Mumbai, India FOSSEE Team (FOSSEE IITB) Basic Python 1 / 45 Outline 1 Data types Numbers Booleans Strings 2 Operators

More information

Python Intro GIS Week 1. Jake K. Carr

Python Intro GIS Week 1. Jake K. Carr GIS 5222 Week 1 Why Python It s simple and easy to learn It s free - open source! It s cross platform IT S expandable!! Why Python: Example Consider having to convert 1,000 shapefiles into feature classes

More information

Part III Appendices 165

Part III Appendices 165 Part III Appendices 165 Appendix A Technical Instructions Learning Outcomes This material will help you learn how to use the software you need to do your work in this course. You won t be tested on it.

More information

Python: common syntax

Python: common syntax Lab 09 Python! Python Intro Main Differences from C++: True and False are capitals Python floors (always down) with int division (matters with negatives): -3 / 2 = -2 No variable data types or variable

More information

Control structure: Repetition - Part 1

Control structure: Repetition - Part 1 Control structure: Repetition - Part 1 01204111 Computers and Programming Chalermsak Chatdokmaiprai Department of Computer Engineering Kasetsart University Cliparts are taken from http://openclipart.org

More information

Decisions, Decisions. Testing, testing C H A P T E R 7

Decisions, Decisions. Testing, testing C H A P T E R 7 C H A P T E R 7 In the first few chapters, we saw some of the basic building blocks of a program. We can now make a program with input, processing, and output. We can even make our input and output a little

More information

Programming with Python

Programming with Python Programming with Python Lecture 3: Python Functions IPEC Winter School 2015 B-IT Dr. Tiansi Dong & Dr. Joachim Köhler Python Functions arguments return obj Global vars Files/streams Function Global vars

More information

Converting File Input

Converting File Input Converting File Input As with the input func.on, the readline() method can only return strings If the file contains numerical data, the strings must be converted to the numerical value using the int()

More information

Python BASICS. Introduction to Python programming, basic concepts: formatting, naming conventions, variables, etc.

Python BASICS. Introduction to Python programming, basic concepts: formatting, naming conventions, variables, etc. Python BASICS Introduction to Python programming, basic concepts: formatting, naming conventions, variables, etc. Identikit First appeared in 1991 Designed by Guido van Rossum General purpose High level

More information

University of Washington CSE 140 Introduction to Data Programming Winter Midterm exam. February 6, 2013

University of Washington CSE 140 Introduction to Data Programming Winter Midterm exam. February 6, 2013 University of Washington CSE 140 Introduction to Data Programming Winter 2013 Midterm exam February 6, 2013 Name: Solutions UW Net ID (username): This exam is closed book, closed notes. You have 50 minutes

More information

Introduction to Programming in Python (2)

Introduction to Programming in Python (2) Introduction to Programming in Python (2) Steve Renals s.renals@ed.ac.uk ICL 29 September 2005 Conditionals Loops Function basics Variables and functions Functional programming Designing functions Python

More information

Flow Control: Branches and loops

Flow Control: Branches and loops Flow Control: Branches and loops In this context flow control refers to controlling the flow of the execution of your program that is, which instructions will get carried out and in what order. In the

More information

Local defini1ons. Func1on mul1ples- of

Local defini1ons. Func1on mul1ples- of Local defini1ons The func1ons and special forms we ve seen so far can be arbitrarily nested except define and check- expect. So far, defini.ons have to be made at the top level, outside any expression.

More information

CSc 110, Spring Lecture 24: print revisited, tuples cont.

CSc 110, Spring Lecture 24: print revisited, tuples cont. CSc 110, Spring 2017 Lecture 24: print revisited, tuples cont. 1 print 2 print revisited We often convert to strings when printing variables: print("the sum is " + str(sum)) This is not always necessary.

More information

CMSC201 Computer Science I for Majors

CMSC201 Computer Science I for Majors CMSC201 Computer Science I for Majors Lecture 08 Lists Constants Last Class We Covered More on while loops Sentinel loops Boolean flags 2 Any Questions from Last Time? 3 Today s Objectives To learn about

More information

Python Input, output and variables. Lecture 23 COMPSCI111/111G SS 2018

Python Input, output and variables. Lecture 23 COMPSCI111/111G SS 2018 Python Input, output and variables Lecture 23 COMPSCI111/111G SS 2018 1 Today s lecture What is Python? Displaying text on screen using print() Variables Numbers and basic arithmetic Getting input from

More information

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

History Installing & Running Python Names & Assignment Sequences types: Lists, Tuples, and Strings Mutability History Installing & Running Python Names & Assignment Sequences types: Lists, Tuples, and Strings Mutability Some material adapted from Upenn cmpe391 slides and other sources Invented in the Netherlands,

More information

CS 61A Interpreters, Tail Calls, Macros, Streams, Iterators. Spring 2019 Guerrilla Section 5: April 20, Interpreters.

CS 61A Interpreters, Tail Calls, Macros, Streams, Iterators. Spring 2019 Guerrilla Section 5: April 20, Interpreters. CS 61A Spring 2019 Guerrilla Section 5: April 20, 2019 1 Interpreters 1.1 Determine the number of calls to scheme eval and the number of calls to scheme apply for the following expressions. > (+ 1 2) 3

More information

Introduction to Computation for the Humanities and Social Sciences. CS 3 Chris Tanner

Introduction to Computation for the Humanities and Social Sciences. CS 3 Chris Tanner Introduction to Computation for the Humanities and Social Sciences CS 3 Chris Tanner Lecture 5 But I ve got a blank space [in my text String] baby Taylor Swift Lecture 5 Reading Input From Users Reading

More information

How To Think Like A Computer Scientist, chapter 3; chapter 6, sections

How To Think Like A Computer Scientist, chapter 3; chapter 6, sections 6.189 Day 3 Today there are no written exercises. Turn in your code tomorrow, stapled together, with your name and the file name in comments at the top as detailed in the Day 1 exercises. Readings How

More information

CMPT 120 Lists and Strings. Summer 2012 Instructor: Hassan Khosravi

CMPT 120 Lists and Strings. Summer 2012 Instructor: Hassan Khosravi CMPT 120 Lists and Strings Summer 2012 Instructor: Hassan Khosravi All of the variables that we have used have held a single item One integer, floating point value, or string often you find that you want

More information

Lecture 02 Making Decisions: Conditional Execution

Lecture 02 Making Decisions: Conditional Execution Lecture 02 Making Decisions: Conditional Execution 1 Flow of Control Flow of control = order in which statements are executed By default, a program's statements are executed sequentially, from top to bottom.

More information

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

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines. Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

61A LECTURE 22 TAIL CALLS, ITERATORS. Steven Tang and Eric Tzeng July 30, 2013

61A LECTURE 22 TAIL CALLS, ITERATORS. Steven Tang and Eric Tzeng July 30, 2013 61A LECTURE 22 TAIL CALLS, ITERATORS Steven Tang and Eric Tzeng July 30, 2013 Announcements Homework 12 due Thursday, not Monday. Take the time to get started on the project instead! Almost done with Scheme

More information

Lecture 7. Memory in Python

Lecture 7. Memory in Python Lecture 7 Memory in Python Announcements For This Lecture Readings Reread Chapter 3 No reading for Thursday Lab Work on Assignment Credit when submit A Nothing else to do Assignment Moved to Fri, Sep.

More information

Scripting Languages. Python basics

Scripting Languages. Python basics Scripting Languages Python basics Interpreter Session: python Direct conversation with python (>>>) Python 3.5.2 (default, Nov 23 2017, 16:37:01) [GCC 5.4.0 20160609] on linux Type "help", "copyright",

More information

ECS Baruch Lab 2 Fall 2019 Name

ECS Baruch Lab 2 Fall 2019 Name ECS 102 - Baruch Lab 2 Fall 2019 Name I. Review Recall that in lab 1, you created a folder on your H: drive, Document/Apps-SU/Python Programs The reason you need to save programs here on the lab computers

More information

Lecture 3. Functions & Modules

Lecture 3. Functions & Modules Lecture 3 Functions & Modules Labs this Week Lab 1 is due at the beginning of your lab If it is not yet by then, you cannot get credit Only exception is for students who added late (Those students should

More information

Python for Beginners. John B. Johnston Bioinforma3cs Engineer

Python for Beginners. John B. Johnston Bioinforma3cs Engineer Python for Beginners John B. Johnston Bioinforma3cs Engineer Python What is it? Python is an interpreted, interac3ve programming language that incorporates external reusable modules. Python is widely used

More information

There are two ways to use the python interpreter: interactive mode and script mode. (a) open a terminal shell (terminal emulator in Applications Menu)

There are two ways to use the python interpreter: interactive mode and script mode. (a) open a terminal shell (terminal emulator in Applications Menu) I. INTERACTIVE MODE VERSUS SCRIPT MODE There are two ways to use the python interpreter: interactive mode and script mode. 1. Interactive Mode (a) open a terminal shell (terminal emulator in Applications

More information

6. Data Types and Dynamic Typing (Cont.)

6. Data Types and Dynamic Typing (Cont.) 6. Data Types and Dynamic Typing (Cont.) 6.5 Strings Strings can be delimited by a pair of single quotes ('...'), double quotes ("..."), triple single quotes ('''...'''), or triple double quotes ("""...""").

More information

CS1 Lecture 3 Jan. 18, 2019

CS1 Lecture 3 Jan. 18, 2019 CS1 Lecture 3 Jan. 18, 2019 Office hours for Prof. Cremer and for TAs have been posted. Locations will change check class website regularly First homework assignment will be available Monday evening, due

More information

CMSC201 Computer Science I for Majors

CMSC201 Computer Science I for Majors CMSC201 Computer Science I for Majors Lecture 08 Lists Constants Last Class We Covered More on while loops Sentinel loops Priming Reads Boolean flags 2 Any Questions from Last Time? 3 Today s Objectives

More information