Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Python - Intro to programming

Vina
June 27, 2018

Python - Intro to programming

Vina

June 27, 2018
Tweet

More Decks by Vina

Other Decks in Education

Transcript

  1. Computer Program - A computer program is a set of

    instructions that causes a computer to perform some kind of action. - Software, not hardware
  2. Normally… - You need another program to write your program

    in - And download a ton of other things - But we’ll don’t have to worry about it
  3. About Python - Created by Guido van Rossum - Named

    after the BBC TV Show “Monty Python’s Flying Circus” - Simple and minimalistic compared to other programs - It’s almost like English - Free and Open Sourced - Powerful
  4. Pseudocode - Not real code - Images, diagrams, or writing

    that describe code - Help you figure out what you want to code without real code
  5. Syntax - Lower case (it matters) - Start on a

    new line every time you write a new step - For every block of code that is related to one step, you should indent and start a new line - All of this also help keep your code neat
  6. Variable - Describes a place to store information such as

    numbers, text, lists of numbers and text, and etc. - Has a name that you give it - Must be unique - It’s like a labeled box that is used to contain other stuff
  7. Naming Variables - Variables names can contain only letters, numbers,

    and underscore. - Cannot start with a number - Spaces are not allowed - Use underscore instead - Do not use python keywords and function names as variable names - Variable names should be short but descriptive
  8. String - Refers to that bit of text you want

    to display to someone. - Ex. print(Hello World!) - Hello world! is the String - You can have an empty String - 0 characters but it exist - Position # of a String - Hello World - H = 0 - d = 10 - Space = 5
  9. Strings cat = cats are domesticated felines print(cat) What did

    you get when you forget the quotations?
  10. Syntax error - SyntaxError means you made a mistake in

    the arrangement and order of words in your code - You did something Python did not expect - EOL means end-of-line - Your program stopped at the end of the line and did not find a double quote to close the string Try and see what other errors you can get by messing up the syntax
  11. Printing a variable and a string • Try printing out

    a string stored in a variable with another string - greeting = “Hello” - print(greeting + “ Vina!”)
  12. Make your own variables (Mad Libs) Store Strings in the

    follow variable names: • my_name • adjective_1 • emotion • memory • plural_noun_1 • adjective_2 • plural_noun_2 • something_delicious • something_yucky • adjective_3 • noun
  13. Make your computer print this with the corresponding variable name

    print(“My name is ” + your_name + “and…
  14. Order of Operations - Basic Math - PEMDAS - Parentheses

    first, exponents, multiply, divide, add, subtract
  15. Calculate these: record your answers 1. 5 + 30 *

    20 2. (5 + 30) * 20 3. (5 + 30) * 20 / 10 4. 6 + 34 * 15 / 8 5. 6 + 34 * 15.0 / 8 Print(5 + 30 * 20) Print((5 + 30) * 20)
  16. Answer these problems (see if you can solve these yourself)

    Bob = 100, Anna = 5, kyle = 39 1. Bob - 32 + Anna = ? 2. Anna - Kyle = ? 3. Bob + Anna + Kyle ?
  17. Decimals - If you don’t have a decimal on the

    left side of your equation, you won’t get a decimal answer. - It never rounds up or down. It Truncates your number 0.7 = ? 2.4 = ? 7.943 =? 43.0 = ?
  18. Print a String and a integer on the same line

    • Example: Bob = 100 • print(“Bob = 100”) • Or • bob = 100 ß the variable you already stored • print(“Bob had this amount of money =“ + str(bob)) ◦ turns your number into a string
  19. Embedding Values in String Now combine number variables and string

    variables together in a sentence - You can use this : %s - This acts like an marker for a value you want to add later
  20. More math functions • ** (exponents) • % (find remainder)

    2^2 = 4 Python code: 2**2 = 4 Python code: 10 % 3 = 1
  21. More math functions (for fun) • abs(x) • min(x) •

    max(x) • pow(x) ◦ pow(2 , 2) ◦ 2**2 • sum(x) ◦ sum( 1, 2 , 3 , 4 )
  22. Functions • Just like variables • You’re storing steps into

    a container (called functions) • You can name them too, just like the way you name variables
  23. For example • 1. def function_name(x) • 2. return what

    you want the function to do • 2. print the result
  24. Cont. • Notice the indentation. We’re grouping statements together. •

    What are some functions we already know and used? ◦ Hint: these are already created and saved into Python language library
  25. Where can we use it? • If you need to

    calculate a math equation over and over again • Ex. Finding the area of many different rectangles from a list: ◦ Math problem: Find the area of the following rectangles 5 by 5 6 by 8 150 by 93 43 by 29.3 Def area(x, y) : return x*y
  26. Try it out! • Write a function to find the

    area of a triangle given 2 numbers (height and base) • See if you get the correct answer if height = 15 , base = 4.3
  27. Congratulations! You know enough coding for you write a program

    to get your computer to do your math homework for you! (most practical for a series of problems requiring the same formula)
  28. Lists • Allows you to store sets of information in

    one place, whether you have just a few items or millions of items ◦ Can put strings, numbers, a lot of things ◦ You can name them too like how you name variables ▪ Name them pural words like bicycles, cats, dogs • Very important. Will use list a lot in coding
  29. Code for lists • Just like making a variable, except

    you use [‘…. ‘ , ‘…. ‘ ] • Example: ◦ Writing an variable: ▪ bicycle = “trek” ◦ Writing a list: ▪ bicycle = [‘trek’, ‘cannondale’ , ‘redline’ , ‘pedal’]
  30. Numbers in a list • If you have a list

    that contains numbers, you don’t need the quotations • List of strings need “ ” List1 = [1, 2, 3, 4] - You can also multiply a list by a number. Try multiplying list1 by 5 and print it out
  31. answer • list1=[1, 2] • print(list1 * 5) • [1,

    2, 1, 2, 1, 2 ,1, 2, 1, 2] • So you can’t use +, /, or – to a list like we just did with * • Why? Because the computer is dumb
  32. Tuples • Is like a list that uses parentheses •

    You should of noticed by now that lists use brackets [ ] • You cannot change a tuple once you created it ◦ A list you can change it
  33. Elements • They are the things that you stored in

    a list • bicycle = [‘trek’, ‘cannondale’ , ‘redline’ , ‘pedal’] ◦ Trek, cannondale, redline, pedal are the elements
  34. Index positions • When you store something into a list,

    it has a positions number • The position number starts at 0 ◦ Usually the case for most programming languages bicycle = [‘trek’, ‘cannondale’ , ‘redline’ , ‘pedal’] If you want to print the first element in the list, you would do this: print(list_name [ the number ]) print(bicycle[0])
  35. Create your own list and print the third element •

    Make a list of names • Print the 3rd name on your list • Also print “The third person’s name is ” before the name, on the same line ◦ Bonus if you store the previous message as a variable before you printed it
  36. Special Case, what do you get? • With your previous

    list, try printing the element with the index of [-1] • Example ◦ print (bicycles[-1] )
  37. Debugging • Debugging refers to finding mistakes in your code

    • Back in the days, computers looked like this: • Admiral Grace Hopper, while working on a computer like this, found a moth stuck inside which caused the computer to not work - called it “debugging” the system - the term caught on
  38. When ever your code is doing something unexpected… • You

    need to debug • Use Print statements ◦ Print a line a code after each step you ask the computer to do ◦ When it’s not printing or it prints something wrong, that’s where the mistake is ◦ Helps you see and find where your program stops working
  39. Using Comments • You use comments to organize your code

    • Take notes • # ◦ Anything after the # will be turned into a comment ◦ That means it computer ignores and doesn’t read what is commented out in your code ◦ you can read it in the code, the computer can’t
  40. Modifying Elements in a List 1. Create your list first

    2. Find the index of the element that you want to change 3. Replace the element 4. print
  41. Adding Elements to a List • Make your list •

    list_name.append(“…”) • Adds it to the end of the list • Make your list • list_name.insert(index#, “…”) • Adds it to the specified index
  42. Removing Elements in a List • If you know the

    position of the item you want to remove: • del list_name[index#] • Or list_name.pop(index#) • If you want to remove the last item (sometimes you don’t know how long a list is) • List_name.pop() What do you get? To store it: motorcycles = motorcycles.pop() print(motorcycles)
  43. When to use .pop() or del • When you want

    to delete an item from a list and not use the item in any way, use the del statement • If you want to use an item as you remove it, use pop() ◦ You can store a popped item into a variable
  44. Remove item by value • Sometimes you don’t know the

    position of the value you want to remove • list_name.remove(‘nameofthingtoberemoved) • Everyone make a list of names, but include the name Bob in the list • Remove Bob’s name using the remove function
  45. Maps • Is a collection of things (like a list

    or tuples) • Map has a key and a corresponding value ◦ One key works with one lock ◦ Same thing for maps ◦ You use a key to get through the lock / You use a key to get to the value
  46. List Map • Uses brackets [ ] • Colons •

    Uses a colon to separate the key and the value • Uses braces { } • Colons to separate each key from its value
  47. Activity • Make a map of people’s favorite sports •

    Find out Ethel Smyth’s favorite sports By accessing the map and using her name As the key print(map_name[‘Ethel Smyth’])
  48. Extra • You can del and replace a value in

    a map the same way as list, but use the key deleting replacing
  49. Yes or no? • In programming we ask a lot

    of yes or no questions • For example, we can ask, are you older than 20? ◦ If yes, respond with, “You are too old” ◦ If no, respond with, “You are young!”
  50. Conditions • Those times of yes or no questions are

    called conditions • Or more popularly called if statements ◦ If, yes, then this, if no then that
  51. Block of Code • A block of code is a

    grouped set of programming statements This is a block of code
  52. indentation • Indentation is important and has meaning • You

    group them together if they are related Change the indentation, you’re creating new blocks.
  53. Conditions to Compare things • Comparing things in conditions •

    True (yes) False (no) • Or use operators to create conditions
  54. Multiple conditions using else print(“Want to hear a dirty joke?”)

    age = 12 if age == 12 print(“A pig fell in the mud!”) else: print(“Shh It’s a secret.”) You can change the age To get a different message
  55. If and Elif Statements • Elif is short for else-if

    • After reading this, what would be printed out?
  56. Combining conditions cont. if age >= 10 and age <=

    13: print(‘What is 13+43+4353+5635+? A headache!’) else: print(‘Huh?’)
  57. Special cases • You can assign variables with no value

    • None variable = None print(variable) None Then you should be able to do this, variable == None: print(“there’s nothing here”) The variable does not have a value
  58. Reminder • String and numbers are very different • 10

    is not equal to ‘10’ Remember when we converted an integer into a string? str(10)