CSCE 110 Programming I

Similar documents
CSCE 110 Programming I Basics of Python: Lists, Tuples, and Functions

Beyond Blocks: Python Session #1

Python Reference (The Right Way) Documentation

contacts= { bill : , rich : , jane : } print contacts { jane : , bill : , rich : }

Modules and scoping rules

CSCE 110 Programming I Basics of Python: Variables, Expressions, Input/Output

Python Intro GIS Week 1. Jake K. Carr

Types, lists & functions

CSCE 110 Programming I

18.1. CS 102 Unit 18. Python. Mark Redekopp

Python 3000 and You. Guido van Rossum PyCon March 14, 2008

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

CNRS ANF PYTHON Objects everywhere

Python Tutorial. Day 1

Python: common syntax

Introduction to Python

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

Advanced Python. Executive Summary, Session 1

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

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

STSCI Python Introduction. Class URL

VALLIAMMAI ENGINEERING COLLEGE

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

Sequences and iteration in Python

MUTABLE LISTS AND DICTIONARIES 4

(IUCAA, Pune) kaustubh[at]iucaa[dot]ernet[dot]in.

Python for Non-programmers

The Pyth Language. Administrivia

The Practice of Computing Using PYTHON

Python 1: Intro! Max Dougherty Andrew Schmitt

Babu Madhav Institute of Information Technology, UTU 2015

Python 3000 and You. Guido van Rossum EuroPython July 7, 2008

ECS15, Lecture 14. Reminder: how to learn Python. Today is the final day to request a regrade of the midterm. Topic 4: Programming in Python, cont.

Lists How lists are like strings

Python for ArcGIS. Lab 1.

Script language: Python Data structures

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

LISTS WITH PYTHON. José M. Garrido Department of Computer Science. May College of Computing and Software Engineering Kennesaw State University

CSCE 110 Programming I

Exam 1 Format, Concepts, What you should be able to do, and Sample Problems

Computer Sciences 368 Scripting for CHTC Day 3: Collections Suggested reading: Learning Python

Fundamentals of Programming (Python) Getting Started with Programming

Programming with Python

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

Part IV. More on Python. Tobias Neckel: Scripting with Bash and Python Compact Max-Planck, February 16-26,

6. Data Types and Dynamic Typing (Cont.)

University of Texas at Arlington, TX, USA

Python Programming: Lecture 2 Data Types

Variable and Data Type I

CS Summer 2013

CS2304: Python for Java Programmers. CS2304: Sequences and Collections

Senthil Kumaran S

CS 115 Exam 1, Fall 2015 Thu. 09/24/2015

DM550/DM857 Introduction to Programming. Peter Schneider-Kamp

Lists, loops and decisions

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

CIS192 Python Programming. Robert Rand. August 27, 2015

cs1114 REVIEW of details test closed laptop period

Getting Started with Python

Introduction to Python

Chapter 2 Writing Simple Programs

CMPT 120 Basics of Python. Summer 2012 Instructor: Hassan Khosravi

Advanced Algorithms and Computational Models (module A)

Webgurukul Programming Language Course

Lecture Writing Programs. Richard E Sarkis CSC 161: The Art of Programming

The Big Python Guide

Lesson 4: Type Conversion, Mutability, Sequence Indexing. Fundamentals of Text Processing for Linguists Na-Rae Han

Data type built into Python. Dictionaries are sometimes found in other languages as associative memories or associative arrays.

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

Python - Variable Types. John R. Woodward

Lecture 7: Python s Built-in. in Types and Basic Statements

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

CS Advanced Unix Tools & Scripting

Variable and Data Type I

Computing with Strings. Learning Outcomes. Python s String Type 9/23/2012

Comp Exam 1 Overview.

CS 1301 Final Exam Review Guide

1 RPN (Danny Yoo / Donovan Preston)

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

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

Swift. Introducing swift. Thomas Woodfin

Python Training. Complete Practical & Real-time Trainings. A Unit of SequelGate Innovative Technologies Pvt. Ltd.

Python. Department of Computer Science And Engineering. European University Cyprus

CIS192: Python Programming

Python for Non-programmers

EE 355 Unit 17. Python. Mark Redekopp

The current topic: Python. Announcements. Python. Python

More Loop Examples Functions and Parameters

Introduction to Python

Course Title: Python + Django for Web Application

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

Part III Appendices 165

PYTHON FOR KIDS A Pl ayfu l I ntrodu ctio n to Prog r am m i ng J a s o n R. B r i g g s

python 01 September 16, 2016

Introduction to Python (All the Basic Stuff)

Lecture #15: Generic Functions and Expressivity. Last modified: Wed Mar 1 15:51: CS61A: Lecture #16 1

Data Structures. Lists, Tuples, Sets, Dictionaries

Downloaded from Chapter 2. Functions

CITS 4406 Problem Solving & Programming

Programming in Python

Transcription:

CSCE 110 Programming I Basics of Python (Part 3): Functions, Lists, For Loops, and Tuples Dr. Tiffani L. Williams Department of Computer Science and Engineering Texas A&M University Spring 2014 Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring 2014 1 / 21

Defining a Function A function is a named block of statements that performs an operation. To define a function, we use the following syntax: def func(param_list): block When executed, this compound statement creates a new function object and assigns it to the name func. func is a valid Python name (think of valid variable names), param_list represents zero or more comma-separated parameters, and block is an indented block of statements. Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring 2014 2 / 21

Function Examples (1) Listing 1: function-example.py 1 # A simple example of how to use functions 2 3 def print_msg (): 4 print "I love Python!" 5 6 def iseven ( num ): 7 print num % 2 == 0 8 9 print_msg () 10 iseven (10) 11 iseven (7) Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring 2014 3 / 21

Function Examples (2) Listing 2: temperature-converter.py 1 # Converts the temperature to Celsius or Fahrenheit 2 3 def to_fahrenheit (c): # Convert celsius to fahrenheit 4 return (c * 9.0/5.0) + 32 5 6 def to_celsius (f): # Convert fahrenheit to celsius 7 return (f - 32) * 5.0/9.0 8 9 type = raw_input (" Convert temperature to Celsius or Fahrenheit (c or f)? ") 10 if type == c : 11 temperature = int ( raw_input (" Enter Fahrenheit temperature : ")) 12 celsius = to_celsius ( temperature ) 13 print "%d Fahrenheit is %d Celsius." % ( temperature, celsius ) 14 else : 15 temperature = int ( raw_input (" Enter Celsius temperature : ")) 16 fahrenheit = to_fahrenheit ( temperature ) 17 print "%d Celsius is %d Fahrenheit." % ( temperature, fahrenheit ) Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring 2014 4 / 21

Function Examples (3) Listing 3: temperature-converter2.py 1 # Converts the temperature to Celsius or Fahrenheit. Uses a main function 2 # to drive the program. 3 4 def to_fahrenheit (c): # Convert celsius to fahrenheit 5 return (c * 9.0/5.0) + 32 6 7 def to_celsius (f): # Convert fahrenheit to celsius 8 return (f - 32) * 5.0/9.0 9 10 def main (): 11 type = raw_input (" Convert temperature to Celsius or Fahrenheit (c or f)? ") 12 if type == c : 13 temperature = int ( raw_input (" Enter Fahrenheit temperature : ")) 14 celsius = to_celsius ( temperature ) 15 print "%d Fahrenheit is %d Celsius." % ( temperature, celsius ) 16 else : 17 temperature = int ( raw_input (" Enter Celsius temperature : ")) 18 fahrenheit = to_fahrenheit ( temperature ) 19 print "%d Celsius is %d Fahrenheit." % ( temperature, fahrenheit ) 20 21 # Execution of the program begins here 22 main () Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring 2014 5 / 21

Built-in Functions abs() divmod() input() open() staticmethod() all() enumerate() int() ord() str() any() eval() isinstance() pow() sum() basestring() execfile() issubclass() print() super() bin() file() iter() property() tuple() bool() filter() len() range() type() bytearray() float() list() raw_input() unichr() callable() format() locals() reduce() unicode() chr() frozenset() long() reload() vars() classmethod() getattr() map() repr() xrange() cmp() globals() max() reversed() zip() compile() hasattr() memoryview() round() import () complex() hash() min() set() apply() delattr() help() next() setattr() buffer() dict() hex() object() slice() coerce() dir() id() oct() sorted() intern() Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring 2014 6 / 21

Local and Global Variables (1) Listing 4: local-global-variables.py 1 # An example showing the difference between local and global variables. 2 v = 15 # v is a global variable 3 4 def f1 (): 5 v = 17 # v is a local variable 6 print v(f1 ):, v 7 v = v + 1 8 print v(f1 ):, v 9 10 def f2 (): 11 print v(f2 ):, v # since v is not local, global version is used 12 13 f1 () 14 f2 () 15 print v:, v # references global version of v Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring 2014 7 / 21

Local and Global Variables (2) Listing 5: local-global-variables2.py 1 # This program has an error. Find it and explain why it is in fact an error. 2 3 v = 15 4 5 def f1 (): 6 v = 17 7 print v(f1 ):, v 8 9 def f2 (): 10 v = v + 10 11 print v(f2 ):, v 12 13 f1 () 14 f2 () 15 print v:, v Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring 2014 8 / 21

Lists Ordered collection of data. Example: some_data = [ dog, 78, 87.0, gorilla ] Elements can be of different types (heterogeneous) Can have a mixture of strings, ints, floats, lists, etc. Composed of elements that can be accessed by indexing Can create sublists by specifying an index range This is accomplished with the slicing operator [:] or [::] You can change individual elements directly ( mutable ) Unlike strings, each element in a list can be modified List creation operator [ ], elements of the list are separated by commas Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring 2014 9 / 21

List Examples (Python Shell) 1 >>> alist = [1, 2, 3, 4] # list creation 2 >>> alist 3 [1, 2, 3, 4] 4 5 >>> alist [0] # indexing individual elements 6 1 7 8 >>> alist [2:] # creating sublist 9 [3, 4] 10 11 >>> alist [:3] # creating sublist 12 [1, 2, 3] 13 14 >>> alist [1] = 5 # mutable 15 >>> alist 16 [1, 5, 3, 4] Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring 2014 10 / 21

List Examples (Python Shell) 1 >>> alist = [1, 2, 3, 4] # list creation 2 >>> alist 3 [1, 2, 3, 4] 4 5 >>> alist [0] # indexing individual elements 6 1 7 8 >>> alist [2:] # creating sublist 9 [3, 4] 10 11 >>> alist [:3] # creating sublist 12 [1, 2, 3] 13 14 >>> alist [1] = 5 # mutable 15 >>> alist 16 [1, 5, 3, 4] Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring 2014 11 / 21

for Loop for iter_var in iterable: suite_to_repeat Objects that are iterable include strings, lists, and tuples. Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring 2014 12 / 21

for Loop Examples Listing 6: for-example.py 1 for eachletter in " Names ": 2 print " current letter :", eachletter Listing 7: for-example2.py 1 name_list = [ Walter, " Nicole ", Steven ] # iterating over a list 2 for each_name in name_list : 3 print each_name, " Smith " Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring 2014 13 / 21

while vs for loops Listing 8: while-vs-for.py 1 # Shows the difference between while and for loops by 2 # printing the numbers from 1 to 5. 3 4 print " while loop : Printing the numbers from 1 to 5." 5 i = 1 6 while i < 6: # could also write while i <= 5: 7 print i 8 i += 1 9 10 print "\ nfor loop : Printing the numbers from 1 to 5." 11 for i in range (1,6): # range (1,6) creates the list [1, 2, 3, 4, 5] 12 print i Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring 2014 14 / 21

Integer to English Conversion Given an integer value, return a string with the equivalent English text of each digit. For example, an input of 89 results in eight-nine being returned. For an extra challenge, return English text with proper usage, i.e., eighty-nine. For this problem, restrict values to be between 0 and 1,000. Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring 2014 15 / 21

Integer to English (Version 1) I Listing 9: integer-to-english1.py 1 # A program that converts an integer between 0 and 1,000 to its English equivalent. 2 3 # Returns the English equivalent of the numbers 0 to 9. 4 def convert ( digit ): 5 6 if digit == 0 : 7 name = zero 8 elif digit == 1 : 9 name = one 10 elif digit == 2 : 11 name = two 12 elif digit == 3 : 13 name = three 14 elif digit == 4 : 15 name = four 16 elif digit == 5 : 17 name = five 18 elif digit == 6 : 19 name = six 20 elif digit == 7 : 21 name = seven 22 elif digit == 8 : 23 name = eight 24 else : 25 name = nine 26 27 return name Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring 2014 16 / 21

Integer to English (Version 1) II 28 29 30 # Obtains the user s input and farms the work. 31 def main (): 32 33 result = 34 number = raw_input ( Please enter an integer between 0 and 1000: ) 35 36 for digit in number : 37 result += convert ( digit ) + - 38 39 print %s is %s. % (number, result [: len ( result ) -1]) 40 41 42 # Execution begins here. 43 main () Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring 2014 17 / 21

Integer to English (Version 2) Listing 10: integer-to-english1a.py 1 # A program that converts an integer between 0 and 1,000 to its English equivalent. 2 # Easy version. 3 4 # Returns the English equivalent of the numbers 0 to 9. 5 def convert ( digit ): 6 name = [ zero, one, two, three, four, five, 7 six, seven, eight, nine ] 8 return name [int ( digit )] 9 10 11 # Obtains the user s input and farms the work. 12 def main (): 13 14 result = [] 15 number = raw_input ( Please enter an integer between 0 and 1000: ) 16 17 for digit in number : 18 result += [ convert ( digit )] 19 20 result = -.join ( result ) 21 22 print %s is %s. % ( number, result ) 23 24 main () Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring 2014 18 / 21

Tuples Tuples are similar to lists except for one important difference. Unlike lists, tuples are immutable. Example: some_data = ( dog, 78, 87.1, gorilla ) An element in a tuple cannot be changed. In that sense, both strings and tuples share the immutability criterion. Reason for immutability: you don t want variable s contents to be accidentally overwritten. Tuple creation operator ( ), elements of the list are separated by commas Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring 2014 19 / 21

Tuple Examples (Python Shell) 1 >>> atuple = ( robots, 77, 93, try ) # tuple creation 2 >>> atuple 3 ( robots, 77, 93, try ) 4 5 >>> atuple [:3] # creating subtuples 6 ( robots, 77, 93) 7 8 >>> atuple [1] = 5 # immutable 9 10 Traceback ( most recent call last ): 11 File "<string >", line 1, in <fragment > 12 TypeError : tuple object does not support item assignment Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring 2014 20 / 21

Concatenating Lists or Tuples Examples (Python Shell) 1 >>> alist = [1, 2, 3] # list creation 2 >>> alist + [4, 5] # list concatenation 3 [1, 2, 3, 4, 5] 4 5 >>> atuple = ( four, five ) # tuple creation 6 >>> atuple + ( six ) # immutable 7 Traceback ( most recent call last ): 8 File "<string >", line 1, in <fragment > 9 TypeError : can only concatenate tuple ( not " str ") to tuple 10 11 >>> alist # print alist 12 [1, 2, 3] 13 >>> atuple # print atuple 14 ( four, five ) 15 >>> alist + [ atuple ] # concatenate list and tuple as a list 16 [1, 2, 3, ( four, five )] 17 18 >>> alist + atuple # immutable 19 20 Traceback ( most recent call last ): 21 File "<string >", line 1, in <fragment > 22 TypeError : can only concatenate list (not " tuple ") to list Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring 2014 21 / 21