Python Programming Lesson on Tuples, Lists, and More

design based thinking defining possibilities n.w
1 / 69
Embed
Share

Explore the world of Python programming with a focus on tuples, lists, and dictionaries. Learn about immutable tuples, dynamic lists, and how to manipulate data structures efficiently. Dive into the basics of indexing, slicing, and adding elements to lists, along with user input and variable comparisons. Get ready to enhance your data analysis skills in upcoming lessons!

  • Python Programming
  • Data Structures
  • Tuples
  • Lists
  • User Input

Uploaded on | 0 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.

E N D

Presentation Transcript


  1. Design-Based Thinking: Defining Possibilities for Innovation Introduction to Python Programming Lesson 2 Developed & Delivered by: Jim Cody jcodygroup@gmail.com www.axiomlearningsolutions.com

  2. Today Tuples, List, Dictionary Prompt the User Comparing Variables If/Else Loops Methods User Defined Functions Lesson 3: Data Analysis Lesson 4: More Data Analysis . Maybe some MySQL 2

  3. Tuples Unchanging Sequences of Data Tuples are a sequence of values, each one accessible individually, and a tuple is a basic type in Python. Tuples are immutable and tuples use parentheses and. We can recognize tuples when they are created because they re surrounded by parentheses: tup1 = ('physics', 'chemistry', 1997, 2000); tup2 = (1, 2, 3, 4, 5 ); tup3 = "a", "b", "c", "d"; 3

  4. List Lists, like tuples, are sequences that contain elements referenced starting at zero. Lists are created by using square brackets. Like tuples, the elements in a list are referenced starting at 0 and are accessed in the same order from 0 until the end. >>> breakfast = [ coffee , tea , toast , egg ] Indexing: Returns a single value Slicing: Returns multiple values 4

  5. List Index & Slice Indexing: Returns a single value Slicing: Returns multiple values 5

  6. Adding to a String List

  7. List - Numeric squares = [1,4,9,16,25] squares squares[0] squares + [36,49,64] 7

  8. Prompt the User some_variable_name = input("Ask a question here?")

  9. Comparing Values Comparing Values Are They the Same? Doing the Opposite Not Equal Comparing Values Which One Is More? Reversing True and False Looking for the Results of More Than One Comparison 10

  10. Comparing Values Are They the Same? True and False are the results of comparing values, asking questions, and performing other actions. However, anything that can be given a value and a name can be compared with the set of comparison operations that return True and False. >>> 1 == 1 True >>> 1 == 2 False >>> 1.23 == 1 False >>> 1.0 == 1 True 11

  11. Comparing Values Are They the Same? >>> a = Mackintosh apples >>> b = Black Berries >>> c = Golden Delicious apples >>> a == b False >>> b == c False >>> a[-len( apples ):-1] == c[-len( apples ):-1] True 12

  12. Doing the Opposite Not Equal There is an opposite operation to the equality comparison. If you use the exclamation and equals together, you are asking Python for a comparison between any two values that are not equal to result in a True value. >>> 3 == 3 True >>> 3 != 3 False >>> 5 != 4 True 13

  13. Comparing Values Which One Is More? Sometimes you will want to know whether a quantity of something is greater than that of another, or whether a value is less than some other value. Python has greater than and less than operations that can be invoked with the > and < characters, respectively. >>> 5 < 3 False >>> 10 > 2 True 14

  14. Comparing Values Which One Is More? >>> Zebra > aardvark False >>> Zebra > Zebrb False >>> Zebra < Zebrb True >>> a > b False >>> A > b False >>> A > a False >>> b > A True >>> Z > a False 15

  15. Comparing Values Which One Is More? >>> Pumpkin == pumpkin False >>> Pumpkin .lower() == pumpkin .lower() True >>> Pumpkin .lower() pumpkin >>> Pumpkin .upper() == pumpkin .upper() True >>> pumpkin .upper() PUMPKIN 16

  16. Comparing Values Which One Is More? >>> 1 > 1 False >>> 1 >= 2 False >>> 10 < 10 False >>> 10 <= 10 True 17

  17. Reversing True and False When you are creating situations and comparing their outcomes, sometimes you want to know whether something is true, and sometimes you want to know whether something is not true. Sensibly enough, Python has an operation to create the opposite situation the word not provides the opposite of the truth value that follows it. >>> not True False >>> not 5 False >>> not 0 True >>> Not True SyntaxError: invalid syntax (<pyshell#30>, line 1) 18

  18. And Operator You can also combine the results of more than one operation, which enables your programs to make more complex decisions by evaluating the truth values of more than one operation. One kind of combination is the and operation, which says if the operation, value, or object on my left evaluates to being True, move to my right and evaluate that. If it doesn t evaluate to True, just stop and say False don t do any more. 19

  19. And Operator >>> True and True True >>> False and True False >>> True and False False >>> False and False False 20

  20. Or Operator The other kind of combining operation is the or operator. Using the or tells Python to evaluate the expression on the left, and if it is False, Python will evaluate the expression on the right. If it is True, Python will stop evaluation of any more expressions. >>> True or True True >>> True or False True >>> False or True True >>> False or False False 21

  21. If/Else The reserved word for decision making is if, and it is followed by a test for the truth of a condition, and the test is ended with a colon. >>> if 1 > 2: print( No it is not! ) ... >>> if 2 > 1: print( Yes it is! ) ... Yes, it is! 23

  22. If/Else If statement In simple terms, the Python if statement selects actions to perform. The if statement may contain other statements, including other ifs. x = 'killer rabbit' if x == 'roger': print("how's jessica?") elif x == 'bugs': print("what's up doc?") else: print('Run away! Run away!') if <test1>: <statements1> elif <test2>: <statements2> Else: <statements3> #if test # Associated block # Optional elifs # Optional else Run away! Run away! 24

  23. How to Get Decisions Made This dictionary is a multiway branch indexing on the key choice branches to one of a set of values, much like a switch in C. >>> choice = 'ham' >>> print({'spam': 1.25, 'bacon': 1.10}[choice]) # A dictionary-based 'switch' # Use has_key or get for default 'ham': 1.99, 'eggs': 0.99, 1.99 25

  24. If/Else An almost equivalent but more verbose Python if statement. Notice the else clause on the if here to handle the default case when no key matches. >>> if choice == 'spam': print(1.25) ... elif choice == 'ham': print(1.99) ... elif choice == 'eggs': print(0.99) ... elif choice == 'bacon': ... else: ... 1.99 print(1.10) print('Bad choice') 26

  25. Get >>> branch = {'spam': 1.25, 'ham': 1.99, 'eggs': 0.99} >>> print(branch.get('spam', 'Bad choice')) 1.25 >>> print(branch.get('bacon', 'Bad choice')) Bad choice >>>choice = 'bacon' >>>if choice in branch: else: choice') Bad choice print(branch[choice]) print('Bad 27

  26. How to Get Decisions Made Python Syntax Rules Statements execute one after another, until you say otherwise. Block and statement boundaries are detected automatically. Compound statements = header + : + indented statements. Blank lines, spaces, and comments are usually ignored. Docstrings are ignored but are saved and displayed by tools. 28

  27. Loops There may be a situation when you need to execute a block of code several number of times. In general, statements are executed sequentially. Loop Type while loop Description Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body. Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable. for loop You can use one or more loop inside any another while, for or do..while loop. nested loops 30

  28. While Loop While loop Python s while statement is the most general iteration construct in the language. It repeatedly executes a block of statements as long as a test at the top keeps evaluating to a true value. while <test>: <statements1> else: <statements2> # Loop test # Loop body # Optional else # Run if didn't exit loop with break 31

  29. While Loop >>> x = 'spam' >>> while x: spam pam am m # While x is not empty print(x) x = x[1:] # Strip first character off x # One way to code counter loops >>> a=0; b=10 >>> while a < b: .. . 0 1 2 3 4 5 6 7 8 9 print(a, end=' ') a += 1 # Or, a = a + 1 32

  30. For Loop for loop The for loop in Python has the ability to iterate over the items of any sequence, such as a list or a string. it can step through the items in any ordered sequence object. The for statement works on strings, lists, tuples, other built-in iterables. for <target> in <object>: <statements> else: <statements> # Assign object items to target # Repeated loop body: use target # If we didn't hit a 'break' 33

  31. For Loop for <target> in <object>: <statements> if <test>: break if <test>: continue else: <statements> # Assign object items to target # Exit loop now, skip else # Go to top of loop now # If we didn't hit a 'break' >>> for x in ["spam", "eggs", "ham"]: print(x) ... spam eggs ham 34

  32. For Loop >>> S = "lumberjack" >>> for x in S: ... # Iterate over a string print(x) l u m b e r j a c k >>> T = [(1, 2), (3, 4), (5, 6)] >>> for (a, b) in T: print(a, b) ... 1 2 3 4 5 6 >>> D = {'a': 1, 'b': 2, 'c': 3} >>> for key in D: print(key, '=>', D[key]) ... a => 1 c => 3 b => 2 35

  33. For Loop >>> D = {'a': 1, 'b': 2, 'c': 3} >>> for (key, value) in D.items(): print(key, '=>', value) ... a => 1 c => 3 b => 2 for num in range(10,20): for i in range(2,num): . else: print num #to iterate between 10 to 20 #to iterate on the factors of the number # else part of the loop 36

  34. For Loop Iterators >>> for x in [1, 2, 3, 4]: print(x ** 2) ... 1 4 9 16 >>> for x in (1, 2, 3, 4): print(x ** 3) ... 1 8 27 64 for num in range(10,20): for i in range(2,num): . else: print num #to iterate between 10 to 20 #to iterate on the factors of the number # else part of the loop 37

  35. Functions: Grouping Code under a Name A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing. 39

  36. Built-in Functions https://docs.python.org/2/library/functions.html

  37. Functions: Grouping Code under a Name As you already know, Python gives you many built-in functions like print(), etc. but you can also create your own functions. These functions are called user-defined functions. 41

  38. Functions: Grouping Code under a Name Defining a Function Here are simple rules to define a function in Python. Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ). Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses. 42

  39. Functions: Grouping Code under a Name The first statement of a function can be an optional statement - the documentation string of the function or docstring. The code block within every function starts with a colon (:) and is indented. The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None. 43

  40. Functions: Grouping Code under a Name def functionname( parameters ): "function_docstring" function_suite return [expression] def printme( str ): "This prints a passed string into this function" print str return 44

  41. Functions: Grouping Code under a Name Calling a Function # Function definition is here def printme( str ): "This prints a passed string into this function" print str; return; # Now you can call printme function printme("I'm first call to user defined function!"); printme("Again second call to the same function"); I'm first call to user defined function! Again second call to the same function 45

  42. Functions: Grouping Code under a Name def Executes at Runtime if test: # Define func this way def func(): ... else: def func(): # Or else this way ... ... Func() # Call the version selected and built 46

  43. Functions: Grouping Code under a Name def is much like an = statement: it simply assigns a name at runtime. Unlike in compiled languages such as C, Python functions do not need to be fully defined before the program runs. More generally, defs are not evaluated until they are reached and run, and the code inside defs is not evaluated until the functions are later called. 47

  44. Functions: Grouping Code under a Name Pass by reference vs value All parameters (arguments) in the Python language are passed by reference. It means if you change what a parameter refers to within a function, the change also reflects back in the calling function. 48

  45. Functions: Grouping Code under a Name Pass by reference vs value If you pass a mutable object into a method, the method gets a reference to that same object and you can mutate it to your heart's delight, but if you rebind the reference in the method, the outer scope will know nothing about it, and after you're done, the outer reference will still point at the original object. If you pass an immutable object to a method, you still can't rebind the outer reference, and you can't even mutate the object. 49

  46. Functions: Grouping Code under a Name Pass by reference vs value def try_to_change_list_contents(the_list): print 'got', the_list the_list.append('four') print 'changed to', the_list outer_list = ['one', 'two', 'three'] print 'before, outer_list =', outer_list try_to_change_list_contents(outer_list) print 'after, outer_list =', outer_list before, outer_list = ['one', 'two', 'three'] got ['one', 'two', 'three'] changed to ['one', 'two', 'three', 'four'] after, outer_list = ['one', 'two', 'three', 'four'] 50

Related


More Related Content