Python unit_4 review Tue/Wed, Dec 1-2

Slides:



Advertisements
Similar presentations
ThinkPython Ch. 10 CS104 Students o CS104 n Prof. Norman.
Advertisements

Chapter 6 Lists and Dictionaries CSC1310 Fall 2009.
String and Lists Dr. Benito Mendoza. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list List.
10-Jun-15 Just Enough Java. Variables A variable is a “box” that holds data Every variable has a name Examples: name, age, address, isMarried Variables.
Strings The Basics. Strings can refer to a string variable as one variable or as many different components (characters) string values are delimited by.
Exam 1 Review Instructor – Gokcen Cilingir Cpt S 111, Sections 6-7 (Sept 19, 2011) Washington State University.
Hossain Shahriar Announcement and reminder! Tentative date for final exam need to be fixed! We have agreed so far that it can.
Chapter 6 Looping Structures. Do…LoopDo…Loop Statement Can operate statements repetitively Do intx=intx + 1 Loop While intx < 10 –The Loop While operates.
Variables, Types, Expressions Intro2CS – week 1b 1.
1 CS 177 Week 6 Recitation Slides Review for Midterm Exam.
Tutorial 9 Iteration. Reminder Assignment 8 is due Wednesday.
Strings CSE 1310 – Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington 1.
Strings CSE 1310 – Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington 1.
Introduction to Programming Oliver Hawkins. BACKGROUND TO PROGRAMMING LANGUAGES Introduction to Programming.
 Python for-statements can be treated the same as for-each loops in Java Syntax: for variable in listOrstring: body statements Example) x = "string"
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
Input, Output and Variables GCSE Computer Science – Python.
Introduction to Programming
Python Basics.
String and Lists Dr. José M. Reyes Álamo.
Intro to CS Nov 21, 2016.
Java Fundamentals 4.
Topics Designing a Program Input, Processing, and Output
CIS3931 – Intro to JAVA Lecture Note Set 2 17-May-05.
CS1022 Computer Programming & Principles
CSc 120 Introduction to Computer Programing II Adapted from slides by
Introduction to Python
Intro to CS Nov 2, 2015.
Building Java Programs
COMPSCI 107 Computer Science Fundamentals
Containers and Lists CIS 40 – Introduction to Programming in Python
Primitive Data, Variables, Loops (Maybe)
Repetition-Counter control Loop
Strings Part 1 Taken from notes by Dr. Neil Moore
CISC101 Reminders Quiz 2 this week.
Intro to Computer Science CS1510 Dr. Sarah Diesburg
CSS 161 Fundamentals of Computing Introduction to Computers & Java
Introduction to C++ Programming
Lists in Python.
Chapter 10 Lists.
Data types Numeric types Sequence types float int bool list str
Building Java Programs
CISC101 Reminders Assn 3 due tomorrow, 7pm.
4. sequence data type Rocky K. C. Chang 16 September 2018
CEV208 Computer Programming
Module 4 Loops.
String and Lists Dr. José M. Reyes Álamo.
Intro to Computer Science CS1510 Dr. Sarah Diesburg
CMSC201 Computer Science I for Majors Lecture 09 – While Loops
Topics Designing a Program Input, Processing, and Output
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Building Java Programs
Building Java Programs
Building Java Programs
Intro to Computer Science CS1510 Dr. Sarah Diesburg
CISC101 Reminders Assignment 2 due today.
Topics Designing a Program Input, Processing, and Output
Programming Dr. Jalal Kawash.
Python Review
Just Enough Java 17-May-19.
Data Types Every variable has a given data type. The most common data types are: String - Text made up of numbers, letters and characters. Integer - Whole.
Building Java Programs
CISC101 Reminders Assignment 3 due today.
Class code for pythonroom.com cchsp2cs
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Strings Taken from notes by Dr. Neil Moore & Dr. Debby Keen
Data Types and Expressions
Introduction to Python
Presentation transcript:

Python unit_4 review Tue/Wed, Dec 1-2

Four Python data types int: age = 20 float: pi = 3.14159 String: name = ‘Alice’ zipcode=‘95120’ Boolean: isCold = True

Arithmetic operator + Addition - Subtraction * Multiplication / Division % Modulus if x % 2 == 1  odd number if x % 2 == 0  even number ** Exponent 5**3 = 125

Assignment operator a = (a + b)  a += b a = (a – b)  a -= b

Data types and operators Numeric types can use all arithmetic operators If mixing string and numeric, be careful !!! print(3+5.5) # ok. Output: 8.5 print(3+’5.5’) # error: unsupported type print(‘3’+’5.5’) # ok. String operation # output: 35.5 print( ‘Hi’*5) #ok. Output: HiHiHiHiHi print(‘Hi’+5) # error.

Built-in functions for type conversion int(x): convert x to a integer example: int(‘5’) float(x): convert x to a decimal example: float(‘2.8’) str(x): convert x to a string example: str(5)

Type conversion example print(3+’5’) #error print(3+int(‘5’)) #ok print(‘Hi’ + 5) #error print(‘Hi’ + str(5)) #ok. Output: Hi5

Built-in function for keyboard input Example_1 print(“Please enter your username: “) x=input() Example_2 x = input(“Please enter your username: “)

Keyboard input (cont’) input() always returns a string. If you want the result to be a number, use int(input()) or float(input()) x=input(“How many books you will buy: “) num_books = int(x) #use int() to convert # string to int price = num_books*22.99

Python while loop while loop_condition : statement_1 statement_2 Note: Check loop_condition, execute statements. Repeat above, until loop_condition becomes False.

while LOOP sample count = 1 while count < 11 : count = count + 1

Infinite while loop c = 0 while c< 10 : print (“Hello !!!”)

If you don’t want an infinite loop c = 0 while c< 10 : print (“Hello !!!”) c = c + 1 Use “break” to break out of a loop. while True : if c > 9 : break

range() range(start, stop, step) A quick way to create a list of integers The first integer = start Last integer = stop – 1 Example: range(4)  [0,1,2,3] range(1, 5)  [1,2,3,4] range(2,7,2)  [2,4,6]

For loop and range() Print “Hello” 4 times for x in range(4) : # x will be integer 0,1,2,3 one by one print(“Hello”) Print the sum of integers from 2 to 8 sum = 0 for x in range(2,9) : # x will be integer 2,3,4,5,6,7,8 sum = sum + x print(sum)

list data structure Len() : how many elements in the list? Use index to access data (positive or negative index) myList = [34, 26, ‘abc’, 56, ‘xy’] | | | | | index: 0 1 2 3 4 or : -5 -4 -3 -2 -1 in operator if ‘abc’ in myList Len() : how many elements in the list? + : merge two lists myList * 3 : repeat myList 3 times

list traverse in order print(myList) for x in myList : print(x)

list slice syntax: myList[start : stop : step] ending index = stop - 1 if start is missing, start from beginning if stop is missing, to the end if step is missing, step = 1 myList[::]  get all list elements in order myList[::-1]  get all list elements in reverse order

Useful List methods myList.append(‘something’) # add a new item to the end myList.sort() # reorder and change the original list myList.sort(reverse=True) # sort in reverse order myString = ‘- ’.join(myList) # join all items with # ‘-’ as separator

Display partial list langs = ["C", "C++", “XML", "Python"] print(langs[2:]) output: “XML” “Python” for x in langs[2:] : print(x + “ is cool”) Output: XML is cool Python is cool

Modify list member: must use index Question: how to modify the last two elements to “Java”? langs = ["C", "C++", "Perl", "Python"] langs[2] = "Perl“ langs[3] = "Python“ range(2,4) gives an integer list [2,3] To update the last two elements to “Java” for x in range(2,4) : langs[x] = “Java” output: ['C', 'C++', 'Java', 'Java']

String myStr = ‘the ring’ index: 0 1 2 3 4 5 6 7 -8 -7 -6 -5 -4 -3 -2 -1 myStr[start : stop : step] “in” operator ‘r’ in myStr “+”: link two strings “*”: repeat string print(myStr*3)

String looping myStr = ‘the ring’ count = 0 for char in myStr : if char==‘e’ : count = count + 1

But string is immutable!!! name = ‘007 Spectre’ You can’t change any letter in a string. name[2] = ‘8’ # ERROR!!!!!!

String replace() Python provides a built-in function myStr.replace(old, new, count) old -- The old substring to be replaced. new --The new substring, which would replace old substring. count – an optional argument. Note: for all string methods result, assign it to something. s1 = myStr.replace(old, new, count) Or myStr = myStr.replace(old, new, count)

Dictionary eng2spa = {} # Create an empty dictionary eng2spa[key] = value create a new entry or Replace the value if the key already exists. key in eng2spa # output: True or False Key not in eng2spa # output: True or False Len(eng2spa) key_list = list(eng2spa.keys()) # get list of keys val_list = list(eng2spa.values()) # get list of values

Function----def foo() : def play_music() : print(“Start playing Hello…”) def find_route_to_home() : print(“open google map. Point to home.”) play_music() find_route_to_home()

def foo(arg) : def play_music(music_name) : print(“Start playing: “, music_name) play_music(‘Hello’) play_music(‘Skyfall’) play_music(‘Happy’)

def foo(arg1, arg2) : def get_avg(x, y) : avg = (x+y)/2 print(“average is: “, avg) get_avg(5, 8) get_avg(22, 34) Note: function result can’t be assigned to a variable !!! x = get_avg(5, 8) # (error !!!)

Solution: def foo(arg1, arg2): return def get_avg(x, y) : avg = (x+y)/2 return avg x = get_avg(5, 8) y = get_avg(3.4, 2.7)

Reminder Show dictionary_proj today: Dec1:2nd/Dec2:3rd Next Project will be Banking. Coming soon. Test: Fri or Monday. Open notes, but handwritten notes only.

Stanford Splash !! https://www.stanfordesp.org/learn/Splash/2015_Fall/catalog#c at36 April 2016. Class try-on for high schooler

Extra question just for fun Write a function that reverses the order of the words in a string. For instance, the string “To be or not to be, that is a question. “ is changed to “question. A is that be, to not or be To”. Assume that all words are space delimited and treat punctuation the same as letters. You are given two fuses and a lighter. When lit, each fuse takes exactly one hour to burn from one end to the other. The fuses do not burn at a constant rate, though, and they are not identical. In other words, you may take no assumptions about the relationship between the length and the time it will take to burn. Two equal length of fuse might take different time to burn. Using only the fuses and the lighter, measure a period of exactly 45 minutes.