Python Boot Camp. Day 3

Similar documents
CSC 148 Lecture 3. Dynamic Typing, Scoping, and Namespaces. Recursion

CS61A Notes Week 13: Interpreters

Introduction to Python (All the Basic Stuff)

Conditionals and Recursion. Python Part 4

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

CS1 Lecture 3 Jan. 22, 2018

Introduction to Bioinformatics

Selection Statement ( if )

CSC326 Python Imperative Core (Lec 2)

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

MITOCW watch?v=0jljzrnhwoi

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

Decision structures. A more complex decision structure is an if-else-statement: if <condition>: <body1> else: <body2>

Typescript on LLVM Language Reference Manual

Assignment 7: functions and closure conversion (part 1)

CS1 Lecture 5 Jan. 26, 2018

Text Input and Conditionals

Python for Informatics

TAIL RECURSION, SCOPE, AND PROJECT 4 11

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

Pull Lecture Materials and Open PollEv. Poll Everywhere: pollev.com/comp110. Lecture 12. else-if and while loops. Once in a while

Part 1 (80 points) Multiple Choice Questions (20 questions * 4 points per question = 80 points)

CS1 Lecture 5 Jan. 25, 2019

TUPLES AND RECURSIVE LISTS 5

CS1 Lecture 3 Jan. 18, 2019

CS61A Notes Week 1A: Basics, order of evaluation, special forms, recursion

Fall 2017 Discussion 7: October 25, 2017 Solutions. 1 Introduction. 2 Primitives

DM536 Introduction to Programming. Peter Schneider-Kamp.

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

Intro. Scheme Basics. scm> 5 5. scm>

Functions and Recursion

COP4020 Programming Assignment 1 - Spring 2011

AN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University

CS 231 Data Structures and Algorithms, Fall 2016

CS61A Discussion Notes: Week 11: The Metacircular Evaluator By Greg Krimer, with slight modifications by Phoebus Chen (using notes from Todd Segal)

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

CSCI 1101B. Boolean Expressions

Programming with Math and Logic

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

Fall 2018 Discussion 8: October 24, 2018 Solutions. 1 Introduction. 2 Primitives

Lecture 2: SML Basics

The SPL Programming Language Reference Manual

CS1 Lecture 13 Feb. 13, 2019

Introduction to Python programming, II

About Python. Python Duration. Training Objectives. Training Pre - Requisites & Who Should Learn Python

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

Assignment 7: functions and closure conversion

EECS1710. Announcements. Labtests have been returned Term Test #01 marking is in progress. Next Labtest: Thu Oct 23/Fri Oct 24

DM536 Introduction to Programming. Peter Schneider-Kamp.

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

1 Truth. 2 Conditional Statements. Expressions That Can Evaluate to Boolean Values. Williams College Lecture 4 Brent Heeringa, Bill Jannen

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Name: Magpie Chatbot Lab: Student Guide. Introduction

Lab1. Introduction to Python. Lab 4: Selection Statement. Eng. Mai Z. Alyazji

Python for Non-programmers

The current topic: Python. Announcements. Python. Python

Introduction to Python programming, II

APCS Semester #1 Final Exam Practice Problems

Self-test Programming Fundamentals

HOUR 4 Understanding Events

Chapter 3 - Simple JavaScript - Programming Basics. Lesson 1 - JavaScript: What is it and what does it look like?

PYTHON. p ykos vtawynivis. Second eciitiovl. CO Ve, WESLEY J. CHUN

Python Basics. Lecture and Lab 5 Day Course. Python Basics

Fundamentals of Programming Session 13

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

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

CS 102 Lab 3 Fall 2012

DM502 Programming A. Peter Schneider-Kamp.

The PCAT Programming Language Reference Manual

Good Luck! CSC207, Fall 2012: Quiz 1 Duration 25 minutes Aids allowed: none. Student Number:

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

Lecture 3: Recursion; Structural Induction

Part 6b: The effect of scale on raster calculations mean local relief and slope

Accelerating Information Technology Innovation

Programming in Python 3

EXPRESSIONS, STATEMENTS, AND FUNCTIONS 1

Try typing the following in the Python shell and press return after each calculation. Write the answer the program displays next to the sums below.

Overview of Semantic Analysis. Lecture 9

Algorithms and Data Structures

DATABASE AUTOMATION USING VBA (ADVANCED MICROSOFT ACCESS, X405.6)

SCHEME 10 COMPUTER SCIENCE 61A. July 26, Warm Up: Conditional Expressions. 1. What does Scheme print? scm> (if (or #t (/ 1 0)) 1 (/ 1 0))

Pace University. Fundamental Concepts of CS121 1

CSCI 2041: Basic OCaml Syntax and Features

Title:[ Variables Comparison Operators If Else Statements ]

C ONTROL AND H IGHER O RDER F UNCTIONS

Programming Languages

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

RACKET BASICS, ORDER OF EVALUATION, RECURSION 1

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

Semantic Analysis. Lecture 9. February 7, 2018

Next: What s in a name? Programming Languages. Data model in functional PL. What s in a name? CSE 130 : Fall Lecture 13: What s in a Name?

Chapter 2: Functions and Control Structures

CS1110 Lab 6 (Mar 17-18, 2015)

1007 Imperative Programming Part II

6.001 Notes: Section 15.1

CSE 115. Introduction to Computer Science I

Selection statements. CSE 1310 Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington

CS 112: Intro to Comp Prog

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

Memory Management and Run-Time Systems

Transcription:

Python Boot Camp Day 3

Agenda 1. Review Day 2 Exercises 2.Getting input from the user, Interview Lab 3.Scopes 4.Conditionals, Mood Ring Lab 5.Recursion, Recursion Lab

Day 2 Exercises Think Python Ch. 3 Functions can call other functions Passing functions as arguments

Day 2 Exercises Think Python Ch. 4 Generalization! Refactoring!

Getting Input from the User raw_input([prompt]) raw_input() takes the user s input, converts it to a string (!), stripping off the trailing newline, and returns the string. set raw_input() to a variable in order to handle it

Let s try it out... Write a function called interview that asks the following questions: What is your first name? How many pets do you have? How likely do you think it is to rain today? (Enter as a floating point number.) After the user (you) answers each question, the function should print out a few sentences repeating what the user entered.

Interview Script

Scopes and Namespaces When you create/assign/define a name, Python creates or looks up the name in a namespace. A namespace is the place where the name lives. In Scheme, it s called the environment. When you create a name, you either define the meaning of the name or refer to a definition somewhere else. Ex: a = b Where you physically assign a name, determines the name s scope Ex: Functions create nested namespaces The scope of a definition is the part of the program over which the definition holds. Variables must be assigned before they are referenced in order to be used. Adapted from CS9H

Python Scope Basics 1. All names are scoped the same Different from Java or C++ where the variable foo and class foo are considered two different things A name can only refer to one thing at a time Adapted from CS9H

Example What does each print statement produce? Write down your predictions and then try it in the interpreter. 4 <function spoon at 08xe630> foo Adapted from CS9H

Python Scope Basics 2. The Scope of a name is its enclosing function or class In the function genius, the second line binds x to 4, and the third line refers to x in the local namespace The scope of x is the genius function Adapted from CS9H

Another Example Let s look at the flow of execution. two plus two is 4 two plus two is 3 4 two plus two is 4 two plus two is 5 Adapted from CS9H

Python Scope Basics 3.Names belong to the namespaces where they are bound If a binding for a variable appears anywhere inside a function, that variable name is local to the function, even if it is never executed. Adapted from CS9H

Last Example What will the two function calls produce? spam(1) causes an UnboundLocalError because x is bound to 5 within spam() even though it is not executed spam(6) prints 5 because it passes 6 in as y, which is greater than 3, which assigns x to 5 before printing x Adapted from CS9H

Python Scope Basics Summary We usually talk about variables as being either global or local (in scope) Assigned variables are local by default unless declared global. The enclosing module is the global scope. Module = file you are working in, for example. The global scope only spans a single file. Each call to a function creates a new local scope. Python will try to look for variables from the inside out: local, enclosing function, global (module), built-in module Adapted from Learning Python by Mark Lutz

Conditionals Boolean Logic Logical Operators (previously talked about math operators) Conditional Statements Chained Conditionals Nested Conditionals

Boolean Logic A boolean expression is an expression that evaluates to either true or false. 7 > 3 evalutes to True 4 >= 5 evalutes to False 3!= 5 evalutes to True 1 + 1 == 3 evalutes to False comparison operators

Logical Operators and, or, not evalute the way that you would expect in English and evalutes as True if both expressions are true or evalutes as True is either expression is true not evalutes as True if the expression is not true not (8 > 10) is True not (8 < 10) is False

Logical Operators Non-zero numbers evalute as true not 17 is False And of course you can combine them! not (True and False) is True not (False or True) is False

How do these statements evaluate? False and True True or False and True not True and not False (6**2) or False and True 0 and 1 or False and False

Conditional Statements So far we ve written scripts or code that executes more or less in order from top to bottom. Conditional statements allow us to write code that behaves differently depending on the given values. if, else statements

Conditional Statements What will this print?

The return statement Return is not the same as print Ok, so how do we print the result? Allows you to terminate the execution of a function before you reach the end. If you detect an error, for example You can only return once from a function.

elif Chained Conditionals

Nested Conditionals

Mood Ring Lab Write a script that tells the user how he/she is feeling today. The script should: Print a greeting to the user with his or her name Tell the user if he/she is happy, neutral, or sad (at random). Or any three emotions. Hint: use the random module Try to encapsulate your code inside functions Use your neighbors for help. Adapted from Python Programming for the Absolute Beginner

Recursion A function can call another function. A function can also call itself. What would happen if we executed this script?

Infinite Recursion Oh no! The output repeats forever! How do we fix this? Include a conditional statement or a loop and a base case. Generally, recursive functions work like this: If the problem can be solved immediately, the function returns the result. If the problem cannot be solved now, the function reduces it to a smaller but similar problem and calls itself to solve the smaller problem.

Infinite Recursion Fixed

Recursion Lab Write a script that uses recursion to calculate the factorial of a number. Create a function called main that: Gets a non-negative number from the user and Calls another function which calculates the factorial of the number and Prints the result Hint: The factorial (n!) of a nonnegative number can be defined by: If n = 0, then n! is 1 If n > 0, then n! is 1 * 2 * 3 *...n

Recursion Lab Volunteers want to share their script?

Recursion Lab

Exercises Read Think Python Ch. 5 & 6 Do the exercises in Think Python Ch. 5 and Ch. 6, but not exercise 6.4