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

Python Crash Course

Python Crash Course

Teaching the basics of Python.

@ Bywave

Renemari Padillo

December 08, 2015
Tweet

More Decks by Renemari Padillo

Other Decks in Programming

Transcript

  1. Objectives • Learn how to setup Python • Learn how

    to use Python interactive interpreter (CLI) • Learn how to execute Python scripts • Learn the different data types and variables • Learn arithmetic and comparison operators • Learn how to display and get input
  2. Objectives • Learn conditional statements • Learn loop statements •

    Learn sequential data types • Learn how to create functions
  3. Variables A variable is a way of referring to a

    memory location used by a computer program. A variable is a symbolic name for this physical location. This memory location contains values, like numbers, text or more complicated types. i = 42 name = “Renesansz”
  4. Naming variables A valid identifier of a non-empty sequence of

    characters of any length with the ff: • The start character can be the underscore “_” or a capital(lower) case letters. • The letters following the start character can be anything which is permitted as a start character plus the digits. • Just a warning for Windows-spoilt users: Identifiers are case-sensitive! • Python keywords are not allowed as identifier names! Python reserved keywords: and, as, assert, break, class, continue, def, del, elif, else, except, finally, for, from, global, if, import, in, is, lambda, nonlocal, not, or, pass, raise, return, try, while, with, yield
  5. Numbers • Integers • Normal integers (eg: 123) • Octal

    literals (eg: 010 or 0o10 # 8) • Hexadecimal literals (eg: 0xA0F # 2575) • Binary (eg: 0b100 # 4)
  6. Numbers (Cont.) • Long integers (eg: 402000000000000000009990L) • Floating-point numbers

    (eg: 42.11, 3.145e-10) • Complex numbers <real part> + <imaginary part> >>> x = 3 + 4j >>> y = 2 - 3j >>> z = x + y >>> print z # 5 + 1j
  7. Strings • “This is what we call a string” •

    ‘This is another string, but single quoted’ • “””
 We can do a multi-line string.
 Which is awesome, but will include ‘\n’
 for every new line
 “””
  8. Strings (Cont.) A string in Python consists of a series

    or sequence of characters - letters, numbers, and special characters. Strings can be indexed - often synonymously called subscripted as well. Similar to C, the first character of a string has the index 0. >>> s = “This is an awesome string” >>> s[0]
 ’T’ >>> s[-1]
 ‘g’
  9. String functions & operators Concatenation “Hello” + “World” -> “HelloWorld”

    Repetition “Hello!” * 3 -> “Hello!Hello!Hello!” “Hello”[0] -> ‘H’ Indexing “Hello”[-1] -> ‘o’
  10. String functions & operators (Cont.) Slicing “Hello”[2:4] -> ‘ll’ Size

    len(“Test”) -> 4 “World”[:2] -> ‘wo’ “World”[2:] -> ‘rld’
  11. Operators Operator Description Example +, - Addition, Subtraction 10 +

    3 # 13 10 - 3 # 7 *, /, % Multiplication, Division, Modulo 15 * 3 # 45 10 / 3 # 3 10.0 / 3 # 3.3333333333333335 27 % 7 # 6 // Truncation Division (Floor Division) 10.3 // 3 # 3.0
  12. Operators Operator Description Example +x, -x Unary minus & plus

    (Algebraic Signs) -3 # -3 3 - -3 # 6 ~x Bitwise Negation ~3 - 4 # -8 ** Exponentiation 10**3 # 1000 <<, >> Shift operators 6 << 3 # 48
  13. Operators Operator Description Example or, and, not Boolean Or, And,

    Not (True and False) or False # False (1 and 0) or 1 # 1 in Element of 1 in [1,2,3] # True 0 in [1,2,3] # False <, >, ==, <=, >=, != Usual comparison operators 1000 <= 1000 # True |, &, ^ Bitwise Or, And, Not 6 ^ 3 # 5
  14. Getting user input and display Python provides the function input()

    and raw_input(). Both functions has an optional parameter, which is the prompt string. For output, we use print() to display the data on the screen. name = raw_input(“What's your name? ") print "Nice to meet you " + name + "!" age = input("Your age? ") print "So, you are are already " + str(age) + " years old, " + name + "!"
  15. Formatting output for x in range(1, 11): print ‘{0:2d} {1:3d}

    {2:4d}’.format(x, x*x, x*x*x) # Display 1 1 1 2 4 8 4 16 32 8 32 64
  16. True or False Any value that is empty will have

    always be False, else it resolves to True. • Numerical values (0, 0.0, 0.0+0.0j) • Boolean value False • Empty strings ‘’, “” • Empty list and empty tuples, () [] • Empty dictionaries {} • Plus the special value None
  17. While loop while condition: statement_block else: statement_block So far, a

    while loop only ends, if the condition in the loop head is fulfilled. With the help of a break statement a while loop can be left prematurely, i.e. as soon as the control flow of the program comes to a break inside of a while loop (or other loops) the loop will be immediately left.
  18. While loop (Cont.) import random n = 20 to_be_guessed =

    int (n * random.random()) + 1 guess = 0 while guess != to_be_guessed: guess = int(raw_input(“Enter your guess: ”)) if guess > 0: if guess > to_be_guessed: print “Number too large.” else: print “Number too small” else: print “loser!!” break else: print “You are correct! Congratulations!”
  19. For loop for variable in sequence: statement_block else: statement_block The

    for statement differs from what programmers of C or C++ are used to. The for statement of Python looks a bit like the for loop of the Bash shell. We often need to go through all the elements of a list or perform an operation over a series of numbers. The Python for statement is the right tool to go easily through various types of lists and ranges.
  20. range() The for statement differs from what programmers of C

    or C++ are used to. The for statement of Python looks a bit like the for loop of the Bash shell. We often need to go through all the elements of a list or perform an operation over a series of numbers. The Python for statement is the right tool to go easily through various types of lists and ranges. >>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> range(1,11) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> range(1,11,2) [2, 4, 6, 8, 10] range(begin[, end, step])
  21. Using range() with for loop The range() function is especially

    useful in combination with the for loop, as we can see in the following example. The range() function supplies the numbers from 1 to 100 for the for loop to calculate the sum of these numbers: sum = 0 for i in range(1, 101): sum = sum + i print sum
  22. Iterating over Lists with range() If you have to access

    the indices of a list, it doesn't look to be a good idea to use the for loop to iterate over the lists. We can access all the elements, but the index of an element is not available. fib = [0,1,1,2,3,5,8,13] for i in range(len(fib)): print i, fib[i]
  23. List iteration with side effects colours = [“red”] for colour

    in colours: if colour == “red”: colours += [“black”] if colour == “black”: colours += [“white”] print colours
  24. List iteration with side effects (Cont.) To avoid these side

    effects, it's best to work on a copy by using the slicing operator colours = [“red”] for colour in colours[:]: if colour == “red”: colours += [“black”] if colour == “black”: colours += [“white”] print colours
  25. Strings A string can be seen as a sequence of

    characters. “Hello” H e l l o [0] [1] [2] [3] [4]
  26. Lists The list is a most versatile data type in

    Python. It can be written as a list of comma- separated items (values) between square brackets. Lists are related to arrays of programming languages like C, C++ or Java, but Python lists are by far more flexible than "classical" arrays. >>> languages = ["Python", "C", "C++", "Java", “Perl"] >>> languages[0] “Python” >>> group = [“Bob”, 23, “George”, 21, “Myriam”, 10] >>> print group[1] 23 >>> print group[2] “George”
  27. Sublists Lists can have sublists as elements. These Sublists may

    contain sublists as well, i.e. lists can be recursively constructed by sublist structures. >>> person = [[“Rene","Padillo"],["Davao City",],"123-3451"] >>> print person[0] [“Rene”, “Padillo”] >>> first_name = person[0][0] >>> print first_name “Rene”
  28. Tuples A tuple is an immutable list, i.e. a tuple

    cannot be changed in any way once it has been created. >>> t = (“this”, “is”, “a”, “tuple”) >>> print t (“this”, “is”, “a”, “tuple”) >>> t[0] = “Another word”
  29. Slicing >>> t = “Awesome!” >>> first_three = t[:3] “Awe”

    >>> starting_at_four = t[4:] “some!” >>> languages = ["Python", "C", "C++", "Java", “Perl"] >>> without_perl = languages[0:-1] ["Python", "C", "C++", "Java"] sequence[begin[, end, step]]
  30. Concatenation of sequences Combining two sequences like strings or lists

    is as easy as adding two numbers. Even the operator sign is the same. >>> first_name = “Rene” >>> last_name = “Padillo” >>> name = first_name + “ “ + last_name >>> print name >>> colors1 = [“red”, “green”, “blue”] >>> colors2 = [“black”, “yellow”] >>> colors = colors1 + colors2 >>> print colors
  31. Check element in list It's easy to check, if an

    item is contained in a sequence. We can use the "in" or the "not in" operator for this purpose. >>> colours = [“red”, “green”, “blue”, “black”, “yellow”] >>> “red” in colours True >>> “pink“ in colours False >>> str = “Python is easy!” >>> “Python” in str True >>> “i” in str True
  32. Repetitions >>> 3 * “test” “testtesttest” >>> “test-” * 3


    “test-test-test-” >>> 3 * [“a”, “b”, “c”] [“a”, “b”, “c”, “a”, “b”, “c”, “a”, “b”, “c”] So far we had a "+" operator for sequences. There is a "*" operator available as well. Of course there is no "multiplication" between two sequences possible. "*" is defined for a sequence and an integer
  33. Bonus: List comprehension List comprehension is an elegant way to

    define and create list in Python. These lists have often the qualities of sets, but are not in all cases sets. >>> Celsius = [39.2, 36.5, 37.3, 37.8] >>> Fahrenheit = [ ((float(9)/5)*x + 32) for x in Celsius ] >>> Fahrenheit
  34. Bonus: List comprehension (Cont.) Calculating prime numbers between 1 and

    100 >>> noprimes = [j for i in range(2, 8) for j in range(i*2,100, i)] >>> primes = [x for x in range(2,100) if x not in noprimes] >>> print primes
  35. Bonus: Lambda Function Lambda operator or lambda function is a

    way to create small anonymous functions, i.e. functions without a name. These functions are throw-away functions, i.e. they are just needed where they have been created. >>> f = lambda x,y: x + y >>> f(1,1) >>> fib = [0,1,1,2,3,5,8,13,21,34,55] >>> result = filter(lambda x: x % 2, fib) >>> print result
  36. Functions Functions are a construct to structure programs. They are

    known in most programming languages, sometimes also called subroutines or procedures. def function_name(param): # function body here pass Example: >>> def add(x, y): … return x +y … >>> add(2, 3) 5
  37. Functions with keyword parameters >>> def sumsub(x, y, a=0, b=0):

    … return a - b + x + y … >>> sumsub(3,5) >>> sumsub(12,4,27,23) >>> sumsub(3,43,b=10,a=10) >>> sumsub(58,19,a=12) >>> sumsub(5,10,b=2)
  38. Functions with arbitrary number of parameters >>> def arbitrary(x, y,

    *more): … print x, y … print more … >>> arbitrary(3,5) >>> arbitrary(12,4,”Test”,23.2, 10)]
  39. In this session we: • Learn how to setup Python

    • Learn how to use Python interactive interpreter (CLI) • Learn how to execute Python scripts • Learn the different data types and variables • Learn arithmetic and comparison operators • Learn how to display and get input
  40. In this session we: • Learn conditional statements • Learn

    loop statements • Learn sequential data types • Learn how to create functions
  41. FIN