Introduction to Python (All the Basic Stuff)

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

Text Input and Conditionals

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

Flow Control: Branches and loops

CS1 Lecture 5 Jan. 26, 2018

ENGR 101 Engineering Design Workshop

CS1 Lecture 3 Jan. 22, 2018

Getting Started. Excerpted from Hello World! Computer Programming for Kids and Other Beginners

Python Programming. Introduction Part II

Hello World! Computer Programming for Kids and Other Beginners. Chapter 1. by Warren Sande and Carter Sande. Copyright 2009 Manning Publications

CS1 Lecture 5 Jan. 25, 2019

Expressions and Variables

Python Unit

Introduction to Scientific Python, CME 193 Jan. 9, web.stanford.edu/~ermartin/teaching/cme193-winter15

Control Structures 1 / 17

CS1 Lecture 3 Jan. 18, 2019

Programming with Python

A Little Python Part 1. Introducing Programming with Python

1. BASICS OF PYTHON. JHU Physics & Astronomy Python Workshop Lecturer: Mubdi Rahman

Notes on Chapter 1 Variables and String

Introduction to Bioinformatics

CMSC 201 Computer Science I for Majors

The current topic: Python. Announcements. Python. Python

Course May 18, Advanced Computational Physics. Course Hartmut Ruhl, LMU, Munich. People involved. SP in Python: 3 basic points

Week 2: Quick and Dirty Jython Refresher

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

Chapter 5 : Informatics practices. Conditional & Looping Constructs. Class XI ( As per CBSE Board)

Beyond Blocks: Python Session #1

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

Session 1: Introduction to Python from the Matlab perspective. October 9th, 2017 Sandra Diaz

Python for Non-programmers

Control of Flow. There are several Python expressions that control the flow of a program. All of them make use of Boolean conditional tests.

Getting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an . Michigan State University CSE 231, Fall 2013

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

Python notes from codecademy. Intro: Python can be used to create web apps, games, even a search engine.

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

The Big Python Guide

Algorithms and Programming I. Lecture#12 Spring 2015

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

CISC-124. Casting. // this would fail because we can t assign a double value to an int // variable

Intro. Speed V Growth

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

Python Boot Camp. Day 3

Static Methods. Why use methods?

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

Fundamentals of Programming. Lecture 1: Introduction + Basic Building Blocks of Programming

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

2

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

Comp 151. Control structures.

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

Programming. We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems.

If Statements, For Loops, Functions

Python Games. Session 1 By Declan Fox

Outline. Announcements. Homework 2. Boolean expressions 10/12/2007. Announcements Homework 2 questions. Boolean expression

LECTURE 1. Getting Started with Python

1007 Imperative Programming Part II

CS 115 Lecture 4. More Python; testing software. Neil Moore

Downloaded from Chapter 2. Functions

Lists, loops and decisions

Iteration. Chapter 7. Prof. Mauro Gaspari: Mauro Gaspari - University of Bologna -

Java Review. Fundamentals of Computer Science

MEIN 50010: Python Flow Control

PYTHON FOR MEDICAL PHYSICISTS. Radiation Oncology Medical Physics Cancer Care Services, Royal Brisbane & Women s Hospital

cs1114 REVIEW of details test closed laptop period

T H E I N T E R A C T I V E S H E L L

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

1 Strings (Review) CS151: Problem Solving and Programming

Programming to Python

Jython. secondary. memory

Visualize ComplexCities

Python: common syntax

Table of Contents EVALUATION COPY

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

Getting Started with Python

Introduction to Python for IBM i

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

Comp Exam 1 Overview.

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

Lecture Transcript While and Do While Statements in C++

Programming for Engineers in Python. Autumn

Python for Analytics. Python Fundamentals RSI Chapters 1 and 2

SAMS Programming - Section C. Lecture 1: Introduction + Basic Building Blocks of Programming

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

CS Summer 2013

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

Chapter 5 Methods. public class FirstMethod { public static void main(string[] args) { double x= -2.0, y; for (int i = 1; i <= 5; i++ ) { y = f( x );

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

Conditionals & Loops /

CIS192: Python Programming

Execution order. main()

Constants. Variables, Expressions, and Statements. Variables. x = 12.2 y = 14 x = 100. Chapter

Comp 151. Control structures.

SAMS Programming A/B. Lecture #1 Introductions July 3, Mark Stehlik

CSSE 120 Introduction to Software Development Practice for Test 1 paper-and-pencil part Page 1 of 6

Programming for Engineers in Python. Recitation 1

Python for C programmers

Python 1: Intro! Max Dougherty Andrew Schmitt

Invent Your Own Computer Games with Python

CME 193: Introduction to Scientific Python Lecture 1: Introduction

Transcription:

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 & scoping 2

Python Environment You ve gotten Python on your machine Run from command line OR Use an Integrated Development Environment (IDE) 3

Command Line (Windows) Python command Windows command shell 4

Command Line (Mac) 5

IDLE IDE 6

Other Python IDEs Pydev (Eclipse) PyCharm Wing Spyder Python 7

Creating/Editing Programs Text editor: Notepad, WordPad, Sublime text, Emacs, Doesn t work ie, not interactive 8

Running Programs Running an existing file 9

Tips & tricks (Windows) Shift right click in background of window to get menu with Open command window here operation Then run python foobar.py 10

Types, Variables int, float, str No variable declarations Weakly typed language x = 1 x = hello print x Boolean values True and False 11

Math Expressions +, -, *, /, %, ** (% - remainder, ** - exponentiation) 5 % 3 is 3 / 2 is 3 / 2.0 is Assignment statements x = (a + 10) * (b**3 / d * f) tax = tax +.01 12

Type Conversions You have two integers a and b You want a/b (the floating point value) a / float(b) Mixed type expression, the integer is converted to a float: 17.5 / 6 13

Output print Hello print Hello print distance print a, b print The value is, val print a, Suppresses the newline Version 3 print( Hello ) print(a, b) print(a, end= ) Suppresses the newline 14

Input (Python 2) Reading strings firstname = raw_input( Enter your first name ) Reading numbers age = input( How old are you? ) 15

Input (Python 3) Reading strings firstname = input( Enter your first name ) Reading numbers age = eval(input( How old are you? )) 16

Intermission Admin stuff 17

Control Flow Not all programs are straight line Conditional statements Iteration Functions and procedures 18

Conditional Expressions Conditionals: if if x == 1: print "X is one" elif x == 0: print "X is zero" else: print "X is something else" 19

Indentation Blocks are denoted by exact indentation if x == 10: a = b * 5 print Hello y = y + 1 print a, b A source of headaches 20

What is X after the code runs? x = 7 if x > 22: x = 5 elif x <= 7: x = x*3 elif x == 21: x = x*2 1. 5 2. 7 3. 21 4. 42 5. I have no idea print(x) 21

Iteration - while General form: while <test>: will continue to iterate as long as <test> is true (not 0 or none) Special keywords to control looping break - jumps out of the loop continue - jumps back to the top of the loop (the while statement) x = 15 while x > 0: print x x = x - 1 Watch that indentation! 22

Iteration - for General form: the for statement iterates over a sequence of items, such as a list for x in range(5): print x prints 0, 1, 2, 3, 4 for x in range(2, 5): print x prints 2, 3, 4 for x in [ spam, eggs, ham ]: print x prints spam, eggs, ham 23

What is z after the code runs? x = 5 z = 0 for x in range(5): y = 6 if x == 3: break while y > 0: y = y - 1 z = z + 1 print(z) 1. 0 2. 18 3. 24 4. 64 5. I have no idea 24

Exercise Write a program that: Takes integer input from the user, until -1 is entered Calculates and prints the average of those numbers (excluding the -1) 25

Functions It s helpful to break your code into smaller pieces that each do some specific function or operation Can test each one individually Makes debugging easier Python uses the def fct_name(): statement statement etc return expression syntax 26

Example def sum(num1, num2): result = num1 + num2 return result Elsewhere in code a = 3 b = 12 c = sum(a,b) 27

Modularity We typically have multiple functions in a file Name one main as the starter Call it to get things going 28

Example def main(): code goes here def fct1(): code goes here def fct2(): code goes here main() 29

Random Numbers Built-in functions for that import random number = random.randint(1, 100) Gives random integer between 1 and 100, inclusive number = random.uniform(1.0, 10.0) Gives random float between 1.0 and 10.0 30

Modules Each separate file is called a module Usually contains a set of related functions that provide some useful operations You then import these modules When you downloaded Python, you got a bunch of them random, math 31

Scoping What is scoping? Scoping is a fancy word that just means the rules about what you can see from where in a program The namespace is the collection of stuff that you can see from any given point in a program 32

An Example Scoping Error welcomemsg = Hello! def changewelcomemsg(): welcomemsg = Bonjour! print New welcome message is, welcomemsg changewelcomemsg() >>> New welcome message is Bonjour! print welcomemsg Hello! WHY? 33

An Example: Scoping Error welcomemsg = Hello! def changewelcomemsg(): welcomemsg = Bonjour! welcomemsg is defined in the global scope print New welcome message is, welcomemsg This lines defines a new variable with the same name, in the local scope! changewelcomemsg() >>> New welcome message is Bonjour! print welcomemsg Hello! Since this call to print is outside the function changewelcomemsg(), it refers to the welcomemsg variable in the global scope. 34

Thinking About Scopes Variables named in the global scope are available to statements in any scope Unless they have been hidden by a local variable with the same name, as in the error example Variables named in a local scope are only available to statements in that scope The first assignment to a variable determines the scope it is in global scope func1 local scope func2 local scope func3 local scope 35

More on Scopes Global really means the file the variable is in When you start developing with multiple files, each file defines its own scope that is global for that file Each call to a function creates a new local scope Thus if a variable foo is defined in function func(), each call to func() has its own new namespace and its own separate foo By default, all assignments that you make in a function create names in the local scope Advanced: you can use the global statement if you want to change a global variable from within a function Dangerous, but useful. We ll talk about it in a later lecture Names not assigned to in a function are assumed to be globals 36

Still More on Scopes What all this boils down to is... Local variables (those first assigned to within a function) serve as temporary names you need only when a function is running This helps modularity of your program ( hide details within a function) But: You need to be careful when using a name within a function that s defined outside Subtle and hard to track bugs... Just don t do it 37

A common bug def print0to9(): maxmum = 10 for i in range(maximum): print(i) maximum = 5 for i in range(1,maximum): print(i) print0to9() 38

Scoping Gotchas Subtly different than some other languages 1. Local scopes don t nest def outerfunc(x, y): def innerfunc(z): if z > 0: print x, y innerfunc(x) x and y aren t available inside the local scope for innerfunc 2. There are actually three scopes: global, local, and builtin First, the local scope is checked Then, the global scope Finally, the scope defined by the module called builtin len, abs, max, min,... 39

More Administratia Late policy for assignments: Clear with me first if you have a valid excuse for missing a due date Examples: medical or family emergency My policy is -10% per late day, maximum 3 days late 40