Slide 1

Slide 1 text

Python !" @henocdz

Slide 2

Slide 2 text

Why Python? Just trust me, you will love it! @henocdz

Slide 3

Slide 3 text

Windows user? No problem. Use Ac#ve Python for Installa-on @henocdz

Slide 4

Slide 4 text

Data Types # Numbers a_integer = 2623 # Up to sys.int_info * a_float = 69.89 # Up to sys.float_info * #Booleans of_horse = True nope = False # Binary as_bytes = b'A random text stored as bytes' # Nothing my_money = None @henocdz

Slide 5

Slide 5 text

Data Types # Sequences a_string = 'Python is Awesome!' # Are immutable! a_string_quotes = "Python is love!" a_string_triple = '''Python is life!''' a_list = [1, [2], 1, a_string, 3.67] # Any size, any data type a_tuple = (5, ['z'], 89, ) # Same rules of lists apply, but this are immutable a_tuple_comma = 5, ['z'], 89, # Comma is the element separator a_set = set([1, 1, 4, 1]) # =[1,4] Collection with no duplicate elements @henocdz

Slide 6

Slide 6 text

Data Types # Dictionaries a_dict = { # Key can be any immutable object # (i.e, numbers, strings, tuples) 'some_key': 'some value', 4: 'another value', a_tuple: a_list # Can be a key only if the tuple contains immutable objects } @henocdz

Slide 7

Slide 7 text

Operators @henocdz

Slide 8

Slide 8 text

Arithme(c Operators # Addition (+) >>> result = 4 + 10 14 # Subtraction (-) >>> 2014 - 2015 1 # Multiplication (*) >>> 2 * 10 20 @henocdz

Slide 9

Slide 9 text

Arithme(c Operators (cont) # Division (/) >>> 10 / 2 5.0 # Type Float # Floor Division (//) >>> 10 // 2 5 # Type Integer # Modulus (%) >>> 14 % 2 # Exponent (**) >>> 2 ** 2 4 @henocdz

Slide 10

Slide 10 text

Comparison Operators # Evaluates if two elements are equal >>> 10 == 10 True # Evaluates if two elements are not equal >>> 10 != 5 True # Evaulates if the value of left operand is greater than the value of right operand >>> 14 < 2 False # Viceversa >>> 14 > 2 True # >= and <= are also supported @henocdz

Slide 11

Slide 11 text

Assignment Operators >>> something = 'classic' # You can combine any arithmetic operator with (=) operator # like this :) >>> something *= 3 'classicclassicclassic' @henocdz

Slide 12

Slide 12 text

Membership Operators >>> 5 in [3, 4, 10] False >>> 5 not in [3, 4, 10] True @henocdz

Slide 13

Slide 13 text

Control Flow Tools @henocdz

Slide 14

Slide 14 text

Condi&onal Statements IF-ELSE some_bool = True # if-else structure >>> if some_bool: ... print('Some bool it\'s True!!') >>> else: ... print('Some bool it\'s not True :(') @henocdz

Slide 15

Slide 15 text

IF-ELSE-IF >>> alumni = True >>> senseis = False >>> if alumni and senseis: ... print('We are ready!') >>> elif alumni: ... print('Waiting for senseis...') >>> elif senseis: ... print('Waiting for alumni...') >>> else: ... print('Fuck!') @henocdz

Slide 16

Slide 16 text

INLINE IF-ELSE >>> ready = True if alumni and senseis else False @henocdz

Slide 17

Slide 17 text

FOR # Iterates over a sequence # (list, tuple, string, bytes, bytesarray, etc.) >>> senseis = ('Henoc', 'Gus', 'Sergio', ) >>> for sensei in senseis: ... print(sensei) Henoc Gus Sergio @henocdz

Slide 18

Slide 18 text

COMMON FOR # range(5) > [0, 1, 2, 3, 4] # range(4, 5) > [4] >>> for i in range(0, 5): ... print(i) 0 1 2 3 4 @henocdz

Slide 19

Slide 19 text

WHILE # Tests the expression and, if it is true, executes the block; # if the expression is false the loop terminates >>> im_awesome = True >>> while im_awesome: ... stay_awesome() @henocdz

Slide 20

Slide 20 text

BREAK & CONTINUE You can control a loop with 1. break: terminates the loop 2. con)nue: ignore the rest of the block and returns to evaluate the expression >>> while True: ... if im_tired: ... break @henocdz

Slide 21

Slide 21 text

Func%ons >>> def tellme_the_truth(): ... print('May the force be with You!') >>> def function_with_params(a_param): ... print(a_param) >>> def function_default_values(a_param, has_default=True): ... """Params with no default value must be defined first""" ... print(a_param, has_default) >>> def give_me_the_year(): ... return 2015 @henocdz

Slide 22

Slide 22 text

Lambda Func+ons >>> do_something = lambda a_number: a_number * a_number >>> do_something(14) 196 @henocdz

Slide 23

Slide 23 text

Execu&ng Func&ons >>> tellme_the_truth() May the force be with You! >>> function_with_params('A string!') A string! >>> function_default_values('not a number') not a number, True >>> function_default_values('a number', False) a number, False >>> function_default_values('default', has_default=False) default, False >>> give_me_the_year() 2015 @henocdz

Slide 24

Slide 24 text

I/O Communica)on with real users @henocdz

Slide 25

Slide 25 text

Input / Output >>> user_input = input('Tell me your name: ') Tell me your name: [[Henoc]] >>> print(user_input, type(user_input)) Henoc @henocdz

Slide 26

Slide 26 text

! @henocdz

Slide 27

Slide 27 text

And now what? ! @henocdz

Slide 28

Slide 28 text

Running Python Script File Create a file and edit it with your favorite code editor: $ touch file_name.py $ vim file_name.py # Run the file $ python file_name.py @henocdz

Slide 29

Slide 29 text

Style guides For example: Don't use Cammel Case with func3on or variables, instead you must use snake case i.e, def thiIsWrong(): def this_is_ok(): 1. PEP8 a. h)ps:/ /www.python.org/dev/peps/pep-0008/ 2. Google Style Guide b. h)p:/ /google.github.io/styleguide/pyguide.html @henocdz

Slide 30

Slide 30 text

Exercises @henocdz

Slide 31

Slide 31 text

[1] List Overlap Take two lists, say for example these two: a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] Then write a program that returns a list that contains only the elements that are common between the lists (without duplicates). Make sure your program works on two lists of different sizes. @henocdz

Slide 32

Slide 32 text

[2] Cows and bulls Create a program that will play the “cows and bulls” game with the user. The game works like this: Randomly generate a 4-digit number. Ask the user to guess a 4-digit number. For every digit that the user guessed correctly in the correct place, they have a “cow”. For every digit the user guessed correctly in the wrong place is a “bull.” Every Ame the user makes a guess, tell them how many “cows” and “bulls” they have. Once the user guesses the correct number, the game is over. Keep track of the number of guesses the user makes throughout teh game and tell the user at the end. Say the number generated by the computer is 1038. An example interacAon could look like this: Welcome to the Cows and Bulls Game! Enter a number: 1234 2 cows, 0 bulls 1256 1 cow, 1 bull Un#l the user guesses the number. @henocdz

Slide 33

Slide 33 text

Hints You can use random module to generate pseudo-random numbers For example: >>> import random >>> random.randint(1000, 9999) 8756 @henocdz

Slide 34

Slide 34 text

Extra Exercises • [1] Randomly generate two lists to test this @henocdz

Slide 35

Slide 35 text

Packages and Modules ! @henocdz

Slide 36

Slide 36 text

Modules A file that contains python defini1ons like func1ons, classes or variables So, almost any file it's a module, for example: # File name: my_math.py def zum(a, b): return a + b def pow(a, b): return a ** b @henocdz

Slide 37

Slide 37 text

We can import a module in other modules like this # File name: other_file.py >>> import my_math >>> print(my_math.zum(3, 4)) 7 # Just one definition with >>> from my_math import zum >>> print(zum(1, 2)) 2 # Single definition with an alias >>> from my_math import zum as my_sum >>> print(my_zum(12, 12)) 24 @henocdz

Slide 38

Slide 38 text

Script file vs Module If you pass your module name to the interpreter, this is executed as script file, so everything in the module file will be executed as-is. If you don't want that, we can use global variable __name__ for code that should be executed only in script mode; like this: if __name__ = '__main__': print('Running as script file...') Global variable __name__ contains the name of the module, but if the module is executed as an script, this variable contains the string __main__ @henocdz

Slide 39

Slide 39 text

Packages A folder that contains other packages or module files utils/ __init__.py my_math.py ... my_script.py Use __init__.py file to convert a folder into a package @henocdz

Slide 40

Slide 40 text

And then we can import some module from the u"ls package like this: # import definition >>> from utils.my_math import zum >>> zum(a, b) # import module >>> from utils import my_math >>> my_math.zum() @henocdz

Slide 41

Slide 41 text

! Let's rock @henocdz

Slide 42

Slide 42 text

Object Oriented Programming @henocdz

Slide 43

Slide 43 text

Classes Basic class Student(object): """The Doc string, used for documenting our class""" # Class attributes skills = [] def __init__(self, belt, skills): # self points to the current instance self.belt = belt self.skills = skills def get_skills(self): # self is required return self.skills @henocdz

Slide 44

Slide 44 text

Crea%ng instances You can create objects or instances like this # New instance >>> dany = Student( ... belt='Red', ... skills=['Python', 'Javascript'] ... ) @henocdz

Slide 45

Slide 45 text

Calling methods >>> dany.get_skills() ['Python', 'Javascript'] @henocdz

Slide 46

Slide 46 text

Accessing a*ributes # Anyone have access to all attributes of a class or object >>> dany.skills ['Python', 'Javascript'] >>> dany.belt 'Red' # We can modify class attributes >>> Student.skills [] @henocdz

Slide 47

Slide 47 text

Inheritance class A(object): def some_method(self): print('something') class B(A): def some_method(self): print('I\'m the class `B :)') super(B, self).some_method() # Basic Inheritance is from left to right class C(A, B): pass Super-pro algorithm for inheritance: h4ps://www.python.org/download/releases/2.3/mro/ @henocdz

Slide 48

Slide 48 text

Magic Methods Like __init__ You can use this magic methods to override operators behavior, i.e., class Student(object): ... def __add__(self, other): if isinstance(other, self.__class__): skills = self.get_skills() + other.get_skills() belt = self.belt + other.belt return Student(belt, skills) @henocdz

Slide 49

Slide 49 text

Other magic methods: @henocdz

Slide 50

Slide 50 text

String forma,ng The correct way for concatena.on and prin.ng strings combined with other object types # Simple way "I like to {}".format('code') # Simple way 2 "I {1} to {0}".format('code', 'like') # 'Complex' way "I {verb} to {what}".format(what='code', verb='like') @henocdz

Slide 51

Slide 51 text

Exercise h"ps:/ /github.com/comunidad-devf/PythonExercises/tree/master/ Classes01 @henocdz

Slide 52

Slide 52 text

Virtual Environment Isolated Python environments Imagine that you have two applica3ons and both depends on MyPackage, but the first one requires version 1 of MyPackage and the later one requires version 2 of MyPackage. The solu)on for that is a virtual environment. In Python 3 you can do so with this command: # pyvenv command it's installed when you install Python3 $ pyvenv ENV_DIR ENV_DIR is the folder where our virtualenv will be installed. @henocdz

Slide 53

Slide 53 text

Older versions For older versions of python i.e <2.7.x you must install virtualenv package in order to work with Virtual Environments and the create it, like this: # Install virtualenv package $ pip install virtualenv # Create a virtualenv $ virtualenv ENV_DIR @henocdz

Slide 54

Slide 54 text

! @henocdz