Types, lists & functions

Similar documents
Python lab session 1

Python Intro GIS Week 1. Jake K. Carr

Python and Bioinformatics. Pierre Parutto

Lists, loops and decisions

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

Iterators & Generators

Fundamentals of Programming (Python) Getting Started with Programming

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

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

At full speed with Python

Problem Solving for Intro to Computer Science

Fundamentals: Expressions and Assignment

Overview of List Syntax

Use recursion to write a function that duplicates the following function: (def (f L) (map (lambda (x) (+ (sqr x) x)) L))

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

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

Python: common syntax

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A

9 abcd = dcba b + 90c = c + 10b b = 10c.

9 abcd = dcba b + 90c = c + 10b b = 10c.

Downloaded from Chapter 2. Functions

Python as a First Programming Language Justin Stevens Giselle Serate Davidson Academy of Nevada. March 6th, 2016

CMSC 201 Fall 2015 Lab 12 Tuples and Dictionaries

Compound Data Types 1

Introduction to Python. Genome 559: Introduction to Statistical and Computational Genomics Prof. James H. Thomas

CSCE 110 Programming I

CMSC201 Computer Science I for Majors

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

Variable and Data Type I

Python Review IPRE

Introduction to Python

Introduction to Python Programming

Full file at

Topic 7: Lists, Dictionaries and Strings

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

Data Structures. Lists, Tuples, Sets, Dictionaries

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

Introduction to Python. Genome 559: Introduction to Statistical and Computational Genomics Prof. James H. Thomas

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

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

Introduction to Python and programming. Ruth Anderson UW CSE 160 Winter 2017

3. Conditional Execution

3. Conditional Execution

Python Programming Exercises 3

MEIN 50010: Python Introduction

python 01 September 16, 2016

The Big Python Guide

ENCM 339 Fall 2017 Lecture Section 01 Lab 9 for the Week of November 20

Variable and Data Type I

ENGR 101 Engineering Design Workshop

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

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

Getting Started Values, Expressions, and Statements CS GMU

Python 2 Conditionals and loops Matthew Egbert CS111

Module 8: Local and functional abstraction

Python. Karin Lagesen.

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

CS115 - Module 9 - filter, map, and friends

Advanced Python. Executive Summary, Session 1

somedata = { } somedata[ cheese ] = dairy somedata[ Cheese ] = dairy items = ( ( 3, 2 ), ( 5, 7 ), ( 1, 9 ), 0, ( 1 ) )

METHODS EXERCISES GuessNumber and Sample run SumAll Sample Run

MUTABLE LISTS AND DICTIONARIES 4

(c) ((!(a && b)) == (!a!b)) TRUE / FALSE. (f) ((!(a b)) == (!a &&!b)) TRUE / FALSE. (g) (!(!a) && (c-d > 0) && (b!b))

Topic 5: Higher Order Functions

Topic 5: Higher Order Functions

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

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

Python for Non-programmers

Chapter 10: Strings and Hashtables

Answers Investigation 5

A Brief Introduction to Python

Lecture 1. Types, Expressions, & Variables

TOPICS TO COVER:-- Array declaration and use.

MICROPROCESSOR SYSTEMS INTRODUCTION TO PYTHON

Python for Informatics

Due Sunday November 12th, 11:59pm. Project Basics document (part of assignment):

Week - 04 Lecture - 01 Merge Sort. (Refer Slide Time: 00:02)

Python Review IPRE

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

2.1 Indefinite Loops. while <condition>: <body> rabbits = 3 while rabbits > 0: print rabbits rabbits -= 1

Getting Started with Python

1. What is the minimum number of bits needed to store a single piece of data representing: a. An integer between 0 and 100?

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7.

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

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

Practical Questions CSCA48 Week 6

Worksheet 6: Basic Methods Methods The Format Method Formatting Floats Formatting Different Types Formatting Keywords

1/11/2010 Topic 2: Introduction to Programming 1 1

Python The way of a program. Srinidhi H Asst Professor Dept of CSE, MSRIT

CS 115 Data Types and Arithmetic; Testing. Taken from notes by Dr. Neil Moore

Chapter 1 Histograms, Scatterplots, and Graphs of Functions

Structure and Interpretation of Computer Programs

Lab ACN : C++ Programming Exercises

CS 115 Lecture 8. Selection: the if statement. Neil Moore

Design and Analysis of Algorithms Prof. Madhavan Mukund Chennai Mathematical Institute. Module 02 Lecture - 45 Memoization

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

Chapter 6: List. 6.1 Definition. What we will learn: What you need to know before: Data types Assignments

Midterm Exam 2A Principles of Computing Fall November 10, 2014

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

Lists in Python CS 8: Introduction to Computer Science, Winter 2018 Lecture #10

Transcription:

Week 2 Types, lists & functions Data types If you want to write a program that allows the user to input something, you can use the command input: name = input (" What is your name? ") print (" Hello "+ name ) If you want the user to enter a number, however, the following code will lead to a TypeError: c = input (" Enter a temperature in Celsius : ") print ("In Fahrenheit, this is",9*c/5+32) In Python, variables all have a type. Without realising it, you have already met at least five types:. int An integer, for example a = 2. complex A complex number, for example a = + 2j 3. float An floating point number (decimal), for example b = / 2 4. str A string of characters, for example c = "Hello" 5. bool A boolean, for example d = True Operator such at +, - and * will behave differently for different combinations of types: print (0*2) print ("0"*2) print (0+2) print ("0"+"2") 20 00 2 02

You can check the type of a variable by using the function type: a = 0 print ( type (a)) print ( type (" Hello ")) <class <class 'int '> 'str '> input will always return what the user types as a str, so to make the example above work, you must convert the input to an int (or a float or complex): c = int ( input (" Enter a temperature in Celsius : ")) print ("In Fahrenheit, this is",9*c/5+32). In the editor window, type the following code and replace each $ with one of a, b, c, or d. a = 5 b = "5" c = 2 d = 2.0 print ( $ * $ + $) What do you need to replace each $ with to make Python print: a. 555 b. 5 c. 5.0 d. TypeError Lists As the name suggests, a list is a list of things. They are very useful in Python for storing multiple pieces of data. Lists are created using square brackets: a = [4,0,3,7,0,-0] b = [] c = [4," Hello ",True,8] Items in a list can be obtained by writing an index in square brackets after the list s name: a = [4,0,3,7,0,-0] print (a[2]) print (a[]) print (a[0]) print (a[-]) print (a[-2]) 3 0 4-0 0 The numbering of a list starts at 0 (leftmost item). A negative index of - i will return the ith item from the right of the list (- is the rightmost item). 2

You can also change the value of an item in a list: a = [4,0,3,7,0,-0] a[ 2] = 8 print (a) [4, 0, 8, 7, 0, -0] If you want to get multiple items from a list, you can take a slice of a list: ˆ list[a : b ] will get the items in the list from a up to and not including b ˆ list[ : b ] will get the items in the list from the start up to and not including b ˆ list[a : ] will get the items in the list from a up to the end ˆ list[a : b : c ] will get every cth item in the list from a up to and not including b a = [4,0,3,7,0,-0] print (a[:3]) print (a[4:]) print (a[:-3]) print (a[:5:2]) print (a[:5:2]) print (a[::2]) [0, 3] [0, -0] [4, 0, 3] [0, 7] [4, 3, 0] [4, 3, 0] The same syntax for getting items and slices from a list also works for strings: words = " Hello there!" print ( words [2]) print ( words [-]) print ( words [3:0]) print ( words [3:0:2]) print ( words [::-]) l! lo ther l hr! ereht olleh 2. In the editor window, type the following code and replace the $ with something. a = [4,0,3,7,0,-0] print (a[$]) 3

What do you need to replace the $ with to make Python print the following. There are multiple possible answers for each part. a. 4 b. 0 c. -0 d. 0 e. [ 4,0] f. [ ] g. IndexError h. TypeError You can add items to the end of a list using the method append and you can concatenate two lists by using the + operator: a = [4,0] a. append (5) print (a) b = [,5] a += b print (a) print (b+b) [4, 0, 5] [4, 0, 5,, 5] [, 5,, 5] There are some useful inbuilt functions that can give you some information about a list. The following example show how to find the maximum and minimum elements in a list, the sum of all the element and the length (number of elements in) of the list: a = [4,0,3,7,0,-0] print ( max (a)) print ( min (a)) print ( sum (a)) print ( len (a)) 0-0 4 6 3. How could you get Python to print the mean of a list? 4. Write a Python script that generates a list containing all the square numbers between and 00. There are a few more useful methods of a list. count tells you how many times something appears in a list. sort will sort the list into order. a = [4,0,3,0,0,0] print (a. count (0)) print (a. count (0)) a. sort () print (a) 3 [0, 3, 4, 0, 0, 0] 4

You can use a for loop to do something for every element in a list: for i in [3,2,4,0]: print (i ** 2) 9 4 6 00 Sometimes, you may need to make a for loop go through both the entries in the list and their indices. You can use enumerate to do this: a = [2,3,5,7,] for i,j in enumerate (a): print (i) print (j) 0 2 3 2 5 3 7 4 5. Write a Python script that prints the remainders when the square numbers between and 00 are divided by 5. (Hint use the script you wrote for the previous question.) 6. The following code is incomplete. a = [, 3, 2] b = [2,, -] dot = 0 for i in range (3): pass print ( dot ) Replace pass with some Python code so that the dot product of the vectors a and b is calculated and printed. Dictionaries A list is a way of storing multiple items in order, numbered 0,, 2,... Sometimes it is more useful to store multiple items not in order, with each one identified by a key. This can be done by storing the items in a dictionary. 5

Dictionaries are created using curly brackets and behave similarly to lists: a = {" cat ":5, " dog ":0, " rabbit ":True, 5:" apple "} print (a[" cat "]) print (a[5]) a[" cat "] += a[" hat "] = - 5 apple The items in the dictionary each have a key and a value, and are written in the form key : value. You can use a for loop to go through each key, each value, or both: data = {" hat ":, " scarf ":2, " coat ":, " shoes ":5} for i in data : # goes through keys print (i) hat scarf coat shoes for i in data. keys (): # goes through keys print (i) hat scarf coat shoes for i in data. values (): # goes through values print (i) 2 5 for i, j in data. items (): # goes through both print (i) print (j) hat scarf 2 coat shoes 5 7. The following dictionary gives the marks out of 00 that six fictional students scored in a test. results = {" Anna ":5, " Ben ":83, " Chris ":2, " Diana ":47, " Elizabeth ":84} 6

A score of more than (or equal to) 80 is a distinction. A score of more than (or equal to) 40 (and less than 80) is a pass. A score of below 40 is a fail. Write a Python script that prints the students names and whether they got a distinction, passed or failed. Tuples A tuple is like a list, but it s entries cannot be changed or added to after it is made. Tuples are created using regular brackets: a = (2,3,0) b = (,) c = (,) To make a tuple with or 0 entries, you must include the comma. Loading lists, dictionaries, and tuples from files You can read and write lists, dictionaries, and tuples from and to files using the json module. This is useful if you ever build a list (or dictionary or tuple) that takes a long time to make and you want to use again without having to build it. To save a list, do the following: import json data = [2,3,5,7,,3] with open (" data. json ","w") as f: json. dump (data, f) To load the list, do the following: import json with open (" data. json ") as f: data = json. load (f) Functions If you want to use a piece of code multiple times on different numbers, you can define a function in Python. def f(x): return x ** 2 7

def is short for define, and tells Python you are about to define a function. This is followed by f, the name of the function. In brackets, we give the input(s) of the function: this function will take one input that it will call x. The command return will cause the function to give x ** 2 as its output, then stop running. This function can then be used as in the following example code. def f(x): return x ** 2 print (f(4)) a = f( 2) print (a) 6 4 Functions can take more than one input as in the following example. They also do not have to return anything. def multiply_ and_ print (a, b): print (a*b) Functions can contain multiple lines of code. It is common to write a string that describes what the function does as the first line of the function. If help is called on the function, it will display this text. def product (a): " Returns the product of all the items in a list " output = for i in a: output *= i return output help ( product ) Help on function product in module main : product (a) Returns the product of all the items in a list 8. Using the function above, print the product of the prime numbers up to 00. Putting it all together Using all the Python commands you have learned in the two weeks so far, do the following questions. 9. It is known that ln 2 = 2 + 3 4 + 5 6 + 7... 8

Write a Python script to add up the first 000 terms in this series by appending every term to a list, then using the sum function. 0. Write a Python function that takes two numbers as an input and returns their highest common factor. Write a second function that takes two numbers as an input and returns their lowest common multiple.. Write some Python code that makes a list of the first 20 triangle numbers. Print the 20th triangle number. Print the sum of the first 20 triangle numbers? (Reminder: The nth triangle number is + 2 + 3 +... + n.) 2. Write a Python script that generates a list containing all the prime numbers between and 00. Prints the squares of all the prime numbers between and 00. 3. There is a row of 00 open lockers, numbered from 0 to 000. One person walks along the row of lockers and closes all the even numbered lockers. A second person walks along and changes the state (opens if they re closed; closes if they re open) of all the lockers that are multiples of 3. More people do the same for multiples of 4, then 5, then 6, and so on until the final person changes the state of the multiples of 000. Which lockers are closed at the end? Hint: You can use the following Python code to make a list containing True 00 times (ie for 0 to 000 inclusive): lockers = [ True ]* 00 4. Write a function that returns the sum of all the factors of a number (including but excluding the number itself). A perfect number is a number (such as 6) that is equal to the sum of its factors. Use your function to find the next three perfect numbers after 6. 5. A pair of numbers a and b are called amicable if a is the sum of the factors of b and b is the sum of the factors of a. Use the function you wrote in the previous section to find pairs of amicable numbers below 500. Assessed question When you have completed this question, you should show your code to one of the helpers in your class. 6. A function f : N N is defined by {n f(n) = 2 3n + if n is even if n is odd 9

Picking a starting number and repeatedly applying this function is conjectured to always eventually lead to the number. (This is called the Collatz conjecture.) 27 requires applications of f before reaching, and is the lowest number that takes more than 00 applications of f to reach. What is the lowest number that takes more than 200 applications of f to reach? 0