Intro2cs Tirgul 3.

Slides:



Advertisements
Similar presentations
CATHERINE AND ANNIE Python: Part 3. Intro to Loops Do you remember in Alice when you could use a loop to make a character perform an action multiple times?
Advertisements

Introduction to Computing Science and Programming I
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.
Dr. Yang, Qingxiong (with slides borrowed from Dr. Yuen, Joe) LT4: Control Flow - Loop CS2311 Computer Programming.
Python November 18, Unit 7. So Far We can get user input We can create variables We can convert values from one type to another using functions We can.
4. Python - Basic Operators
More Looping Structures
Programming for Linguists An Introduction to Python 24/11/2011.
If statements while loop for loop
Collecting Things Together - Lists 1. We’ve seen that Python can store things in memory and retrieve, using names. Sometime we want to store a bunch of.
Copyright © Nancy Acemian 2004 For Loops-Break-Continue COMP For loop is a counter controlled loop. For loop is a pretest loop. Used when number.
Lists CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Built-in Data Structures in Python An Introduction.
Q and A for Sections 2.9, 4.1 Victor Norman CS106 Fall 2015.
10. Python - Lists The list is a most versatile datatype available in Python, which can be written as a list of comma-separated values (items) between.
Lists. The list is a most versatile datatype available in Python which can be written as a list of comma-separated values (items) between square brackets.
INTRO2CS Tirgul 3 1. What we will cover today?  Boolean and logical expressions  Truth values  Conditional statements  while loop  for loop  range.
INTRO2CS Tirgul 4 1. What will we see today?  Strings  Lists  Tuples  Mutable and Immutable  Iterating over sequences  Nested Loops  Shallow and.
Loops ( while and for ) CSE 1310 – Introduction to Computers and Programming Alexandra Stefan 1.
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.
Lists/Dictionaries. What we are covering Data structure basics Lists Dictionaries Json.
Chapter 2 Writing Simple Programs
CMSC201 Computer Science I for Majors Lecture 07 – While Loops
String and Lists Dr. José M. Reyes Álamo.
REPETITION CONTROL STRUCTURE
Introduction To Repetition The for loop
The switch Statement, and Introduction to Looping
Topics Introduction to Repetition Structures
Python: Control Structures
Warm-up Program Use the same method as your first fortune cookie project and write a program that reads in a string from the user and, at random, will.
CS 115 Lecture 8 Structured Programming; for loops
Topics Introduction to Repetition Structures
Lecture 07 More Repetition Richard Gesick.
Repeating code We could repeat code we need more than once: i = 1 print (i) i += 1 print (i) #… stop when i == 9 But each line means an extra line we might.
Lecture 4B More Repetition Richard Gesick
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
Lists Part 1 Taken from notes by Dr. Neil Moore & Dr. Debby Keen
Ruth Anderson UW CSE 160 Spring 2018
Ruth Anderson UW CSE 160 Winter 2017
Looping.
Arrays, For loop While loop Do while loop
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
Additional Control Structures
Chapter 10 Lists.
CS190/295 Programming in Python for Life Sciences: Lecture 6
8 – Lists and tuples John R. Woodward.
Iteration: Beyond the Basic PERFORM
Types of Flow of Control
Module 4 Loops.
String and Lists Dr. José M. Reyes Álamo.
More Looping Structures
Topics Introduction to Repetition Structures
CMSC201 Computer Science I for Majors Lecture 09 – While Loops
Topics Sequences Introduction to Lists List Slicing
Computing Fundamentals
CHAPTER 6: Control Flow Tools (for and while loops)
For loops Taken from notes by Dr. Neil Moore
CISC101 Reminders Assignment 2 due today.
CHAPTER 4: Lists, Tuples and Dictionaries
Topics Introduction to Repetition Structures
Loops and Simple Functions
COMPUTER PROGRAMMING SKILLS
Topic: Loops Loops Idea While Loop Introduction to ranges For Loop
More Looping Structures
Class code for pythonroom.com cchsp2cs
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Control flow: Loops UW CSE 160.
Introduction to Computer Science
Selamat Datang di “Programming Essentials in Python”
Presentation transcript:

Intro2cs Tirgul 3

What we will cover today? Short recap For loop Range Lists Nested Loops Debugging and Testing!

Syntax – reminder Each indentation is considered a new “scope”. All statements considered to be in the same group should be indented the same. In general you should try to code as you speak, it might just work!

Truth values - Reminder An object is considered to be False if-and-only-if it holds one of the following values: None False Zero (of any numeric type, e.g., 0, 0.0) Which means everything else is True! (well, almost, but for us it is everything )

Loops - Motivation Often, we want to execute a statement multiple times repetitively Write a program that receives 2 numbers from the user and sums them up. Write a program that receives 3 numbers from the user and sums them up. What if we wanted a program that sums 100 numbers? current syntax requires a single line for every print. But note that there is actually just a single action here which we need to repeat many times.

What is a loop? A loop is a programming structure that contains an executable block of code that can be repeated several times. There are two types of loops: while loop for loop Print every item in the list

The range function Used to generate a sequence of numbers following a simple “rule”. And is used like this: If start is omitted, it will begin at 0. If step is specified, the numbers we will run over are: start, start+step, start+2*step, … such that the last element is the largest number (in the form of start+n*step) which is smaller than end. range([start],end[,step])

Python’s Range Python has a built in construct, range which creates an ordered collection of all integers in a given range. For two integers a, b, range(a, b) contains all integers k satisfying a ≤ k < b. range(b) is a shorthand for range(0,b). range returns a list (not exactly) with the numbers in the range on demand range(a, b, d)returns a list (not exactly) contains all integers of the form a+id, i≥0 satisfying a ≤ a+id < b.

The for loop for i in range(3): print('Hello World') Hello World Basic Syntax: for i in range(3): print('Hello World') Hello World

Summing a range use each item’s value What will be printed?

Iterating over a string with for loop line = 'The quick brown fox jumps ' \ ‘over the lazy dog’ num_of_spaces = 0 for char in line: if char == ' ': num_of_spaces += 1 if num_of_spaces: print('There are ', num_of_spaces, ‘ spaces in the sentence’) There are 8 spaces in the sentence

How many iterations? How many iterations the following loops will run? How can you check it if you’re not sure? for i in range (5): for i in range (0,5): for i in range (0,5,2): for i in range (0,50,20): for i in range (0,5,8):

7 Boom Go over the numbers from 1 to N, if the number is a multiplication of 7, or it contains the digit 7 print ‘Boom’ instead of the number for i in range(50): if i % 7 == 0 or '7' in str(i): print('Boom') else: print(i)

Create a random number import random for i in range(10): print(random.randint(1, 50), end=’, ’) 3, 40, 43, 41, 33, 43, 31, 36, 6, 31, More about random function

Is a random sequence contains a specific value import random for i in range(10): if random.randint(1, 50) == 41: print(’41 was randomized’) How many times will it be printed? What should we do if we want it to be printed once at most?

Breaking loops What happens if we enter an infinite loop? How can we escape from it? Use the “break” directive, which tells the program to exit from its current loop and continue the regular flow of the program.

break The break statement terminates the current loop and resumes execution at the next statement For example: import random for i in range(10): if random.randint(1, 50) == 41: print(’41 was randomized’) break 41 was randomized

Continuing an iteration - 1 What happens if we do not want to continue executing the current iteration of the loop? We could break, but what if we want to keep on running the loop, and just skip the current iteration? For that (again - type as you would have said it) you could use: continue Example: for <condition1>: if <condition2>: continue <statements>

continue With “continue” it is possible to skip the rest of the commands in the current iteration and start from the top of the loop again. >>> for i in range(5): ... x = random.randint(-5, 5) ... if(x == 0): ... continue ... print('The inverse of, ', x, 'is:', 1/x) The inverse of, 3 is: 0.3333333333333333 The inverse of, 5 is: 0.2 The inverse of, -5 is: -0.2 The inverse of, -1 is: -1.0

Iterating average We want to get 10 numbers from the user, and after each one print the current average NUMBER_OF_ITERATIONS = 10 avg = 0 for counter in range(1,NUMBER_OF_ITERATIONS+1): num = float(input('Enter a number: ')) avg += (num - avg) / counter print('The current average is:', avg)

Iterating average NUMBER_OF_ITERATIONS = 10 avg = 0 counter = 0 Example of execution: Please enter a number: 10 The current average is: 10.0 Please enter a number: 0 The current average is: 5.0 Please enter a number: 9 The current average is: 6.333 Please enter a number: 1 Please enter a number: 8 The current average is: 5.6 Please enter a number: 2 Please enter a number: 7 The current average is: 5.285 Please enter a number: 3 Please enter a number: 6 The current average is: 5.111 Please enter a number: 4 NUMBER_OF_ITERATIONS = 10 avg = 0 counter = 0 for counter in range(1,NUMBER_OF_ITERATIONS+1): num = float(input('Enter a number: ')) avg += (num - avg) / counter print('The current average is:', avg)

Range with negative step? Well why shouldn’t we use a negative step? Can be useful for iterating in a reversed order… Using range(start, end, negVal) will produce the values: start, start-negVal, start-2*negVal, … such that the last element is the smallest number (in the form of start-n*negVal) greater than end.

Example What will these code snippets print? for num in range(5,0,-1): print(num) for num in range(5,0,-3): print(num) for num in range(5,6,-1): print(num) Answers : [5,4,3,2,1], [5,2], []

Example print('#'*size) for i in range(0,size-2): Supposed you are asked to print a square with only the char ‘#’ and of some length, how would you do that? A solution is to use a for loop (with range): print('#'*size) for i in range(0,size-2): print('#'+' '*(size-2)+'#') ########## # # # # Another solution using one liner: print('#'*s+'\n'+('#'+' '*(s-2)+'#\n')*(s-2)+'#'*s)

Python Lists The list is the most versatile data type available in Python, which can be written as a list of comma-separated values (items) between square brackets: [ ] Good thing about a list is that items in a list do not need to have the same type.

Lists can hold different types lst = [1,3,'hi','bye'] be cautious! Can you think of an example of what may go wrong?

Creating a list (1) Creating a list is as simple as putting different comma-separated values between square brackets. For example: Like string indices, list indices start at 0 Lists can be sliced, concatenated and so on.

Creating a list (1) Another way to create a list is by using the ‘list()’ method. list(seq) - Converts a sequence into list.

Accessing Values in Lists To access values in lists, use the square brackets for slicing along with the index or indices to obtain value available at that index.

List Slicing (1) Slicing will create a new list with a subset of the original list. Works very similar to ‘range’ lst1 = lst[start:end] # items from start through end-1 lst2 = lst[start:] # items from start through the rest of the list

List Slicing (2) Slicing will create a new list with a subset of the original list lst3 = lst[:end] # items from the beginning through end-1 lst4 = lst[start:end:step] # start through not past end, by step lst5 =lst[::step] # from the beginning to the end by step

Updating Lists (1) You can update single or multiple elements of a list by giving the slice on the left-hand side of the assignment operator, and the new values on the right-hand side.

Updating Lists (2) You can also add elements to a list by using the append() method: list.append(x): Add an item to the end of the list; equivalent to a[len(a):] = [x]. append() takes exactly one argument!

Updating Lists (3) You can also extend a list by using the extend() method: list.extend(L): Extend the list by appending all the items in the given list; equivalent to a[len(a):] = L.

Delete List Elements To remove a list element, you can use either the del statement if you know exactly which element(s) you are deleting, or the remove() method if you do not know. 

Basic List Operations Lists respond to the + and * operators much like strings; they mean concatenation and repetition here too. In fact, lists respond to all of the general sequence operations we used on strings. Python Expression Results Description len([1, 2, 3]) 3 Length [1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation ['Hi!‘] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!‘] Repetition 3 in [1, 2, 3] True Membership for x in [1, 2, 3]: print x, 1 2 3 Iteration

Indexing and Slicing Because lists are sequences, indexing and slicing work the same way for lists as they do for strings. Assuming following input: Python Expression Results Explanation L[2] 'SPAM!' Offsets start at zero Negative: count from the right L[-2] 'Spam' ['Spam', 'SPAM!'] Slicing fetches sections L[1:]

Built-in List Functions len(list) Gives the total length of the list. max(list) Returns item from the list with max value. min(list) Returns item from the list with min value. list(seq) Converts a tuple into list.

Iterating over a list (1)

Iterating over a list (2) – an important comment What’s the difference between: for i in range(len(lst)): lst[i] = lst[i]*2 And for i in lst: i =i*2

Sequences go well with loops Print every item in the list

Nested for loops For loops may be nested, that is you can put a for loop inside another for loop A nested loop is a loop within a loop, an inner loop within the body of an outer one. How this works is that the first pass of the outer loop triggers the inner loop, which executes to completion. Then the second pass of the outer loop triggers the inner loop again. This repeats until the outer loop is ended.

Nested loops, why is it useful? How to print 8 rows of 5 stars each? for i in range(8): for k in range(5): print('*', end='') print() ***** The truth is that it could be done simpler: for i in range(8): print('*'*5)

Multiplication table How do you print the multiplication table? (Up to 100) 1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27 30 4 8 12 16 20 24 28 32 36 40 5 10 15 20 25 30 35 40 45 50 6 12 18 24 30 36 42 48 54 60 7 14 21 28 35 42 49 56 63 70 8 16 24 32 40 48 56 64 72 80 9 18 27 36 45 54 63 72 81 90 10 20 30 40 50 60 70 80 90 100

Multiplication table for i in range(1, 11): for j in range(1, 11): print(i*j, end='\t') print()

nested loops How can we print the following series using nested loops? 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5

Print range of ranges for i in range(1, 6): for j in range(1, i+1): print(j, end=" ") print()

Iterating over a list of lists What will be printed?

Nested for loops What are we trying to do here? What will be printed? We performed a sort of the list, by a method called “Bubble Sort”

Debugging 101 One of the most important tasks as a programmer is to have the ability of debugging

Debugging 101 Learning how to debug takes time! One of the approaches for debugging is using printouts We print some message that signifies the progress in our program Fast and provides with visual aid

Debugging Example - 1 You are given a list of numbers. You need to ask the user for a number to add to every item in the list (doesn’t have to be the same number) def addition_function(numbers): for num in numbers: my_num = int( input(”Enter an integer:") ) numbers.append(num+my_num) return numbers

Debugging Example - 1 If we got as input the list: [1,2] def addition_function(numbers): for num in numbers: my_num = int( input(”Enter an integer:") ) numbers.append(num+my_num) return numbers If we got as input the list: [1,2] Enter an integer: 10 Enter an integer: 5 Enter an integer: 13 Enter an integer: 1 Enter an integer: -100

Debugging Example - 1 What went wrong? Lets test and see! def addition_function(numbers): for num in numbers: print( num ) my_num = int( input(”Enter an integer:") ) numbers.append(num+my_num) return numbers addition_function([1]) 1 Enter an integer: 5 6 Enter an integer:

Debugging Example - 1 Found the problem! def addition_function(numbers): for num in numbers: print( num ) my_num = int( input(”Enter an integer:") ) numbers.append(num+my_num) return numbers Found the problem! Appending to the list we are going over

Debugging Example - 2 An encryption program! We will design the Caesar Code encryption There is a key (number) Every letter in a message is shifted by that key For example! Using key=2 we would have: a b c d e f … x y z c d e f g h … z a b

Debugging Example - 2 So first we would need to convert characters into strings, this could be done using the ord function! This function gives us the ASCII value of every letter The inverse of this function is the chr function As there are 26 letters in the English alphabet we would have to use these two functions: encrypt(msg, key) – adds key to every letter of msg decrypt(msg,key) – reduces key from every letter of msg ENCRYPT(LETTER,KEY) = (Value(LETTER)+KEY) mod 26 DECRYPT(LETTER,KEY) = (Value(LETTER)-KEY) mod 26

Debugging Example - 2 def encrypt(message, key): encrypted = "" for letter in message: encrypted += chr( ( ord(letter) +key ) % 26 ) return encrypted def decrypt(message, key): decrypted = "" for letter in message: decrypted += chr( ( ord(letter) - key ) % 26 ) return decrypted

Debugging Example - 2 Lets test our code! What went wrong?? Lets test! print( encrypt(“abc”, 1) == “bcd” ) False print( encrypt(“abc”, 1) ) '\x14\x14\x14'

This transforms the value of the letter ‘a’ to 0 Debugging Example - 2 OK so something is wrong, lets check the ord function and see if we’ve missed something: Oh right! The values of letters in ASCII starts at 97… Lets fix that! print( ord(“a”) ) 97 This transforms the value of the letter ‘a’ to 0 def encrypt(message, key): encrypted = "" for letter in message: encrypted += chr( ( ord(letter) - 97 +key ) % 26 ) return encrypted

Debugging Example - 2 Lets test our code (again)! What went wrong?? Lets test! print( encrypt(“abc”, 1) == “bcd” ) False print( encrypt(“abc”, 1) ) '\x01\x02\x03'

Debugging Example - 2 OK so something is wrong, lets check the ord function and see if we’ve missed something: Oh right! If we remove 97 we also have to add it back… Lets fix that! print( ( ord(‘a’) - 97 +key ) % 26 ) 1 This transforms the value of every letter back to ASCII This transforms the value of the letter ‘a’ to 0 def encrypt(message, key): encrypted = "" for letter in message: encrypted += chr( ( ord(letter) - 97 +key ) % 26 + 97 ) return encrypted

Debugging Example - 2 Lets test our code (again)! Great! Lets copy the whole procedure to the decrypt function print( encrypt(“abc”, 1) == “bcd” ) True def decrypt(message, key): decrypted = "" for letter in message: decrypted += chr( ( ord(letter) - 97 +key ) % 26 + 97 ) return decrypted

Debugging Example - 2 So now, if we encrypt and than decrypt we should get the same message! Wait, so what went wrong? Oh, when copying the line we forgot to change it to (-key) print( decrypt( encrypt(“abc”, 1), 1) == “abc” ) False decrypted += chr( ( ord(letter) - 97 +key ) % 26 + 97 ) DECRYPT(LETTER,KEY) = (Value(LETTER)-KEY) mod 26

Debugging Example - 2 def encrypt(message, key): encrypted = "" for letter in message: encrypted += chr( ( ord(letter) - 97 +key ) % 26 + 97) return encrypted def decrypt(message, key): decrypted = "" for letter in message: decrypted += chr( ( ord(letter) - 97 - key ) % 26 +97 ) return decrypted

Debugging Examples So what did we have here? Using the print function could help you find where your bugs are Always remember to check your assumptions! Beware of copy-paste errors!

Extra Slides

else clause (of ‘for’ statement) Loop statements may have an else clause; it is executed when the for loop terminates through exhaustion, but not when the loop is terminated by a break statement. Similar to what you have seen with while loop

Example of ‘else’ statement has_even_number = False for i in range(10): val = random.randint(1, 50) if val % 2 == 0: has_even_number = True break if has_even_number: print(’An even number was found’) else: print(’No even number found') Notice where the else is indented for i in range(10): val = random.randint(1, 50) if val % 2 == 0: print('An even number was found’) break else: print(’No even number found')

Built-in Methods of List (1) list.append(obj) Appends object obj to list list.count(obj) Returns count of how many times obj occurs in list list.extend(seq) Appends the contents of seq to list list.index(obj) Returns the lowest index in list that obj appears list.insert(index, obj) Inserts object obj into list at offset index

Built-in Methods of List (2) list.pop(obj=list[-1]) Removes and returns last object or obj from list list.remove(obj) Remove the first item from the list whose value is x. It is an error if there is no such item. list.reverse() Reverses objects of list in place list.sort([func]) Sorts objects of list, use compare func if given More about list methods: https://docs.python.org/2/tutorial/datastructures.html #more-on-lists

An example that uses most of the list methods (1) >>> a = [66.25, 333, 333, 1, 1234.5] >>> print(a.count(333), a.count(66.25), a.count('x')) 2 1 0 >>> a.insert(2, -1) >>> a.append(333) >>> a [66.25, 333, -1, 333, 1, 1234.5, 333] >>> a.index(333) 1

An example that uses most of the list methods (2) >>> a.remove(333) >>> a [66.25, -1, 333, 1, 1234.5, 333] >>> a.reverse() [333, 1234.5, 1, 333, -1, 66.25] >>> a.sort() [-1, 1, 66.25, 333, 333, 1234.5] >>> a.pop() 1234.5 [-1, 1, 66.25, 333, 333]