1 / 35

Python

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

theola
Download Presentation

Python

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Python November 28, Unit 9+

  2. 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

  3. 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

  4. 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

  5. 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

  6. 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)

  7. 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

  8. 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

  9. 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

  10. 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()

  11. 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

  12. 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

  13. 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

  14. 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

  15. 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”

  16. 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

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

  18. 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

  19. 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”]

  20. 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”

  21. 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

  22. listOfNames=[“Sam”,”Jim”, “Amy”,”Art”,”May”,”Max”,”Jen”,”Ray] Sam Jim Amy Art May Max Jen Ray 0 1 2 3 4 5 6 7 Index Lists, cont. • 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

  23. 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

  24. 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

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

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

  27. 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

  28. 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”]

  29. 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”

  30. 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

  31. 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

  32. 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

  33. 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

  34. 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

  35. Questions?

More Related