Www.teachingcomputing.com Mastering Programming in Python Lesson 3(b) All you need to know about FOR LOOPS.

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

ECS 15 if and random. Topic  Testing user input using if statements  Truth and falsehood in Python  Getting random numbers.
Introduction to Computing Science and Programming I
James Tam Loops In Python In this section of notes you will learn how to rerun parts of your program without having to duplicate the code.
Computer Science 1620 Loops.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 5: Looping by Tony.
Pseudocode and Algorithms
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.
Main task -write me a program
Chapter 3 Planning Your Solution
Python. What is Python? A programming language we can use to communicate with the computer and solve problems We give the computer instructions that it.
Fundamentals of Python: From First Programs Through Data Structures
Python.
The University of Texas – Pan American
CC0002NI – Computer Programming Computer Programming Er. Saroj Sharan Regmi Week 7.
Fundamentals of Python: First Programs
Noadswood Science,  To know the basics of Python coding and decoding Monday, September 07, 2015.
An Introduction to Textual Programming
1 Lab Session-III CSIT-120 Fall 2000 Revising Previous session Data input and output While loop Exercise Limits and Bounds Session III-B (starts on slide.
Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.
Control Structures FOR Statement Looping.
Iteration. Adding CDs to Vic Stack In many of the programs you write, you would like to have a CD on the stack before the program runs. To do this, you.
PYTHON: PART 2 Catherine and Annie. VARIABLES  That last program was a little simple. You probably want something a little more challenging.  Let’s.
Nonvisual Arrays and Recursion by Chris Brown under Prof. Susan Rodger Duke University June 2012.
By the end of this session you should be able to...
Conditions. Objectives  Understanding what altering the flow of control does on programs and being able to apply thee to design code  Look at why indentation.
Python – May 11 Briefing Course overview Introduction to the language Lab.
Lesson 4 Using Variables in Python – Creating a Simple ChatBot Program.
1 09/20/04CS150 Introduction to Computer Science 1 Let ’ s all Repeat Together.
Saeed Ghanbartehrani Summer 2015 Lecture Notes #5: Programming Structures IE 212: Computational Methods for Industrial Engineering.
Logic Our programs will have to make decisions in terms of what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if.
Introducing Python CS 4320, SPRING Resources We will be following the Python tutorialPython tutorial These notes will cover the following sections.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
CSC 110 Using Python [Reading: chapter 1] CSC 110 B 1.
More about Strings. String Formatting  So far we have used comma separators to print messages  This is fine until our messages become quite complex:
Python 101 Dr. Bernard Chen University of Central Arkansas PyArkansas.
Decision Structures and Boolean Variables. Sequence Structures Thus far, we’ve been programming “sequence structures” Thus far, we’ve been programming.
COIT29222 Structured Programming 1 COIT29222-Structured Programming Lecture Week 02  Reading: Textbook(4 th Ed.), Chapter 2 Textbook (6 th Ed.), Chapters.
Chapter 7 Problem Solving with Loops
PROGRAMMING IN PYTHON LETS LEARN SOME CODE TOGETHER!
GCSE Computing: Programming GCSE Programming Remembering Python.
Introduction to Computer Programming - Project 2 Intro to Digital Technology.
Algorithms and Pseudocode
Mastering Programming in Python Lesson 1.
Loops (While and For) CSE 1310 – Introduction to Computers and Programming 1.
COMPUTER PROGRAMMING Year 9 – lesson 1. Objective and Outcome Teaching Objective We are going to look at how to construct a computer program. We will.
Getting Started With Python Brendan Routledge
Selection Using IF THEN ELSE CASE Introducing Loops.
Whatcha doin'? Aims: To start using Python. To understand loops.
3.1 Fundamentals of algorithms
REPETITION CONTROL STRUCTURE
Lesson 1 - Sequencing.
Lesson 1 An Introduction
CS1371 Introduction to Computing for Engineers
Lesson 3 - Repetition.
Introduction to Programmng in Python
Iterations Programming Condition Controlled Loops (WHILE Loop)
Learning to Program in Python
Learning to Program in Python
Selection CIS 40 – Introduction to Programming in Python
Learning to Program in Python
Escape sequences: Practice using the escape sequences on the code below to see what happens. Try this next code to help you understand the last two sequences.
Loops CIS 40 – Introduction to Programming in Python
Introduction to TouchDevelop
Module 4 Loops.
Topics Introduction to Repetition Structures
A look at Python Programming Language 2018.
Python programming exercise
Software Development Techniques
Presentation transcript:

Mastering Programming in Python Lesson 3(b) All you need to know about FOR LOOPS

Lesson 1: Introduction to the language, SEQUENCE variables, create a Chat bot Lesson 2: Introduction SELECTION (if else statements) Lesson 3a): Introducing ITERATION (While loops) Lesson 3b): Introducing For Loops Lesson 4: Use of Functions/Modular Programming Lesson 5: Introducing Lists /Operations/List comprehension Lesson 6: Use of Dictionaries Lesson 7: String Manipulation Lesson 8: File Handling – Reading and writing to CSV Files Lesson 9: Importing and Exporting Files Lesson 10: Transversing, Enumeration, Zip Merging Lesson 11: Recursion Lesson 12: Project 1 Lesson 13 Project 2 Lesson 14: Project 3 Lesson 15: Consolidation of all your skills – useful resources Series Overview *Please note that each lesson is not bound to a specific time (so it can be taken at your own pace) Information/Theory/Discuss Task (Code provided) Challenge (DIY!) Suggested Project/HW COMING SOON

In this lesson you will …  Learn about loops, specifically the FOR LOOP  Predict the output (For Loop Task)  Adapt and change code involving For Loops  Compare ‘while’ and ‘for’ loops.  Use the break statement and see how it works  Learn about Nested Loops  Create your own For Loops  Create the beginnings of an Arithmetic quiz using a random function and for loops  Big ideas: Is the universe digital? A program?  Introducing Gottfried Leibniz and Konrad Zuse *For this series we assume students know how to open, save and run a python module. Version: Python 3

Did you know? Guido van Rossum, the guy on the right, created python! He is a Dutch computer programmer and completed his degree in the university of Amsterdam He was employed by Google from 2005 until December 2012, where much of his time was spent developing the Python language. In 2013, Van Rossum started working for Dropbox. Python is intended to be a highly readable language. It has a relatively uncluttered visual layout, frequently using English keywords where other languages use punctuation. Guido van Rossum, the creator of Python An important goal of the Python developers is making Python fun to use. This is reflected in the origin of the name which comes from Monty Python

The difference between ‘While’ and ‘For’ For loops are traditionally used when you have a piece of code which you want to repeat n number of times. As an alternative, there is the WhileLoop, however, while is used when a condition is to be met, or if you want a piece of code to repeat forever, for example -WhileLoop For loops are traditionally used when you have a piece of code which you want to repeat n number of times. As an alternative, there is the WhileLoop, however, while is used when a condition is to be met, or if you want a piece of code to repeat forever, for example -WhileLoop For loops are used when the number of iterations are known before hand. The name for-loop comes from the English word “for”, which is used as the keyword in most languages. The term in English dates to ALGOL 58

For Loops and game design … Take, for example, the game ‘Super Mario’. For loops can be used to create a timed interval recall loop for each animation. See if you can spot the “for loop” in the code below. It would be hard to come across a programmed game that has not utilised a for loop of some kind in its code.

The anatomy of a For Loop for in : else: for in : else: The For Loop can step through the items in any ordered sequence list, i.e. string, lists, tuples, the keys of dictionaries and other iterables. It starts with the keyword "for" followed by an arbitrary variable name. This will hold the values of the following sequence object, which is stepped through. Generally, the syntax looks like this:

Task 1: Predict the output (using For Loops) Predict the output, then code it yourself to see if you were right! Both of these do the same thing. Note: 0 is the starting point. Look out for FORMAT SPECIFIERS: The %d specifier refers specifically to a decimal (base 10) integer. The %s specifier refers to a Python string.

Were your predictions right? Answers: This is the Fibonacci sequence!

Nested Loops And now for a Nested Loop. This will break each word into its constituent letters and print them out. A Nested loop is basically a loop within a loop. You can have a for loop inside a while loop or vice versa. Let’s start with something simple. Use a for loop to print out the items in a list. OUTPUT

Challenge 1: 3 and 4 times table up to 10 This bit of code produces the times tables for the numbers 1 and 2 (and only up to 5). Can you change it to produce the following? (3 and 4 times table up to 10) 1.Type in the code below (nested loop used) 2.Run it to see what it does 3.Now try and change the values in the program to get it to do what is required. 4.Once done, play around with these values and get it to produce more timestables! You could go all the way up to 100! 1.Type in the code below (nested loop used) 2.Run it to see what it does 3.Now try and change the values in the program to get it to do what is required. 4.Once done, play around with these values and get it to produce more timestables! You could go all the way up to 100! Desired output

Solution1: 3 and 4 times table up to 10 The key is to understand the way the “range” works in Python. Change the numbers to the following and it should work! Now you can experiment with doing more! Output Change the above to ….

The ‘Break’ statement – how it works! found = False # initial assumption for value in values_to_check() : if is_what_im_looking_for(value) : found = True break #end if #end for #... found is True on success, False on failure found = False # initial assumption for value in values_to_check() : if is_what_im_looking_for(value) : found = True break #end if #end for #... found is True on success, False on failure Having no way out of a situation is never a good thing! In python programming, you can use the ‘Break’ statement to exit a loop – say for instance the conditions of the loop aren’t met.

Note how ‘break’ provides an early exit Having no way out of a situation is never a good thing! In python programming, you can use the ‘Break’ statement to exit a loop – say for instance the conditions of the loop aren’t met. OUTPUT Note only 1,2,3,4 are printed from the range and once x = 5, the loop is exited! OUTPUT? Nothing! This is because the loop finds ‘1’ and breaks before it can do anything! ???????

Challenge 2: Extend the code and get someone to try out your program! 1.Copy the code on the right and analyse how it works (notice use of user input, lists and for loops) 2.Extend the program to: a)Ask the user how many more holidays they are planning for the coming year(s) b)Allow them to enter the places they would like to visit c)Append these new values to the list. d)Print the new list. e)If they enter a number over 10 or zero, exit the loop. 1.Copy the code on the right and analyse how it works (notice use of user input, lists and for loops) 2.Extend the program to: a)Ask the user how many more holidays they are planning for the coming year(s) b)Allow them to enter the places they would like to visit c)Append these new values to the list. d)Print the new list. e)If they enter a number over 10 or zero, exit the loop. print ("**********Hello, welcome to the program***********") print ("This program will ask you to enter the names of places you've been to") print ("Before we get started, please enter the number of places you want to enter") number = int(input("How many holidays have you had this year?: ")) print ("Thank you!") print ("We'll now ask you to enter all the places you've traveled to: ") places_traveled = [] #Empty list created to hold entered values for i in range(number): #range(number) used because we want to limit number of inputs to user choice places = input("Enter Place:") places_traveled.append(places) print (("Here's a list of places you've been to: \n"), places_traveled)

Challenge 3:The beginnings of an Arithmetic Quiz Program. Can you extend it? 1.Copy the code on the right and analyse how it works (notice use of random function and for loops) 2.Extend the program to: a)Create more questions (what would you need to change to do this?) b)Add a division operator to the mix so that the questions also extend to division. c)Gifted and Talented: What else could you add to make this program more interesting? How about a score variable that increments each time an answer is correct? 1.Copy the code on the right and analyse how it works (notice use of random function and for loops) 2.Extend the program to: a)Create more questions (what would you need to change to do this?) b)Add a division operator to the mix so that the questions also extend to division. c)Gifted and Talented: What else could you add to make this program more interesting? How about a score variable that increments each time an answer is correct? # # Name: Maths Quiz # Purpose: Tutorial # Author: teachingcomputing.com # Created: 23/02/2016 # Copyright: (c) teachingcomputing.com 2016 # import random #identifying the variables we will be using score=0 answer=0 operators=("x", "+", "-") #Randomly generate the numbers and operators we will be using in this Maths Quiz #The For in in range loop will tell us how many times to repeat the program for i in range(3): #variable num is equal to a random number between 5 and 10 num1=random.randint(5,10) #this will generate a random number between 1 and 5 num2=random.randint(1,5) #select an operator of choice operator=random.choice(operators) #Now we need to calculate the answer! For that, we need to know which operator is being used if operator=="+": answer=num1+num2 elif operator=="-": answer=num1-num2 elif operator=="x": answer=num1*num2 #Creating the question (randomly generated) and create user's input #remember the lines to follow should be indented to be IN the above for loop print('What is' + str(num1)+operator+str(num2)) user_answer=int(input("Enter Answer: ")) #This section allows for the user's response if user_answer==answer: print("That's Right") else: print("Not quite, sorry! The answer was: " + str(answer)) score=score

Discussion: Is the universe Binary? You may find Wikipedia’s listing on digital universe possibilities an interesting read In physics and cosmology, digital physics is a collection of theoretical perspectives based on the premise that the universe is, at heart, describable by information and is therefore computable. Some scientists say that the universe may in fact be a computer program.

Useful Videos to watch on covered topics What is the nature of the universe we live in? Recommended video on Python For Loops

Suggested Project / HW / Research  Create a research information point on Gottfried Leibniz  Basic facts about him  Achievements  His interpretation and understanding of Binary  How Binary plays a role in computers today!  Write an essay (or create an informational power point) on ‘DO WE LIVE IN A BINARY UNIVERSE?”  What were Konrad Zuse’s views on a Binary/ digital universe  Charles Babbage claimed that miracles were the ‘master programmer’ at work – do you agree?  If there is a God (higher power) might he be a programmer?  What arguments (for and against) a Binary universe can you present?  Create a research information point on Gottfried Leibniz  Basic facts about him  Achievements  His interpretation and understanding of Binary  How Binary plays a role in computers today!  Write an essay (or create an informational power point) on ‘DO WE LIVE IN A BINARY UNIVERSE?”  What were Konrad Zuse’s views on a Binary/ digital universe  Charles Babbage claimed that miracles were the ‘master programmer’ at work – do you agree?  If there is a God (higher power) might he be a programmer?  What arguments (for and against) a Binary universe can you present? Gottfried Leibniz Konrad Zuse

Useful links and additional reading