Basics of Programming with Python

Similar documents
Invent Your Own Computer Games with Python

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

Random Walks and Defining Functions FEB 9 AND 11, 2015

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

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

Function Call Stack and Activation Records

Review Chapter 6 in Bravaco. Short Answers 1. This type of method does not return a value. a. null b. void c. empty d. anonymous

COMP 110 Programming Exercise: Simulation of the Game of Craps

CSC 1351: Quiz 6: Sort and Search

Most of the class will focus on if/else statements and the logical statements ("conditionals") that are used to build them. Then I'll go over a few

Flow Control: Branches and loops

The Big Python Guide

Comp 151. Control structures.

STUDENT LESSON A14 Boolean Algebra and Loop Boundaries

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

Random Walks and Defining Functions FEB 16TH

cs1114 REVIEW of details test closed laptop period

Conditionals and Recursion. Python Part 4

Text Input and Conditionals

Classwork 7: Craps. N. Duong & R. Rodriguez, Java Crash Course January 6, 2015

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

Lecture 19. Topics: Chapter 9. Simulation and Design Moving to graphics library Unit Testing 9.5 Other Design Techniques

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

CONDITION CONTROLLED LOOPS. Introduction to Programming - Python

Mat 2170 Week 9. Spring Mat 2170 Week 9. Objects and Classes. Week 9. Review. Random. Overloading. Craps. Clients. Packages. Randomness.

COMMOM OBJECT ORIENTED LISP SYSTEMS

Unit E Step-by-Step: Programming with Python

Student Responsibilities. Mat 2170 Week 9. Notes About Using Methods. Recall: Writing Methods. Chapter Six: Objects and Classes

Functions. Computer System and programming in C Prentice Hall, Inc. All rights reserved.

Control, Quick Overview. Selection. Selection 7/6/2017. Chapter 2. Control

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

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

Lecture 04 FUNCTIONS AND ARRAYS

Functions in C++ Problem-Solving Procedure With Modular Design C ++ Function Definition: a single

KAREL UNIT 5 STUDENT JOURNAL REVISED APRIL 19, 2017 NAME SCHOOL, CLASS, PERIOD

Introduction to: Computers & Programming: Review prior to 2 nd Midterm

CMPT 120 Control Structures in Python. Summer 2012 Instructor: Hassan Khosravi

15-110: Principles of Computing, Spring 2018

(Python) Chapter 3: Repetition

Data 8 Final Review #1

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

Professor Hugh C. Lauer CS-1004 Introduction to Programming for Non-Majors

Python - Loops and Iteration

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

18.1. CS 102 Unit 18. Python. Mark Redekopp

Condition Controlled Loops. Introduction to Programming - Python

Conditional Expressions and Decision Statements

Downloaded from Chapter 2. Functions

Chapter 1. Data types. Data types. In this chapter you will: learn about data types. learn about tuples, lists and dictionaries

CS177 Recitation. Functions, Booleans, Decision Structures, and Loop Structures

Accelerating Information Technology Innovation

Lab 2: Booleans, Strings, Random Numbers, Recursion, Variables, Input function

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

C Functions. 5.2 Program Modules in C

CPSC 217 L01 Midterm

A453 Task 1: Analysis: Problem: Solution:

Lists, loops and decisions

3 Programming. Jalal Kawash Mandatory: Chapter 5 Section 5.5 Jalal s resources: How to movies and example programs available at:

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

Python - Conditional Execution

CS1110 Lab 6 (Mar 17-18, 2015)

Python for Non-programmers

1.3 Conditionals and Loops

Quiz. Introduction: Python. In this project, you ll make a quiz game to challenge your friends. Activity Checklist.

CPSC 427: Object-Oriented Programming

CMSC 201 Fall 2015 Lab 12 Tuples and Dictionaries

CS 1301 Exam 1 Fall 2010

Visualize ComplexCities

Python allows variables to hold string values, just like any other type (Boolean, int, float). So, the following assignment statements are valid:

Accelerating Information Technology Innovation

INTERMEDIATE LEVEL PYTHON PROGRAMMING SELECTION AND CONDITIONALS V1.0

Fundamentals of Programming. Week 2 - Lecture 1: Strings part 2 + Monte Carlo method

(f) d={ alchemist :( a, t ), shaman : ( s, n ), wizard : ( w, z )} d[ shaman ][1]

MEIN 50010: Python Flow Control

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

Program #7: Let s Play Craps!

Python 1: Intro! Max Dougherty Andrew Schmitt

Loops and Iteration. Chapter 5. Python for Informatics: Exploring Information

Last Time: Rolling a Weighted Die

The Practice of Computing Using PYTHON. Chapter 2. Control. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Lecture 3 (02/06, 02/08): Condition Statements Decision, Operations & Information Technologies Robert H. Smith School of Business Spring, 2017

Comp 151. Control structures.

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

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

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

6.S189 Homework 1. What to turn in. Exercise 1.1 Installing Python. Exercise 1.2 Hello, world!

12/22/11. } Rolling a Six-Sided Die. } Fig 6.7: Rolling a Six-Sided Die 6,000,000 Times

Python 2.7 will also work for this workshop due to certain language rules, however I prefer working with the most current stable version.

8. DEALING WITH RANDOMNESS

4.2 Function definitions the basics

Advanced Operations Research Prof. G. Srinivasan Department of Management Studies Indian Institute of Technology, Madras

An Introduction to Python for KS4!

Lecture 8. Conditionals & Control Flow

Tutorial 12 Craps Game Application: Introducing Random Number Generation and Enumerations

MITOCW watch?v=se4p7ivcune

UNIT 6. Functions and Structured Programming

Lesson 1 Python: Interactive Fiction

MICROPROCESSOR SYSTEMS INTRODUCTION TO PYTHON

1 Getting used to Python

Practical Questions CSCA48 Winter 2018 Week 11

Transcription:

Basics of Programming with Python A gentle guide to writing simple programs Robert Montante 1

Topics Part 3 Obtaining Python Interactive use Variables Programs in files Data types Decision-making Functions Repetition Lists 2

What is a function? A group of related program statements Act together to produce a specific small result Independent of other statements Can be called or invoked (or used) from somewhere else within a program Functions split a larger overall program into smaller, more easily manageable parts Better organization Easier to make changes Less duplication of statements 3

General Form of a Function 1 st line defines the function, gives it a name, lists any needed arguments Function's body is indented If the function produces a value, that value is returned (usually as the last statement) def cowtalk( msg ): message = 'Moo! ' + msg + ' Moo.' return message 4

Using a function A user-defined function is called just like any other function: words = raw_input( 'What message? ' ) themessage = cowtalk( words ) print 'The cow says ', themessage The function must be defined somewhere before it is called 5

a complete example 6

more examples def fairdie(): d = random.randint(1,6) return d def badcoin(): c = random.random() if c < 0.6 : flip = 'Heads' else: flip = 'Tails' return flip 7

Topics Part 3 Obtaining Python Interactive use Variables Programs in files Data types Decision-making Functions Repetition Lists 8

Repetition; Loops Many programs require an action to be repeated multiple steps in a random walk repeated coin tosses A loop allows the programmer to repeat things as often as desired as often as desired means? Some fixed number of times Until some Boolean test is True (or False) 9

"fixed" loops Repeat something a certain number of times, or once for each item in a list: this prints a message five times: for n in [1, 2, 3, 4, 5] : print "hello " this lists all the vowels: for v in ['a', 'e', 'i','o', 'u'] : print "vowel ", v Use a for loop 10

the for loop Required format: Remember the colon for <variable> <statement> <statement> in <list-of-values> : The for and in are required keywords The body must be indented relative to the loop The body includes as many statements as needed. <variable> can be used within the loop body (but doesn't have to be) 11

"for" specifics of use "for" performs a block of statements, just like "if" does "for" walks through a list use the range() function to generate a list of numbers "for" uses a variable the variable is assigned each value from the list in turn, and the statement block is performed using that value 12

Lists A list is just a collection of values, all inside of square brackets Examples: vowels: [ 'a', 'e', 'i', 'o', 'u' ] words: [ 'cat', 'dog', 'fish' ] numbers: [ 0, 22, -8, 3.14159, 0 ] Lists can be assigned to variables: v = [ 'a', 'e', 'i', 'o', 'u' ] monthlength = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ] 13

Counting things Use a list of numbers in order, to "count" things: [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ] This is a very common case Use the range() function to create a list of numbers: range(10) gives ten numbers, 0 through 9 range(5, 9) gives four numbers, 5 through 8 range(2,100,2) gives all even numbers less than 100 14

more "for" examples Very simple, using range() for n in range(10): print n, "hello", print " --- goodbye" An arbitrary list of values: for ctr in [ 3, 9, -7, 'abcd', 33 ] : print ctr Use a string as a list: for ltr in 'abcdefghijklmnopqrestuvwxyz' : print ltr 15

Uncertain loops Use a while loop to repeat some statements as long as a condition is true: Let the user control the loop: while answer!= 'yes' : answer = input( 'Are you happy? ' ) The loop itself modifies part of the condition: while n%2 == 0 : print n, "is even" n = n / 2 16

the while loop Required format: Remember the colon while <Boolean expression> : <statement> <statement> The body must be indented relative to the loop The while is required The body includes as many statements as needed. The <Boolean expression> generally tests a variable. The variable must have a starting value! 17

"while" loop specifics "while" loops through a block of statements like "for" and "if" "while" checks a condition before each pass through its statement block the condition is a Boolean/logical expression, like those in "if" statements Any variables in the Boolean expression must have some value before the loop occurs! The statement block must be able to change one of the variables, or this will be an infinite loop. 18

more "while" examples Repeat something randomly: coin = random.randint(0,1) while coin == 1: print '"1" means Heads' coin = random.randint(0,1) Just like a "for" loop: n = 0 while n < 10: partyertakesstep( ) n = n + 1 19

The "craps" dice game: A bigger example Players take turns throwing a pair of dice A player can win, lose, or set a point If the player sets a point, then she throws again On each following throw, the player can win, lose, or just keep going If the player wins, she gets another turn If the player loses, the next player gets the dice (Betting takes place on many aspects of the throws.) 20

the game of Craps in detail The come-out throw: Natural: 7 or 11 Craps: 2, 3, 12 or a Point ( any of 4, 5, 6, 8, 9, 10 ) If you set a point, keep throwing again until you: Make your point: match the first throw to win (and get another turn) Seven-out: a 7 loses (and ends the turn) 21

Craps program structure Make the come-out throw Use an if-elif-else structure to decide whether you win, or lose, or keep throwing Record the result with a variable ( if you keep throwing ) Use a while block to repeat throws as long as the result isn't a win or a loss Print each throw; at the end, print the result 22

An Incomplete Craps Program This program shows the main features needed: A function produces each throw of the dice prints the die values returns their sum Three-way if-elif-else on the first (or "Come-out") throw Natural, craps, or keep throwing A while loop to make repeated throws if needed test each throw for a result Missing from this program: first-throw results are wrong counting the number of throws is wrong 23

Craps throws Ways to Make a Point 1 2 3 4 5 6 This isn't needed for the program, but here's how the various throws are named in a casino: (Lots of betting possibilities here) 1 2 2- Snake Eyes 3- Loose Deuce 3- Loose Deuce 4- Hard Four 5- Fever Five 3 4- Easy Four 5- Fever Five 4 5- Fever Five 5 6- Easy Six 6 7- Natural or Seven Out 6- Easy Six 7- Natural or Seven Out 8- Easy Eight 4- Easy Four 5- Fever Five 6- Hard Six 7- Natural or Seven Out 8- Easy Eight 6- Easy Six 7- Natural or Seven Out 8- Hard Eight 9- Nina 10- Easy Ten 6- Easy Six 7- Natural or Seven Out 8- Easy Eight 9- Nina 10- Hard Ten 7- Natural or Seven Out 8- Easy Eight 9- Nina 9- Nina 10- Easy Ten 11- Yo 11- Yo 12- Boxcars 24