Python November 28, Unit 9+. Local and Global Variables There are two main types of variables in Python: local and global –The explanation of local and.

Slides:



Advertisements
Similar presentations
Why not just use Arrays? Java ArrayLists.
Advertisements

Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop.
Arrays A list is an ordered collection of scalars. An array is a variable that holds a list. Arrays have a minimum size of 0 and a very large maximum size.
ThinkPython Ch. 10 CS104 Students o CS104 n Prof. Norman.
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?
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.
Lists Introduction to Computing Science and Programming I.
Topic 9 – Introduction To Arrays. CISC105 – Topic 9 Introduction to Data Structures Thus far, we have seen “simple” data types. These refers to a single.
Python (yay!) November 16, Unit 7. Recap We can store values in variables using an assignment statement >>>x = We can get input from the user using.
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.
ECE122 L11: For loops and Arrays March 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 11 For Loops and Arrays.
JaySummet IPRE Python Review 2. 2 Outline Compound Data Types: Strings, Tuples, Lists & Dictionaries Immutable types: Strings Tuples Accessing.
CS0007: Introduction to Computer Programming Introduction to Arrays.
CMPT 120 Lists and Strings Summer 2012 Instructor: Hassan Khosravi.
Games and Simulations O-O Programming in Java The Walker School
Simple Python Loops Sec 9-7 Web Design.
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
Lists in Python.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
Python Programming Chapter 6: Iteration Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
CPS120 Introduction to Computer Science Iteration (Looping)
What is an Array? An array is a collection of variables. Arrays have three important properties: –group of related items(for example, temperature for.
Arrays 1 Multiple values per variable. Why arrays? Can you collect one value from the user? How about two? Twenty? Two hundred? How about… I need to collect.
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.
5 BASIC CONCEPTS OF ANY PROGRAMMING LANGUAGE Let’s get started …
Built-in Data Structures in Python An Introduction.
Chapter 8: Arrays and Functions Department of Computer Science Foundation Year Program Umm Alqura University, Makkah Computer Programming Skills
With Python.  One of the most useful abilities of programming is the ability to manipulate files.  Python’s operations for file management are relatively.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
I Power Higher Computing Software Development High Level Language Constructs.
Introduction to Loops For Loops. Motivation for Using Loops So far, everything we’ve done in MATLAB, you could probably do by hand: Mathematical operations.
Scripting Languages Diana Trandab ă ț Master in Computational Linguistics - 1 st year
CPS120 Introduction to Computer Science Iteration (Looping)
ActionScript: For Loops, While Loops, Concatenation and Arrays MMP 220 Multimedia Programming This material was prepared for students in MMP220 Multimedia.
Passing Arguments, Local/Global Variables Writing Functions( ) (Part 2)
1 Printing in Python Every program needs to do some output This is usually to the screen (shell window) Later we’ll see graphics windows and external files.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
Chapter 5 Linked List by Before you learn Linked List 3 rd level of Data Structures Intermediate Level of Understanding for C++ Please.
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
Python 1 SIGCS 1 Intro to Python March 7, 2012 Presented by Pamela A Moore & Zenia C Bahorski 1.
Arrays and Loops. Learning Objectives By the end of this lecture, you should be able to: – Understand what a loop is – Appreciate the need for loops and.
Today… Python Keywords. Iteration (or “Loops”!) Winter 2016CISC101 - Prof. McLeod1.
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.
CSC 1010 Programming for All Lecture 5 Functions Some material based on material from Marty Stepp, Instructor, University of Washington.
String and Lists Dr. José M. Reyes Álamo.
CS170 – Week 1 Lecture 3: Foundation Ismail abumuhfouz.
Loops BIS1523 – Lecture 10.
CS 115 Lecture 8 Structured Programming; for loops
Miscellaneous Items Loop control, block labels, unless/until, backwards syntax for “if” statements, split, join, substring, length, logical operators,
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.
Chapter 4 LOOPS © Bobby Hoggard, Department of Computer Science, East Carolina University / These slides may not be used or duplicated without permission.
Arrays, For loop While loop Do while loop
File Handling Programming Guides.
Bryan Burlingame 03 October 2018
Java Programming Arrays
CISC101 Reminders Assn 3 due tomorrow, 7pm.
Data Structures – 1D Lists
Coding Concepts (Data Structures)
String and Lists Dr. José M. Reyes Álamo.
Remembering lists of values lists
For loops Taken from notes by Dr. Neil Moore
Python Review
For loop Using lists.
CISC101 Reminders Assignment 3 due today.
Class code for pythonroom.com cchsp2cs
Dictionary.
Introduction to Computer Science
Presentation transcript:

Python November 28, Unit 9+

Local and Global Variables There are two main types of variables in Python: local and global –The explanation of local and global is given here only in terms of what we’ve covered Global variables can be accessed by any of the functions in your program Local variables are “local” to the function they were created in

Global Variables Variables declared outside of a function are usually global x = 5 def someFunction(a,b) z = a+b+x return z x is a global variable here The function, someFunction(a,b) can access the value stored in x –If it couldn’t an error would result

Local Variables Local variables are those variables which only exist inside of a particular function –They are “local” to the function x = 5 def someFunction(a,b) z = a+b+x return z In this function: a, b, and z are all local variables

Local and Global Variables, cont. When looking up a variable, Python checks the local variables first, then the global variables What does this mean? –You can have global and local variables with the same name –But, they don’t have to have the same value Local variables are good because they protect you from changing values on variables you may want to reuse by accident. –Come with more complicated programming mostly

Local and Global Example x = 5 def someFunction(a,b) x = 6 z = a+b+x return z In this example, we have a global variable x And, a local variable x (along with z, a, and b)

Example, cont. x = 5 def someFunction(a,b) x = 6 z = a+b+x return z Num = someFunction(2,1) print “num is: “, num, “ and x is: “, x This program would print: “num is: 9, and x is 5” The local variable x is used for the calculation of z, but the print statement doesn’t see that local x –It uses the global x instead

Another Example of Local and Global Variables a =2 b = 3 x = 5 def someFunction(a,b): x = 6 z = a + b +c Num = someFunction(2,1) print a, b, x This would print 2, 3, 5 In someFunction(), a is given the value of 2 and b is given the value of 1 –But these are local variables –Does not affect the values of the global variables a and b

Local Variables and Multiple Functions If you declare a variable inside of a function, it can only be used inside of that function Outside of that function it either: –Won’t exist –Or will actually be a different variable If you declare a variable inside of one function, it cannot be used by another function

Multiple Function Example def firstFunction(): x = 2 print x def secondFunction(): z = x*2 print z This would cause an error –x is not defined for secondFunction()

Issues with Global Variables Before a function can use a global variable, it must be declared You can put your function definitions at the top of your Python program even if they use global variables But, before you call your function, the global variables must be declared –Remember declaring a variable involves assigning it a value

Example with Global Variables def someFunction(a): z = x*a return z x = 3 num = someFunction(2) print num This program executes fine because x is delcared before someFunction() is called

Program with Error def someFunction(a): z = x*a return z num = someFunction(2) x = 3 print num This program will not execute because Python runs sequentially –You can’t use the value of x before it is declared –It is declared after the function which uses x has been called

Changing the Value of a Global Variable In a Function If we try to assign a new value to a global variable inside of a function, all it does is create a new local variable of the same name def someFunc(a) x = a return x x =2 print someFunc(3) The x inside of the function is the local x

Changing Globals, cont. Python does, however, provide a way to change the value of global variables We can use the global keyword To use it we apply it to the variable we want before we assign it a value –Basically says “the x I’m going to use is the global x”

Value of Globals, cont. def someFunction(a) global x x = x*a x =3 someFunction(2) print x This would print the value of 6 for x –Without the global it would print the value of 3 The global keyword allows us to modify a global variable –Should be used sparingly

In-Class Runs of Examples Simple local and global example Multiple function example Using global keyword

Lists Lists in Python look and act a lot like arrays in other languages What is a list? –It is an ordered collection of Python values Basically, it allows us to group a bunch of values under one variable name The values can be any python objects –Unlike arrays in many languages which all must be of the same type

Example of a List We can create a list by using square brackets and separating the values with commas in the following manner: –breadList = [“flour”, “oil”, “yeast”, “butter”] –In this case a list of ingredients for a loaf of bread If I print the list: [“flour”, “oil”, “yeast”, “butter”]

Accessing Individual Values Having a list of a bunch of values does us little good unless we can access the individual elements of the list We can access individual elements by their index –Index is their number in the order of the list breadList[2] has the value “yeast” breadList[0] has the value “oil”

Indexes in Lists When counting the index in a list, it starts at 0 and not 1 –Seems a bit counter-intuitive at first –Fairly standard for many programming languages A list of 8 items has indices from 0-7 A list of 200 items has indices from 0-199

Many people have difficulty grasping the concept of a list at first One useful metaphor is a series of bins Each bin holds a value Lists, cont. listOfNames=[“Sam”,”Jim”, “Amy”,”Art”,”May”,”Max”,”Jen”,”Ray] SamAmyArtMayMaxJenRayJim Index

Using a List We can access individual elements by their index number –Name = listOfNames[2] –i =3 Name = listOfNames[i] Another way of accessing the elements in a list is by using a for loop

For Loop For loops are more restricted than while loops –While loops check to see if a condition is true and execute code based on that –For loops execute code a specific number of times The basic syntax of a for loops is: for i in someList: code to execute

Simple For Loop Example print ”To make bread you need: for ingred in breadList: print ingred This would print: flour oil yeast butter

Another Simple Example for ingred in breadList: print “I love baking ” This would print: “I love baking”

For Loops, cont. You can think of a for loop as reading : –For each item in my list of items: Execute this code So, if our list has 4 items with indices ranging from 0-3 –Our loop executes 4 times

Adding Values to a List We do not have to declare every item in our list at the start We can add values to our list by using the append function Given our previous breadList, if we wanted to add an item: breadList.append(“sugar”) breadList.append(“salt”) Now, breadList= [“flour”, “oil”, “yeast”, “butter”, “sugar”, “salt”]

Deleting Values We can remove a value from our list by using the del keyword –We must know the index of the item we want to delete del breadList[0] would remove “flour” del breadList[2] would remove “yeast”

Other Simple List Operations + is the concatenation operator –If we use it on two lists it adds them together –aList = [1,2,3] –bList = [4,5,6] –cList = aList+bList –cList would now be [1,2,3,4,5,6] The * or multiplication operator repeats a list a given number of times –cList = aList*2 –cList would now be [1,2,3,1,2,3] –You cannot multiply two lists together cList = aList*bList will give you an error

range(someNumber) Function range() is a useful function for for loops range returns a list of values from 0 to someNumber -1 Example: print range(5) would print [0,1,2,3,4] This is great for for loops where you simply want to count and aren’t using a separate list

For Loop with range() Example for i in range(10) print i This would print the numbers from 0 to 9 for i in range(10) print i+1 This would print the numbers from 1 to 10

Range(), cont. We can specify start and stop values for range as well, where the first number is the start value and the second number is the stop value –range(2,10) Prints 2, 3, 4,5, 6, 7,8,9 And we can specify the step –Step is how much we count by each time (last number is the step) –range(2,10,2) Prints 2,4,6,8 The step can be backwards as well –range(10,2, -2) Prints 10, 8, 6, 4 Great for counting downwards –To countdown by 1, specify the step to be -1

While Loops and For Loops Any for loop can be written as a while loop for i in range(1,11): print i i =1 while i<=10 print I So why use for loops? –They nicer when looping through regular lists (not produced by range()) –They are better when we know exactly how many times we want the loop to execute They don’t require a separate counter variable Can use the range function to loop a certain number of times

Questions?