I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/If, elif, and else Statements -checkpoint.ipynb".
The first task is:
Note how the nested if statements are each checked until a True boolean causes the nested code below it to run. You should also note that you can put in as many elif statements as you want before you close off with an else.
Let's create two more simple examples for the if,elif, and else statements:
Can you write Python code for it?

person = 'Sammy'

if person == 'Sammy':
    print 'Welcome Sammy!'
else:
    print "Welcome, what's your name?"

person = 'George'

if person == 'Sammy':
    print 'Welcome Sammy!'
elif person =='George':
    print "Welcome George!"
else:
    print "Welcome, what's your name?"


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Iterators and Generators Homework - Solution-checkpoint.ipynb".
The first task is:
Problem 3
Use the iter() function to convert the string below
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Iterators and Generators Homework - Solution-checkpoint.ipynb".
The first task is:
Problem 4
Explain a use case for a generator using a yield statement where you would not want to use a normal function with a return statement.
If the output has the potential of taking up a large amount of memory and you only intend to iterate through it, you would want to use a generator. (Multiple answers are acceptable here!)
Extra Credit!
Can you explain what bonus is in the code below? (Note: We never covered this in lecture!)
Can you write Python code for it?

my_list = [1,2,3,4,5]

gencomp = (item for item in my_list if item > 3)

for item in gencomp:
    print item


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Iterators and Generators Homework-checkpoint.ipynb".
The first task is:
Problem 2
Create a generator that yields "n" random numbers between a low and high number (that are inputs). Note: Use the random library. For example:
Can you write Python code for it?

import random

random.randint(1,10)

def rand_num(low,high,n):
    pass

for num in rand_num(1,10,12):
    print num


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Iterators and Generators Homework-checkpoint.ipynb".
The first task is:
Problem 3
Use the iter() function to convert the string below
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Iterators and Generators-checkpoint.ipynb".
The first task is:
After yielding all the values next() caused a StopIteration error. What this error informs us of is that all the values have been yielded.
You might be wondering that why don’t we get this error while using a for loop? The for loop automatically catches this error and stops calling next.
Lets go ahead and check out how to use iter(). You remember that strings are iterables:
Can you write Python code for it?

s = 'hello'

#Iterate over string
for let in s:
    print let


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Iterators and Generators-checkpoint.ipynb".
The first task is:
But that doesn't mean the string itself is an iterator! We can check this with the next() function:
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Iterators and Generators-checkpoint.ipynb".
The first task is:
Great! Now since we have a generator function we don't have to keep track of every single cube we created.
Generators are best for calculating large sets of results (particularly in calculations that involve loops themselves) in cases where we don’t want to allocate the memory for all of the results at the same time.
As we've noted in previous lectures (such as range()) many Standard Library functions that return lists in Python 2 have been modified to return generators in Python 3 because generators.
Lets create another example generator which calculates fibonacci numbers:
Can you write Python code for it?

def genfibon(n):
    '''
    Generate a fibonnaci sequence up to n
    '''
    a = 1
    b = 1
    for i in range(n):
        yield a
        a,b = b,a+b

for num in genfibon(10):
    print num


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Iterators and Generators-checkpoint.ipynb".
The first task is:
Interesting, this means that a string object supports iteration, but we can not directly iterate over it as we could with a generator function. The iter() function allows us to do just that!
Can you write Python code for it?

s_iter = iter(s)

next(s_iter)

next(s_iter)


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Iterators and Generators-checkpoint.ipynb".
The first task is:
Notice that if we call some huge value of n (like 100000) the second function will have to keep track of every single result, when in our case we actually only care about the previous result to generate the next one!
next() and iter() built-in functions
A key to fully understanding generators is the next function() and the iter() function.
The next function allows us to access the next element in a sequence. Lets check it out:
Can you write Python code for it?

def simple_gen():
    for x in range(3):
        yield x

# Assign simple_gen
g = simple_gen()

print next(g)

print next(g)

print next(g)

print next(g)


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Iterators and Generators-checkpoint.ipynb".
The first task is:
What is this was a normal function, what would it look like?
Can you write Python code for it?

def fibon(n):
    a = 1
    b = 1
    output = []

    for i in range(n):
        output.append(a)
        a,b = b,a+b

    return output

fibon(10)


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/List Comprehensions-checkpoint.ipynb".
The first task is:
Example 3
Lets see how to add in if statements:
Can you write Python code for it?

# Check for even numbers in a range
lst = [x for x in range(11) if x % 2 == 0]

lst


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/List Comprehensions-checkpoint.ipynb".
The first task is:
Example 4
Can also do more complicated arithmetic:
Can you write Python code for it?

# Convert Celsius to Fahrenheit
celsius = [0,10,20.1,34.5]

fahrenheit = [ ((float(9)/5)*temp + 32) for temp in celsius ]

fahrenheit


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/List Comprehensions-checkpoint.ipynb".
The first task is:
Example 5
We can also perform nested list comprehensions, for example:
Can you write Python code for it?

lst = [ x**2 for x in [x**2 for x in range(11)]]
lst


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/List Comprehensions-checkpoint.ipynb".
The first task is:
This is the basic idea of a list comprehension. If you're familiar with mathematical notation this format should feel familiar for example: x^2 : x in { 0,1,2...10}
Lets see a few more example of list comprehensions in Python:
Example 2
Can you write Python code for it?

# Square numbers in range and turn into list
lst = [x**2 for x in range(0,11)]

lst


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Lists-checkpoint.ipynb".
The first task is:
Basic List Methods
If you are familiar with another programming language, you might start to draw parallels between arrays in another language and lists in Python. Lists in Python however, tend to be more flexible than arrays in other languages for a two good reasons: they have no fixed size (meaning we don't have to specify how big a list will be), and they have no fixed type constraint (like we've seen above).
Let's go ahead and explore some more special methods for lists:
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Lists-checkpoint.ipynb".
The first task is:
Indexing and Slicing
Indexing and slicing works just like in strings. Let's make a new list to remind ourselves of how this works:
Can you write Python code for it?

my_list = ['one','two','three',4,5]

# Grab element at index 0
my_list[0]

# Grab index 1 and everything past it
my_list[1:]

# Grab everything UP TO index 3
my_list[:3]


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Lists-checkpoint.ipynb".
The first task is:
It should also be noted that lists indexing will return an error if there is no element at that index. For example:
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Lists-checkpoint.ipynb".
The first task is:
Nesting Lists
A great feature of of Python data structures is that they support nesting. This means we can data structures within data structures. For example: A list inside a list.
Let's see how this works!
Can you write Python code for it?

# Let's make three lists
lst_1=[1,2,3]
lst_2=[4,5,6]
lst_3=[7,8,9]

# Make a list of lists to form a matrix
matrix = [lst_1,lst_2,lst_3]

# Show
matrix


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Lists-checkpoint.ipynb".
The first task is:
Note: This doesn't actually change the original list!
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Lists-checkpoint.ipynb".
The first task is:
Now we can again use indexing to grab elements, but now there are two levels for the index. The items in the matrix object, and then the items inside that list!
Can you write Python code for it?

# Grab first item in matrix object
matrix[0]

# Grab first item of the first item in the matrix object
matrix[0][0]


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Lists-checkpoint.ipynb".
The first task is:
Use pop to "pop off" an item from the list. By default pop takes off the last index, but you can also specify which index to pop off. Let's see an example:
Can you write Python code for it?

# Pop off the 0 indexed item
l.pop(0)

# Show
l

# Assign the popped element, remember default popped index is -1
popped_item = l.pop()

popped_item

# Show remaining list
l


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Lists-checkpoint.ipynb".
The first task is:
Use the append method to permanently add an item to the end of a list:
Can you write Python code for it?

# Append
l.append('append me!')

# Show
l


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Lists-checkpoint.ipynb".
The first task is:
We can use the sort method and the reverse methods to also effect your lists:
Can you write Python code for it?

new_list = ['a','e','x','b','c']

#Show
new_list

# Use reverse to reverse order (this is permanent!)
new_list.reverse()

new_list

# Use sort to sort the list (in this case alphabetical order, but for numbers it will go ascending)
new_list.sort()

new_list


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Lists-checkpoint.ipynb".
The first task is:
We just created a list of integers, but lists can actually hold different object types. For example:
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Lists-checkpoint.ipynb".
The first task is:
You would have to reassign the list to make the change permanent.
Can you write Python code for it?

# Reassign
my_list = my_list + ['add new item permanently']

my_list


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Map -checkpoint.ipynb".
The first task is:
Great! We got the same result! Using map is much more commonly used with lambda expressions since the entire purpose of map() is to save effort on having to create manual for loops.
map() can be applied to more than one iterable. The iterables have to have the same length.
For instance, if we are working with two lists-map() will apply its lambda function to the elements of the argument lists, i.e. it first applies to the elements with the 0th index, then to the elements with the 1st index until the n-th index is reached.
For example lets map a lambda expression to two lists:
Can you write Python code for it?

a = [1,2,3,4]
b = [5,6,7,8]
c = [9,10,11,12]

map(lambda x,y:x+y,a,b)

# Now all three lists
map(lambda x,y,z:x+y+z, a,b,c)


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Map -checkpoint.ipynb".
The first task is:
In the example above we haven't used a lambda expression. By using lambda, we wouldn't have had to define and name the functions fahrenheit() and celsius().
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Map -checkpoint.ipynb".
The first task is:
Now lets see map() in action:
Can you write Python code for it?

F_temps = map(fahrenheit, temp)

#Show
F_temps

# Convert back
map(celsius, F_temps)


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Milestone Project 1 - Solution-checkpoint.ipynb".
The first task is:
Finally put it all together in a function to play the game.
Can you write Python code for it?

def play_game():
    reset_board()
    global announce

    # Set marks
    X='X'
    O='O'
    while True:
        # Show board
        clear_output()
        display_board()

        # Player X turn
        game_state,announce = player_choice(X)
        print announce
        if game_state == False:
            break

        # Player O turn
        game_state,announce = player_choice(O)
        print announce
        if game_state == False:
            break

    # Ask player for a rematch
    rematch = raw_input('Would you like to play again? y/n')
    if rematch == 'y':
        play_game()
    else:
        print "Thanks for playing!"


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Milestone Project 1 - Solution-checkpoint.ipynb".
The first task is:
Next make a function that will reset the board, in this case we'll store values as a list.
Can you write Python code for it?

# Note: Game will ignore the 0 index
def reset_board():
    global board,game_state
    board = [' '] * 10
    game_state = True


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Milestone Project 1- Complete Walkthrough Solution-checkpoint.ipynb".
The first task is:
Step 10: Here comes the hard part! Use while loops and the functions you've made to run the game!
Can you write Python code for it?

print('Welcome to Tic Tac Toe!')

while True:
    # Reset the board
    theBoard = [' '] * 10
    player1_marker, player2_marker = player_input()
    turn = choose_first()
    print(turn + ' will go first.')
    game_on = True

    while game_on:
        if turn == 'Player 1':
            # Player1's turn.

            display_board(theBoard)
            position = player_choice(theBoard)
            place_marker(theBoard, player1_marker, position)

            if win_check(theBoard, player1_marker):
                display_board(theBoard)
                print('Congratualtions! You have won the game!')
                game_on = False
            else:
                if full_board_check(theBoard):
                    display_board(theBoard)
                    print('The game is a draw!')
                    break
                else:
                    turn = 'Player 2'

        else:
            # Player2's turn.

            display_board(theBoard)
            position = player_choice(theBoard)
            place_marker(theBoard, player2_marker, position)

            if win_check(theBoard, player2_marker):
                display_board(theBoard)
                print('Player 2 has won!')
                game_on = False
            else:
                if full_board_check(theBoard):
                    display_board(theBoard)
                    print('The game is a tie!')
                    break
                else:
                    turn = 'Player 1'

    if not replay():
        break


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Milestone Project 1- Complete Walkthrough Solution-checkpoint.ipynb".
The first task is:
Step 1: Write a function that can print out a board. Set up your board as a list, where each index 1-9 corresponds with a number on a number pad, so you get a 3 by 3 board representation.
Can you write Python code for it?

from IPython.display import clear_output
def display_board(board):

    clear_output()
    print('   |   |')
    print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])
    print('   |   |')
    print('-----------')
    print('   |   |')
    print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])
    print('   |   |')
    print('-----------')
    print('   |   |')
    print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3])
    print('   |   |')


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Milestone Project 1- Complete Walkthrough Solution-checkpoint.ipynb".
The first task is:
Step 2: Write a function that can take in a player input and assign their marker as 'X' or 'O'. Think about using while loops to continually ask until you get a correct answer.
Can you write Python code for it?

def player_input():

    marker = ''
    while not (marker == 'X' or marker == 'O'):
        marker = raw_input('Player 1: Do you want to be X or O?').upper()

    if marker == 'X':
        return ('X', 'O')
    else:
        return ('O', 'X')


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Milestone Project 1- Complete Walkthrough Solution-checkpoint.ipynb".
The first task is:
Step 4: Write a function that takes in a board and checks to see if someone has won.
Can you write Python code for it?

def win_check(board,mark):

    return ((board[7] == mark and board[8] == mark and board[9] == mark) or # across the top
    (board[4] == mark and board[5] == mark and board[6] == mark) or # across the middle
    (board[1] == mark and board[2] == mark and board[3] == mark) or # across the bottom
    (board[7] == mark and board[4] == mark and board[1] == mark) or # down themarkft side
    (board[8] == mark and board[5] == mark and board[2] == mark) or # down the middle
    (board[9] == mark and board[6] == mark and board[3] == mark) or # down the right side
    (board[7] == mark and board[5] == mark and board[3] == mark) or # diagonal
    (board[9] == mark and board[5] == mark and board[1] == mark)) # diagonal


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Milestone Project 1- Complete Walkthrough Solution-checkpoint.ipynb".
The first task is:
Step 5: Write a function that uses the random module to randomly decide which player goes first. You may want to lookup random.randint() Return a string of which player went first.
Can you write Python code for it?

import random
def choose_first():
    if random.randint(0, 1) == 0:
        return 'Player 2'
    else:
        return 'Player 1'


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Milestone Project 1- Complete Walkthrough Solution-checkpoint.ipynb".
The first task is:
Step 6: Write a function that returns a boolean indicating whether a space on the board is freely available.
Can you write Python code for it?

def space_check(board, position):

    return board[position] == ' '


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Milestone Project 1- Complete Walkthrough Solution-checkpoint.ipynb".
The first task is:
Step 7: Write a function that checks if the board is full and returns a boolean value. True if full, False otherwise.
Can you write Python code for it?

def full_board_check(board):
    for i in range(1,10):
        if space_check(board, i):
            return False
    return True


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Milestone Project 1- Complete Walkthrough Solution-checkpoint.ipynb".
The first task is:
Step 8: Write a function that asks for a player's next position (as a number 1-9) and then uses the function from step 6 to check if its a free position. If it is, then return the position for later use.
Can you write Python code for it?

def player_choice(board):
    # Using strings because of raw_input
    position = ' '
    while position not in '1 2 3 4 5 6 7 8 9'.split() or not space_check(board, int(position)):

        position = raw_input('Choose your next position: (1-9) ')
    return int(position)


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Nested Statements and Scope-checkpoint.ipynb".
The first task is:
Enclosing function locals
This occurs when we have a function inside a function (nested functions)
Can you write Python code for it?

name = 'This is a global name'

def greet():
    # Enclosing function
    name = 'Sammy'

    def hello():
        print 'Hello '+name

    hello()

greet()


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Nested Statements and Scope-checkpoint.ipynb".
The first task is:
Interesting! But how does Python know which x you're referring to in your code? This is where the idea of scope comes in. Python has a set of rules it follows to decide what variables (such as x in this case) you are refrencing in your code. Lets break down the rules:
This idea of scope in your code is very important to understand in order to properly assign and call variable names.
In simple terms, the idea of scope can be described by 3 general rules:

Name assignments will create or change local names by default.
Name references search (at most) four scopes, these are:
local
enclosing functions
global
built-in

Names declared in global and nonlocal statements map assigned names to enclosing module and function scopes.

The statement in #2 above can be defined by the LEGB rule.
LEGB Rule.
L: Local — Names assigned in any way within a function (def or lambda)), and not declared global in that function.
E: Enclosing function locals — Name in the local scope of any and all enclosing functions (def or lambda), from inner to outer.
G: Global (module) — Names assigned at the top-level of a module file, or declared global in a def within the file.
B: Built-in (Python) — Names preassigned in the built-in names module : open,range,SyntaxError,...
Quick examples of LEGB
Local
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Nested Statements and Scope-checkpoint.ipynb".
The first task is:
Local Variables
When you declare variables inside a function definition, they are not related in any way to other variables with the same names used outside the function - i.e. variable names are local to the function. This is called the scope of the variable. All variables have the scope of the block they are declared in starting from the point of definition of the name.
Example:
Can you write Python code for it?

x = 50

def func(x):
    print 'x is', x
    x = 2
    print 'Changed local x to', x

func(x)
print 'x is still', x


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Nested Statements and Scope-checkpoint.ipynb".
The first task is:
The first time that we print the value of the name x with the first line in the function’s body, Python uses the value of the parameter declared in the main block, above the function definition.
Next, we assign the value 2 to x. The name x is local to our function. So, when we change the value of x in the function, the x defined in the main block remains unaffected.
With the last print statement, we display the value of x as defined in the main block, thereby confirming that it is actually unaffected by the local assignment within the previously called function.
The global statement
If you want to assign a value to a name defined at the top level of the program (i.e. not inside any kind of scope such as functions or classes), then you have to tell Python that the name is not local, but it is global. We do this using the global statement. It is impossible to assign a value to a variable defined outside a function without the global statement.
You can use the values of such variables defined outside the function (assuming there is no variable with the same name within the function). However, this is not encouraged and should be avoided since it becomes unclear to the reader of the program as to where that variable’s definition is. Using the global statement makes it amply clear that the variable is defined in an outermost block.
Example:
Can you write Python code for it?

x = 50

def func():
    global x
    print 'This function is now using the global x!'
    print 'Because of global x is: ', x
    x = 2
    print 'Ran func(), changed global x to', x

print 'Before calling func(), x is: ', x
func()
print 'Value of x (outside of func()) is: ', x


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Nested Statements and Scope-checkpoint.ipynb".
The first task is:
What do you imagine the output of printer() is? 25 or 50? What is the output of print x? 25 or 50?
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Numbers-checkpoint.ipynb".
The first task is:
Python 3 Alert!
Whoa! What just happened? Last time I checked, 3 divided by 2 is equal 1.5 not 1!
The reason we get this result is because we are using Python 2. In Python 2, the / symbol performs what is known as "classic" division, this means that the decimal points are truncated (cut off). In Python 3 however, a single / performs "true" division. So you would get 1.5 if you had inputed 3/2 in Python 3.
So what do we do if we are using Python 2 to avoid this?
There are two options:
Specify one of the numbers to be a float:
Can you write Python code for it?

# Specifying one of the numbers as a float
3.0/2

# Works for either number
3/2.0


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Numbers-checkpoint.ipynb".
The first task is:
Now if I call a in my Python script, Python will treat it as the number 5.
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Numbers-checkpoint.ipynb".
The first task is:
Variable Assignments
Now that we've seen how to use numbers in Python as a calculator let's see how we can assign names and create variables.
We use a single equals sign to assign labels to variables. Let's see a few examples of how we can do this.
Can you write Python code for it?

# Let's create an object called "a" and assign it the number 5
a = 5


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Numbers-checkpoint.ipynb".
The first task is:
We will go over functions in much more detail later on in this course, so don't worry if you are confused by the syntax here. Consider this a sneak preview.
One more "sneak preview" we can use to deal with classic division in Python 2 is importing from a module called future.
This is a module in Python 2 that has Python 3 functions, this basically allows you to import Python 3 functions into Python 2. We will go over imports and modules later in the course, so don't worry about fully understanding the import statement right now!
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Numbers-checkpoint.ipynb".
The first task is:
Yes! Python allows you to write over assigned variable names. We can also use the variables themselves when doing the reassignment. Here is an example of what I mean:
Can you write Python code for it?

# Check
a

# Use A to redefine A
a = a + a

# Check
a


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Object Oriented Programming-checkpoint.ipynb".
The first task is:
By convention we give classes a name that starts with a capital letter. Note how x is now the reference to our new instance of a Sample class. In other words, we instanciate the Sample class.
Inside of the class we currently just have pass. But we can define class attributes and methods.
An attribute is a characteristic of an object.
A method is an operation we can perform with the object.
For example we can create a class called Dog. An attribute of a dog may be its breed or its name, while a method of a dog may be defined by a .bark() method which returns a sound.
Let's get a better understanding of attributes through an example.
Attributes
The syntax for creating an attribute is:
self.attribute = something

There is a special method called:
__init__()

This method is used to initialize the attributes of an object. For example:
Can you write Python code for it?

class Dog(object):
    def __init__(self,breed):
        self.breed = breed

sam = Dog(breed='Lab')
frank = Dog(breed='Huskie')


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Object Oriented Programming-checkpoint.ipynb".
The first task is:
Great! Notice how we used self. notation to reference attributes of the class within the method calls. Review how the code above works and try creating your own method
Inheritance
Inheritance is a way to form new classes using classes that have already been defined. The newly formed classes are called derived classes, the classes that we derive from are called base classes. Important benefits of inheritance are code reuse and reduction of complexity of a program. The derived classes (descendants) override or extend the functionality of base classes (ancestors).
Lets see an example by incorporating our rpevious work on the Dog class:
Can you write Python code for it?

class Animal(object):
    def __init__(self):
        print "Animal created"

    def whoAmI(self):
        print "Animal"

    def eat(self):
        print "Eating"

class Dog(Animal):
    def __init__(self):
        Animal.__init__(self)
        print "Dog created"

    def whoAmI(self):
        print "Dog"

    def bark(self):
        print "Woof!"

d = Dog()

d.whoAmI()

d.eat()

d.bark()


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Object Oriented Programming-checkpoint.ipynb".
The first task is:
In this example, we have two classes: Animal and Dog. The Animal is the base class, the Dog is the derived class.
The derived class inherits the functionality of the base class.

It is shown by the eat() method.

The derived class modifies existing behaviour of the base class.

shown by the whoAmI() method.

Finally, the derived class extends the functionality of the base class, by defining a new bark() method.
Special Methods
Finally lets go over special methods. Classes in Python can implement certain operations with special method names. These methods are not actually called directly but by Python specific language syntax. For example Lets create a Book class:
Can you write Python code for it?

class Book(object):
    def __init__(self, title, author, pages):
        print "A book is created"
        self.title = title
        self.author = author
        self.pages = pages

    def __str__(self):
        return "Title:%s , author:%s, pages:%s " %(self.title, self.author, self.pages)

    def __len__(self):
        return self.pages

    def __del__(self):
        print "A book is destroyed"

book = Book("Python Rocks!", "Jose Portilla", 159)

#Special Methods
print book
print len(book)
del book


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Object Oriented Programming-checkpoint.ipynb".
The first task is:
Lets break down what we have above.The special method
__init__()

is called automatically right after the object has been created:
def __init__(self, breed):

Each attribute in a class definition begins with a reference to the instance object. It is by convention named self. The breed is the argument. The value is passed during the class instantiation.
 self.breed = breed

Now we have created two instances of the Dog class. With two breed types, we can then access these attributes like this:
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Object Oriented Programming-checkpoint.ipynb".
The first task is:
Methods
Methods are functions defined inside the body of a class. They are used to perform operations with the attributes of our objects. Methods are essential in encapsulation concept of the OOP paradigm. This is essential in dividing responsibilities in programming, especially in large applications.
You can basically think of methods as functions acting on an Object that take the Object itself into account through its self argument.
Lets go through an example of creating a Circle class:
Can you write Python code for it?

class Circle(object):
    pi = 3.14

    # Circle get instantiaed with a radius (default is 1)
    def __init__(self, radius=1):
        self.radius = radius

    # Area method calculates the area. Note the use of self.
    def area(self):
        return self.radius * self.radius * Circle.pi

    # Method for resetting Radius
    def setRadius(self, radius):
        self.radius = radius

    # Method for getting radius (Same as just calling .radius)
    def getRadius(self):
        return self.radius

c = Circle()

c.setRadius(2)
print 'Radius is: ',c.getRadius()
print 'Area is: ',c.area()


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Object Oriented Programming-checkpoint.ipynb".
The first task is:
Note how we don't have any parenthesis after breed, this is because it is an attribute and doesn't take any arguments.
In Python there are also class object attributes. These Class Object Attributes are the same for any instance of the class. For example, we could create the attribute species for the Dog class. Dogs (regardless of their breed,name, or other attributes will always be mammals. We apply this logic in the following manner:
Can you write Python code for it?

class Dog(object):

    # Class Object Attribute
    species = 'mammal'

    def __init__(self,breed,name):
        self.breed = breed
        self.name = name

sam = Dog('Lab','Sam')

sam.name


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Object Oriented Programming-checkpoint.ipynb".
The first task is:
Note that the Class Object Attribute is defined outside of any methods in the class. Also by convention, we place them first before the init.
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Object Oriented Programming-checkpoint.ipynb".
The first task is:
Remember how we could call methods on a list?
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Object Oriented Programming-checkpoint.ipynb".
The first task is:
So we know all these things are objects, so how can we create our own Object types? That is where the class keyword comes in.
class
The user defined objects are created using the class keyword. The class is a blueprint that defines a nature of a future object. From classes we can construct instances. An instance is a specific object created from a particular class. For example, above we created the object 'l' which was an instance of a list object.
Let see how we can use class:
Can you write Python code for it?

# Create a new object type called Sample
class Sample(object):
    pass

# Instance of Sample
x = Sample()

print type(x)


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Object Oriented Programming-checkpoint.ipynb".
The first task is:
What we will basically be doing in this lecture is exploring how we could create an Object type like a list. We've already learned about how to create functions. So lets explore Objects in general:
Objects
In Python, everything is an object. Remember from previous lectures we can use type() to check the type of object something is:
Can you write Python code for it?

print type(1)
print type([])
print type(())
print type({})


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Print Formatting-checkpoint.ipynb".
The first task is:
Conversion Format methods.
It should be noted that two methods %s and %r actually convert any python object to a string using two seperate methods: str() and repr(). We will learn more about these functions later on in the course, but you should note you can actually pass almost any Python object with these two methods and it will work:
Can you write Python code for it?

print 'Here is a number: %s. Here is a string: %s' %(123.1,'hi')

print 'Here is a number: %r. Here is a string: %r' %(123.1,'hi')


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Print Formatting-checkpoint.ipynb".
The first task is:
Multiple Formatting
Pass a tuple to the modulo symbol to place multiple formats in your print statements:
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Python Debugger (pdb)-checkpoint.ipynb".
The first task is:
Hmmm, looks like we get an error! Lets implement a set_trace() using the pdb module. This will allow us to basically pause the code at the point of the trace and check if anything is wrong.
Can you write Python code for it?

import pdb

x = [1,3,4]
y = 2
z = 3

result = y + z
print result

# Set a trace using Python Debugger
pdb.set_trace()

result2 = y+x
print result2


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Regular Expressions-checkpoint.ipynb".
The first task is:
Character Ranges
As character sets grow larger, typing every character that should (or should not) match could become very tedious. A more compact format using character ranges lets you define a character set to include all of the contiguous characters between a start and stop point. The format used is [start-end].
Common use cases are to search for a specific range of letters in the alphabet, such [a-f] would return matches with any instance of letters between a and f.
Let's walk through some examples:
Can you write Python code for it?

test_phrase = 'This is an example sentence. Lets see if we can find some letters.'

test_patterns=[ '[a-z]+',      # sequences of lower case letters
                '[A-Z]+',      # sequences of upper case letters
                '[a-zA-Z]+',   # sequences of lower or upper case letters
                '[A-Z][a-z]+'] # one upper case letter followed by lower case letters

multi_re_find(test_patterns,test_phrase)


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Regular Expressions-checkpoint.ipynb".
The first task is:
Escape Codes
You can use special escape codes to find specific types of patterns in your data, such as digits, non-digits,whitespace, and more. For example:

<colgroup>
<col width="14%" />
<col width="86%" />
</colgroup>

Code
Meaning

<tt class="docutils literal">\d</tt>
a digit

<tt class="docutils literal">\D</tt>
a non-digit

<tt class="docutils literal">\s</tt>
whitespace (tab, space, newline, etc.)

<tt class="docutils literal">\S</tt>
non-whitespace

<tt class="docutils literal">\w</tt>
alphanumeric

<tt class="docutils literal">\W</tt>
non-alphanumeric

Escapes are indicated by prefixing the character with a backslash (). Unfortunately, a backslash must itself be escaped in normal Python strings, and that results in expressions that are difficult to read. Using raw strings, created by prefixing the literal value with r, for creating regular expressions eliminates this problem and maintains readability.
Personally, I think this use of r to escape a backslash is probably one of the things that block someone who is not familiar with regex in Python from being able to read regex code at first. Hopefully after seeing these examples this syntax will become clear.
Can you write Python code for it?

test_phrase = 'This is a string with some numbers 1233 and a symbol #hashtag'

test_patterns=[ r'\d+', # sequence of digits
                r'\D+', # sequence of non-digits
                r'\s+', # sequence of whitespace
                r'\S+', # sequence of non-whitespace
                r'\w+', # alphanumeric characters
                r'\W+', # non-alphanumeric
                ]

multi_re_find(test_patterns,test_phrase)


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Regular Expressions-checkpoint.ipynb".
The first task is:
It makes sense that the first [sd] returns every instance. Also the second input will just return any thing starting with an s in this particular case of the test phrase input.
Exclusion
We can use ^ to exclude terms by incorporating it into the bracket syntax notation. For example: [^...] will match any single character not in the brackets. Let's see some examples:
Can you write Python code for it?

test_phrase = 'This is a string! But it has punctutation. How can we remove it?'


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Regular Expressions-checkpoint.ipynb".
The first task is:
Now we've seen that re.search() will take the pattern, scan the text, and then returns a Match object. If no pattern is found, a None is returned. To give a clearer picture of this match object, check out the cell below:
Can you write Python code for it?

# List of patterns to search for
pattern = 'term1'

# Text to parse
text = 'This is a string with term1, but it does not have the other term.'

match = re.search(pattern,  text)

type(match)


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Regular Expressions-checkpoint.ipynb".
The first task is:
Pattern re Syntax
This will be the bulk of this lecture on using re with Python. Regular expressions supports a huge variety of patterns the just simply finding where a single string occurred.
We can use metacharacters along with re to find specific types of patterns.
Since we will be testing multiple re syntax forms, let's create a function that will print out recults given a list of various regular expressions and a phrase to parse:
Can you write Python code for it?

def multi_re_find(patterns,phrase):
    '''
    Takes in a list of regex patterns
    Prints a list of all matches
    '''
    for pattern in patterns:
        print 'Searching the phrase using the re check: %r' %pattern
        print re.findall(pattern,phrase)
        print '\n'


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Regular Expressions-checkpoint.ipynb".
The first task is:
Repetition Syntax
There are five ways to express repetition in a pattern:
1.) A pattern followed by the metacharacter * is repeated zero or more times.
2.) Replace the * with + and the pattern must appear at least once.
3.) Using ? means the pattern appears zero or one time.
4.) For a specific number of occurrences, use {m} after the pattern, where m is replaced with the number of times         the pattern should repeat.
5.) Use {m,n} where m is the minimum number of repetitions and n is the maximum. Leaving out n ({m,}) means the           value appears at least m times, with no maximum.

Now we will see an example of each of these using our multi_re_find function:
Can you write Python code for it?

test_phrase = 'sdsd..sssddd...sdddsddd...dsds...dsssss...sdddd'

test_patterns = [ 'sd*',     # s followed by zero or more d's
                'sd+',          # s followed by one or more d's
                'sd?',          # s followed by zero or one d's
                'sd{3}',        # s followed by three d's
                'sd{2,3}',      # s followed by two to three d's
                ]

multi_re_find(test_patterns,test_phrase)


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Regular Expressions-checkpoint.ipynb".
The first task is:
Split with regular expressions
Let's see how we can split with the re syntax. This should look similar to how you used the split() method with strings.
Can you write Python code for it?

# Term to split on
split_term = '@'

phrase = 'What is the domain name of someone with the email: hello@gmail.com'

# Split the phrase
re.split(split_term,phrase)


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Regular Expressions-checkpoint.ipynb".
The first task is:
Use [^!.? ] to check for matches that are not a !,.,?, or space. Add the + to check that the match appears at least once, this basicaly translate into finding the words.
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Statements Assessment Test - Solutions-checkpoint.ipynb".
The first task is:
Go through the string below and if the length of a word is even print "even!"
Can you write Python code for it?

st = 'Print every word in this sentence that has an even number of letters'

for word in st.split():
    if len(word)%2 == 0:
        print word+" <-- has an even length!"


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Statements Assessment Test - Solutions-checkpoint.ipynb".
The first task is:
Use List comprehension to create a list of all numbers between 1 and 50 that are divisble by 3.
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Statements Assessment Test - Solutions-checkpoint.ipynb".
The first task is:
Write a program that prints the integers from 1 to 100. But for multiples of three print "Fizz" instead of the number, and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz".
Can you write Python code for it?

for num in xrange(1,101):
    if num % 5 == 0 and num % 3 == 0:
        print "FizzBuzz"
    elif num % 3 == 0:
        print "Fizz"
    elif num % 5 == 0:
        print "Buzz"
    else:
        print num


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Statements Assessment Test-checkpoint.ipynb".
The first task is:
Go through the string below and if the length of a word is even print "even!"
Can you write Python code for it?

st = 'Print every word in this sentence that has an even number of letters'

#Code in this cell


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Statements Assessment Test-checkpoint.ipynb".
The first task is:
Use range() to print all the even numbers from 0 to 10.
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Statements Assessment Test-checkpoint.ipynb".
The first task is:
Write a program that prints the integers from 1 to 100. But for multiples of three print "Fizz" instead of the number, and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz".
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Strings-checkpoint.ipynb".
The first task is:
Let's start indexing!
Can you write Python code for it?

# Show first element (in this case a letter)
s[0]

s[1]

s[2]


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Strings-checkpoint.ipynb".
The first task is:
Note the above slicing. Here we're telling Python to grab everything from 0 up to 3. It doesn't include the 3rd index. You'll notice this a lot in Python, where statements and are usually in the context of "up to, but not including".
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Strings-checkpoint.ipynb".
The first task is:
Notice how the error tells us directly what we can't do, change the item assignment!
Something we can do is concatenate strings!
Can you write Python code for it?

s

# Concatenate strings!
s + ' concatenate me!'

# We can reassign s completely though!
s = s + ' concatenate me!'

print(s)

s


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Strings-checkpoint.ipynb".
The first task is:
String Properties
Its important to note that strings have an important property known as immutability. This means that once a string is created, the elements within it can not be changes or replaced. For example:
Can you write Python code for it?

s

# Let's try to change the first letter to 'x'
s[0] = 'x'


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Strings-checkpoint.ipynb".
The first task is:
There are many more methods than the ones covered here. Visit the advanced String section to find out more!
Print Formatting
We can use the .format() method to add formatted objects to printed string statements.
The easiest way to show this is through an example:
Can you write Python code for it?

'Insert another string with curly brackets: {}'.format('The inserted string')


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Strings-checkpoint.ipynb".
The first task is:
We can also use index and slice notation to grab elements of a sequence by a specified step size (teh default is 1). For instance we can use two colons in a row and then a number specifying the frequency to grab elements. For example:
Can you write Python code for it?

# Grab everything, but go in steps size of 1
s[::1]

# Grab everything, but go in step sizes of 2
s[::2]

# We can use this to print a string backwards
s[::-1]


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Strings-checkpoint.ipynb".
The first task is:
We can use a : to perform slicing which grabs everything up to a designated point. For example:
Can you write Python code for it?

# Grab everything past the first term all the way to the length of s which is len(s)
s[1:]

# Note that there is no change to the original s
s

# Grab everything UP TO the 3rd index
s[:3]


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Strings-checkpoint.ipynb".
The first task is:
We can use a print statement to print a string.
Can you write Python code for it?

print 'Hello World 1'
print 'Hello World 2'
print 'Use \n to print a new line'
print '\n'
print 'See what I mean?'


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Strings-checkpoint.ipynb".
The first task is:
We can use the multiplication symbol to create repetition!
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Timing your code - timeit-checkpoint.ipynb".
The first task is:
Great! We see a significant time difference by using map()! This is good to know and we shuold keep this in mind.
Now lets introduce iPython's magic function %timeit
iPython's %timeit will perform the code in the same line a certain number of times (loops) and will give you the fastest performance time (best of 3).
Lets repeat the above examinations using iPython magic!
Can you write Python code for it?

%timeit "-".join(str(n) for n in range(100))

%timeit "-".join([str(n) for n in range(100)])

%timeit "-".join(map(str, range(100)))


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Tuples-checkpoint.ipynb".
The first task is:
Basic Tuple Methods
Tuples have built-in methods, but not as many as lists do. Lets look at two of them:
Can you write Python code for it?

# Use .index to enter a value and return the index
t.index('one')

# Use .count to count the number of times a value appears
t.count('one')


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Tuples-checkpoint.ipynb".
The first task is:
Because of this immutability, tuples can't grow. Once a tuple is made we can not add to it.
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Tuples-checkpoint.ipynb".
The first task is:
Immutability
It can't be stressed enough that tuples are immutable. To drive that point home:
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/While loops -checkpoint.ipynb".
The first task is:
Note how the other else statement wasn't reached and continuing was never printed!
After these brief but simple examples, you should feel comfortable using while statements in you code.
A word of caution however! It is possible to create an infinitely running loop with while statements. For example:
Can you write Python code for it?

# DO NOT RUN THIS CODE!!!!
while True:
    print 'Uh Oh infinite Loop!'


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/While loops -checkpoint.ipynb".
The first task is:
Note how we have a printed statement when x==3, and a continue being printed out as we continue through the outer while loop. Let's put in a break once x ==3 and see if the result makes sense:
Can you write Python code for it?

x = 0

while x < 10:
    print 'x is currently: ',x
    print ' x is still less than 10, adding 1 to x'
    x+=1
    if x ==3:
        print 'Breaking because x==3'
        break
    else:
        print 'continuing...'
        continue


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/While loops -checkpoint.ipynb".
The first task is:
Notice how many times the print statements occured and how the while loop kept going until the True condition was met, which occured once x==10. Its important to note that once this occured the code stopped. Lets see how we could add an else statement:
Can you write Python code for it?

x = 0

while x < 10:
    print 'x is currently: ',x
    print ' x is still less than 10, adding 1 to x'
    x+=1

else:
    print 'All Done!'


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/While loops -checkpoint.ipynb".
The first task is:
break, continue, pass
We can use break, continue, and pass statements in our loops to add additional functionality for various cases. The three statements are defined by:
break: Breaks out of the current closest enclosing loop.
continue: Goes to the top of the closest enclosing loop.
pass: Does nothing at all.

Thinking about break and continue statements, the general format of the while loop looks like this:
while test:
    code statement
    if test:
        break
    if test:
        continue
else:

break and continue statements can appear anywhere inside the loop’s body,but we will usually put them furhter nested in conjunction with an if statement to perform an action based on some condition.
Lets go ahead and look at some examples!
Can you write Python code for it?

x = 0

while x < 10:
    print 'x is currently: ',x
    print ' x is still less than 10, adding 1 to x'
    x+=1
    if x ==3:
        print 'x==3'
    else:
        print 'continuing...'
        continue


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Zip-checkpoint.ipynb".
The first task is:
Great! Finally lets use zip a to switch the keys and values of the two dictionaries:
Can you write Python code for it?

def switcharoo(d1,d2):
    dout = {}

    for d1key,d2val in zip(d1,d2.itervalues()):
        dout[d1key] = d2val

    return dout

switcharoo(d1,d2)


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Zip-checkpoint.ipynb".
The first task is:
Note how tuples are returned. What if one iterabel is longer than the other?
Can you write Python code for it?

x = [1,2,3]
y = [4,5,6,7,8]

# Zip the lists together
zip(x,y)


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Advanced Dictionaries.ipynb".
The first task is:
Dictionary Comprehensions
Just like List Comprehensions, Dictionary Data Types also support their own version of comprehension for quick creation. It is not as commonly used as List Comprehensions, but the syntax is:
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Advanced Dictionaries.ipynb".
The first task is:
One of the reasons it is not as common is the difficulty in structuring the key names that are not based off the values.
Iteration over keys,values, and items
Dictionaries can be iterated over using the iter methods available in a dictionary. For example:
Can you write Python code for it?

for k in d.iterkeys():
    print k

for v in d.itervalues():
    print v

for item in d.iteritems():
    print item


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Advanced Dictionaries.ipynb".
The first task is:
view items,keys and values
You can use the view methods to view items keys and values. For example:
Can you write Python code for it?

d.viewitems()

d.viewkeys()

d.viewvalues()


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Advanced Functions Test Solutions.ipynb".
The first task is:
Problem 3
Use filter to return the words from a list of words which start with a target letter.
Can you write Python code for it?

def filter_words(word_list, letter):

    return filter(lambda word: word[0]==letter,word_list)

l = ['hello','are','cat','dog','ham','hi','go','to','heart']
filter_words(l,'h')


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Advanced Functions Test Solutions.ipynb".
The first task is:
Problem 4
Use zip and list comprehension to return a list of the same length where each value is the two strings from
L1 and L2 concatenated together with connector between them. Look at the example output below:
Can you write Python code for it?

def concatenate(L1, L2, connector):

    return [word1+connector+word2 for (word1,word2) in zip(L1,L2)]

concatenate(['A','B'],['a','b'],'-')


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Advanced Functions Test Solutions.ipynb".
The first task is:
Problem 5
Use enumerate and other skills to return a dictionary which has the values of the list as keys and the index as the value. You may assume that a value will only appear once in the given list.
Can you write Python code for it?

def d_list(L):

    return {key:value for value,key in enumerate(L)}

d_list(['a','b','c'])


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Advanced Functions Test Solutions.ipynb".
The first task is:
Problem 6
Use enumerate and other skills from above to return the count of the number of items in the list whose value equals its index.
Can you write Python code for it?

def count_match_index(L):

    return len([num for count,num in enumerate(L) if num == count])

count_match_index([0,2,2,1,5,5,6,10])


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Advanced Functions Test.ipynb".
The first task is:
Problem 2
Use reduce to take a list of digits and return the number that they
correspond to. Do not convert the integers to strings!
Can you write Python code for it?

def digits_to_num(digits):

    pass

digits_to_num([3,4,3,2,1])


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Advanced Functions Test.ipynb".
The first task is:
Problem 5
Use enumerate and other skills to return a dictionary which has the values of the list as keys and the index as the value. You may assume that a value will only appear once in the given list.
Can you write Python code for it?

def d_list(L):

    pass

d_list(['a','b','c'])


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Collections Module.ipynb".
The first task is:
An Ordered Dictionary:
Can you write Python code for it?

print 'OrderedDict:'

d = collections.OrderedDict()

d['a'] = 'A'
d['b'] = 'B'
d['c'] = 'C'
d['d'] = 'D'
d['e'] = 'E'

for k, v in d.items():
    print k, v


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Collections Module.ipynb".
The first task is:
Common patterns when using the Counter() object
Can you write Python code for it?

sum(c.values())                 # total of all counts
c.clear()                       # reset all counts
list(c)                         # list unique elements
set(c)                          # convert to a set
dict(c)                         # convert to a regular dictionary
c.items()                       # convert to a list of (elem, cnt) pairs
Counter(dict(list_of_pairs))    # convert from a list of (elem, cnt) pairs
c.most_common()[:-n-1:-1]       # n least common elements
c += Counter()                  # remove zero and negative counts


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Collections Module.ipynb".
The first task is:
Counter with words in a sentence
Can you write Python code for it?

s = 'How many times does each word show up in this sentence word times each each word'

words = s.split()

Counter(words)

# Methods with Counter()
c = Counter(words)

c.most_common(2)


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Collections Module.ipynb".
The first task is:
For simple use cases, this is usually enough. On the other hand, remembering which index should be used for each value can lead to errors, especially if the tuple has a lot of fields and is constructed far from where it is used. A namedtuple assigns names, as well as the numerical index, to each member.
Each kind of namedtuple is represented by its own class, created by using the namedtuple() factory function. The arguments are the name of the new class and a string containing the names of the elements.
You can basically think of namedtuples as a very quick way of creating a new object/class type with some attribute fields.
For example:
Can you write Python code for it?

from collections import namedtuple

Dog = namedtuple('Dog','age breed name')

sam = Dog(age=2,breed='Lab',name='Sammy')

frank = Dog(age=2,breed='Shepard',name="Frankie")


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Collections Module.ipynb".
The first task is:
OrderedDict
An OrderedDict is a dictionary subclass that remembers the order in which its contents are added.
Fro example a normal dictionary:
Can you write Python code for it?

print 'Normal dictionary:'

d = {}

d['a'] = 'A'
d['b'] = 'B'
d['c'] = 'C'
d['d'] = 'D'
d['e'] = 'E'

for k, v in d.items():
    print k, v


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Collections Module.ipynb".
The first task is:
We construct the namedtuple by first passing the object type name (Dog) and then passing a string with the variety of fields as a string with spaces between the field names. We can then call on the various attributes:
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Collections Module.ipynb".
The first task is:
defaultdict
defaultdict is a dictionary like object which provides all methods provided by dictionary but takes first argument (default_factory) as default data type for the dictionary. Using defaultdict is faster than doing the same using dict.set_default method.
A defaultdict will never raise a KeyError. Any key that does not exist gets the value returned by the default factory.
Can you write Python code for it?

from collections import defaultdict

d = {}

d['one']

d  = defaultdict(object)

d['one']

for item in d:
    print item


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Collections Module.ipynb".
The first task is:
namedtuple
The standard tuple uses numerical indexes to access its members, for example:
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Datetime.ipynb".
The first task is:
Another way to create new date instances uses the replace() method of an existing date. For example, you can change the year, leaving the day and month alone.
Can you write Python code for it?

d1 = datetime.date(2015, 3, 11)
print 'd1:', d1

d2 = d1.replace(year=1990)
print 'd2:', d2


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Datetime.ipynb".
The first task is:
As with time, the range of date values supported can be determined using the min and max attributes.
Can you write Python code for it?

print 'Earliest  :', datetime.date.min
print 'Latest    :', datetime.date.max
print 'Resolution:', datetime.date.resolution


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Datetime.ipynb".
The first task is:
Note: A time instance only holds values of time, and not a date associated with the time.
We can also check the min and max values a time of day can have in the module:
Can you write Python code for it?

print 'Earliest  :', datetime.time.min
print 'Latest    :', datetime.time.max
print 'Resolution:', datetime.time.resolution


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Datetime.ipynb".
The first task is:
The min and max class attributes reflect the valid range of times in a single day.
Dates
datetime (as you might suspect) also allows us to work with date timestamps. Calendar date values are represented with the date class. Instances have attributes for year, month, and day. It is easy to create a date representing today’s date using the today() class method.
Lets see some examples:
Can you write Python code for it?

today = datetime.date.today()
print today
print 'ctime:', today.ctime()
print 'tuple:', today.timetuple()
print 'ordinal:', today.toordinal()
print 'Year:', today.year
print 'Mon :', today.month
print 'Day :', today.day


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Decorators.ipynb".
The first task is:
Functions within functions
Great! So we've seen how we can treat functions as objects, now lets see how we can define functions inside of other functions:
Can you write Python code for it?

def hello(name='Jose'):
    print 'The hello() function has been executed'

    def greet():
        return '\t This is inside the greet() function'

    def welcome():
        return "\t This is inside the welcome() function"

    print greet()
    print welcome()
    print "Now we are back inside the hello() function"

hello()

welcome()


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Decorators.ipynb".
The first task is:
Great! Note how we can pass the functions as objects and then use them within other functions. Now we can get started with writing our first decorator:
Creating a Decorator
In the previous example we actually manually created a Decorator. Here we will modify it to make its use case clear:
Can you write Python code for it?

def new_decorator(func):

    def wrap_func():
        print "Code would be here, before executing the func"

        func()

        print "Code here will execute after the func()"

    return wrap_func

def func_needs_decorator():
    print "This function is in need of a Decorator"

func_needs_decorator()

# Reassign func_needs_decorator
func_needs_decorator = new_decorator(func_needs_decorator)

func_needs_decorator()


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Decorators.ipynb".
The first task is:
Great! Now we can see how x is pointing to the greet function inside of the hello function.
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Decorators.ipynb".
The first task is:
Here we get back a dictionary of all the global variables, many of them are predefined in Python. So let's go ahead and look at the keys:
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Decorators.ipynb".
The first task is:
Lets take a quick look at the code again.
In the if/else clause we are returning greet and welcome, not greet() and welcome().
This is because when you put a pair of parentheses after it, the function gets executed; whereas if you don’t put parenthesis after it, then it can be passed around and can be assigned to other variables without executing it.
When we write x = hello(), hello() gets executed and because the name is Jose by default, the function greet is returned. If we change the statement to x = hello(name = "Sam") then the welcome function will be returned. We can also do print hello()() which outputs now you are in the greet() function.
Functions as Arguments
Now lets see how we can pass functions as arguments into other functions:
Can you write Python code for it?

def hello():
    return 'Hi Jose!'

def other(func):
    print 'Other code would go here'
    print func()

other(hello)


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Decorators.ipynb".
The first task is:
Note how due to scope, the welcome() function is not defined outside of the hello() function. Now lets learn about returning functions from within functions:
Returning Functions
Can you write Python code for it?

def hello(name='Jose'):

    def greet():
        return '\t This is inside the greet() function'

    def welcome():
        return "\t This is inside the welcome() function"

    if name == 'Jose':
        return greet
    else:
        return welcome

x = hello()


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Decorators.ipynb".
The first task is:
Remember that Python functions create a new scope, meaning the function has its own namespace to find variable names when they are mentioned within the function. We can check for local variables and global variables with the local() and globals() functions. For example:
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Dictionaries.ipynb".
The first task is:
A few Dictionary Methods
There are a few methods we can call on a dictionary. Let's get a quick introduction to a few of them:
Can you write Python code for it?

# Create a typical dictionary
d = {'key1':1,'key2':2,'key3':3}

# Method to return a list of all keys
d.keys()

# Method to grab all values
d.values()

# Method to return tuples of all items  (we'll learn about tuples soon)
d.items()


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Dictionaries.ipynb".
The first task is:
A quick note, Python has a built-in method of doing a self subtraction or addition (or multiplication or division). We could have also used += or -= for the above statement. For example:
Can you write Python code for it?

# Set the object equal to itself minus 123
my_dict['key1'] -= 123
my_dict['key1']


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Dictionaries.ipynb".
The first task is:
Its important to note that dictionaries are very flexible in the data types they can hold. For example:
Can you write Python code for it?

my_dict = {'key1':123,'key2':[12,23,33],'key3':['item0','item1','item2']}

#Lets call items from the dictionary
my_dict['key3']

# Can call an index on that value
my_dict['key3'][0]

#Can then even call methods on that value
my_dict['key3'][0].upper()


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Dictionaries.ipynb".
The first task is:
We can also create keys by assignment. For instance if we started off with an empty dictionary, we could continually add to it:
Can you write Python code for it?

# Create a new dictionary
d = {}

# Create a new key through assignment
d['animal'] = 'Dog'

# Can do this with any object
d['answer'] = 42

#Show
d


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Dictionaries.ipynb".
The first task is:
We can effect the values of a key as well. For instance:
Can you write Python code for it?

my_dict['key1']

# Subtract 123 from the value
my_dict['key1'] = my_dict['key1'] - 123

#Check
my_dict['key1']


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Dictionaries.ipynb".
The first task is:
Wow! That's a quite the inception of dictionaries! Let's see how we can grab that value:
Can you write Python code for it?

# Keep calling the keys
d['key1']['nestkey']['subnestkey']


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Errors and Exceptions Handling.ipynb".
The first task is:
Great! Now we don't actually need to memorize that list of exception types! Now what if we kept wanting to run code after the exception occurred? This is where finally comes in.
finally
The finally: block of code will always be run regardless if there was an exception in the try code block. The syntax is:
try:
   Code block here
   ...
   Due to any exception, this code may be skipped!
finally:
   This code block would always be executed.

For example:
Can you write Python code for it?

try:
   f = open("testfile", "w")
   f.write("Test write statement")
finally:
   print "Always execute finally code blocks"


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Errors and Exceptions Handling.ipynb".
The first task is:
Hmmm...that only did one check. How can we continually keep checking? We can use a while loop!
Can you write Python code for it?

def askint():
    while True:
        try:
            val = int(raw_input("Please enter an integer: "))
        except:
            print "Looks like you did not enter an integer!"
            continue
        else:
            print 'Yep thats an integer!'
            break
        finally:
            print "Finally, I executed!"
        print val

askint()


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Errors and Exceptions Handling.ipynb".
The first task is:
Notice how we got an error when trying to print val (because it was never properly assigned) Lets remedy this by asking the user and checking to make sure the input type is an integer:
Can you write Python code for it?

def askint():
        try:
            val = int(raw_input("Please enter an integer: "))
        except:
            print "Looks like you did not enter an integer!"
            val = int(raw_input("Try again-Please enter an integer: "))
        finally:
            print "Finally, I executed!"
        print val

askint()


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Errors and Exceptions Handling.ipynb".
The first task is:
Now lets see what would happen if we did not have write permission (opening only with 'r'):
Can you write Python code for it?

try:
    f = open('testfile','r')
    f.write('Test write this')
except IOError:
    # This will only check for an IOError exception and then execute this print statement
   print "Error: Could not find file or read data"
else:
   print "Content written successfully"
   f.close()


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Errors and Exceptions Homework - Solution.ipynb".
The first task is:
Problem 2
Handle the exception thrown by the code below by using try and except blocks. Then use a finally block to print 'All Done.'
Can you write Python code for it?

x = 5
y = 0
try:
    z = x/y
except ZeroDivisionError:
    print "Can't divide by Zero!"
finally:
    print 'All Done!'


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Errors and Exceptions Homework - Solution.ipynb".
The first task is:
Problem 3
Write a function that asks for an integer and prints the square of it. Use a while loop with a try,except, else block to account for incorrect inputs.
Can you write Python code for it?

def ask():

    while True:
        try:
            n = input('Input an integer: ')
        except:
            print 'An error occurred! Please try again!'
            continue
        else:
            break

    print 'Thank you, you number squared is: ',n**2

ask()


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Files.ipynb".
The first task is:
Don't worry about fully understanding this yet, for loops are coming up soon. But we'll break down what we did above. We said that for every line in this text file, go ahead and print that line. Its important to note a few things here:
1.) We could have called the 'line' object anything (see example below).
2.) By not calling .read() on the file, the whole text file was not stored in memory.
3.) Notice the indent on the second line for print. This whitespace is required in Python.

We'll learn a lot more about this later, but up next: Sets and Booleans!
Can you write Python code for it?

# Pertaining to the first point above
for asdf in open('test.txt'):
    print asdf


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Files.ipynb".
The first task is:
Python Opening a file
We can open a file with the open() function. The open function also takes in arguments (also called parameters). Lets see how this is used:
Can you write Python code for it?

# Open the text.txt we made earlier
my_file = open('test.txt')

# We can now read the file
my_file.read()

# But what happens if we try to read it again?
my_file.read()


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/For Loops.ipynb".
The first task is:
Cool! With tuples in a sequence we can access the items inside of them through unpacking! The reason this is important is because many object will deliver their iterables through tuples. Let's start exploring iterating through Dictionaries to explore this further!
Example 7
Can you write Python code for it?

d = {'k1':1,'k2':2,'k3':3}

for item in d:
    print item


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/For Loops.ipynb".
The first task is:
Example 3
Another common idea during a for loop is keeping some sort of running tally during the multiple loops. For example, lets create a for loop that sums up the list:
Can you write Python code for it?

# Start sum at zero
list_sum = 0

for num in l:
    list_sum = list_sum + num

print list_sum


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/For Loops.ipynb".
The first task is:
Example 4
We've used for loops with lists, how about with strings? Remember strings are a sequence so when we iterate through them we will be accessing each item in that string.
Can you write Python code for it?

for letter in 'This is a string.':
    print letter


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/For Loops.ipynb".
The first task is:
Example 5
Let's now look at how a for loop can be used with a tuple:
Can you write Python code for it?

tup = (1,2,3,4,5)

for t in tup:
    print t


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/For Loops.ipynb".
The first task is:
Example 6
Tuples have a special quality when it comes to for loops. If you are iterating through a sequence that contains tuples, the item can actually be the tuple itself, this is an example of tuple unpacking. During the for loop we will be unpacking the tuple inside of a sequence and we can access the individual items inside that tuple!
Can you write Python code for it?

l = [(2,4),(6,8),(10,12)]

for tup in l:
    print tup

# Now with unpacking!
for (t1,t2) in l:
    print t1


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/For Loops.ipynb".
The first task is:
Great! Hopefully this makes sense. Now lets add a if statement to check for even numbers. We'll first introduce a new concept here--the modulo.
Modulo
The modulo allows us to get the remainder in a division and uses the % symbol. For example:
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/For Loops.ipynb".
The first task is:
Great! Read over the above cell and make sure you understand fully what is going on. Also we could have implemented a += to to the addition towards the sum. For example:
Can you write Python code for it?

# Start sum at zero
list_sum = 0

for num in l:
    list_sum += num

print list_sum


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/For Loops.ipynb".
The first task is:
Notice that if a number is fully divisible with no remainder, the result of the modulo call is 0. We can use this to test for even numbers, since if a number modulo 2 is equal to 0, that means it is an even number!
Back to the for loops!
Example 2
Let's print only the even numbers from that list!
Can you write Python code for it?

for num in l:
    if num % 2 == 0:
        print num


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/For Loops.ipynb".
The first task is:
We could have also put in else statement in there:
Can you write Python code for it?

for num in l:
    if num % 2 == 0:
        print num
    else:
        print 'Odd number'


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Functions and Methods Homework - Solutions.ipynb".
The first task is:
If you only wanted to return a boolean:
Can you write Python code for it?

def ran_bool(num,low,high):
    return num in range(low,high+1)

ran_bool(3,1,10)


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Functions and Methods Homework - Solutions.ipynb".
The first task is:
Write a Python function that checks whether a passed string is palindrome or not.
Note: A palindrome is word, phrase, or sequence that reads the same backward as forward, e.g., madam or nurses run.
Can you write Python code for it?

def palindrome(s):

    s = s.replace(' ','') # This replaces all spaces " " with no space ''. (Fixes issues with strings that have spaces)
    return s == s[::-1] # Check through slicing

palindrome('nurses run')

palindrome('abcba')


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Functions and Methods Homework - Solutions.ipynb".
The first task is:
Write a function that checks whether a number is in a given range (Inclusive of high and low)
Can you write Python code for it?

def ran_check(num,low,high):
    #Check if num is between low and high (including low and high)
    if num in range(low,high+1):
        print " %s is in the range" %str(num)
    else :
        print "The number is outside the range."


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Functions and Methods Homework.ipynb".
The first task is:
Hard:
Write a Python function to check whether a string is pangram or not.
Note : Pangrams are words or sentences containing every letter of the alphabet at least once.
For example : "The quick brown fox jumps over the lazy dog"

Hint: Look at the string module
Can you write Python code for it?

import string

def ispangram(str1, alphabet=string.ascii_lowercase):
    pass

ispangram("The quick brown fox jumps over the lazy dog")

string.ascii_lowercase


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Functions and Methods Homework.ipynb".
The first task is:
Write a Python function that checks whether a passed string is palindrome or not.
Note: A palindrome is word, phrase, or sequence that reads the same backward as forward, e.g., madam or nurses run.
Can you write Python code for it?

def palindrome(s):
    pass

palindrome('helleh')


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Functions and Methods Homework.ipynb".
The first task is:
Write a Python function to multiply all the numbers in a list.
Sample List : [1, 2, 3, -4]
Expected Output : -24
Can you write Python code for it?

def multiply(numbers):
    pass

multiply([1,2,3,-4])


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Functions and Methods Homework.ipynb".
The first task is:
Write a function that checks whether a number is in a given range (Inclusive of high and low)
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Functions.ipynb".
The first task is:
Example 2: A simple greeting function
Let's write a function that greets people with their name.
Can you write Python code for it?

def greeting(name):
    print 'Hello %s' %name

greeting('Jose')


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Functions.ipynb".
The first task is:
Note how we break the code after the print statement! We can actually improve this by only checking to the square root of the target number, also we can disregard all even numbers after checking for 2. We'll also switch to returning a boolean value to get an example of using return statements:
Can you write Python code for it?

import math

def is_prime(num):
    '''
    Better method of checking for primes.
    '''
    if num % 2 == 0 and num > 2:
        return False
    for i in range(3, int(math.sqrt(num)) + 1, 2):
        if num % i == 0:
            return False
    return True

is_prime(14)


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Functions.ipynb".
The first task is:
Note that because we don't declare variable types in Python, this function could be used to add numbers or sequences together! We'll later learn about adding in checks to make sure a user puts in the correct arguments into a function.
Lets also start using break,continue, and pass statements in our code. We introduced these during the while lecture.
Finally lets go over a full example of creating a function to check if a number is prime ( a common interview exercise).
We know a number is prime if that number is only evenly divisible by 1 and itself. Let's write our first version of the function to check all the numbers from 1 to N and perform modulo checks.
Can you write Python code for it?

def is_prime(num):
    '''
    Naive method of checking for primes.
    '''
    for n in range(2,num):
        if num % n == 0:
            print 'not prime'
            break
    else: # If never mod zero, then prime
        print 'prime'

is_prime(16)


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Functions.ipynb".
The first task is:
What happens if we input two strings?
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/GUI/.ipynb_checkpoints/3 - Widget Events-checkpoint.ipynb".
The first task is:
Function traitlets.link and traitlets.dlink return a Link or DLink object. The link can be broken by calling the unlink method.
Can you write Python code for it?

# May get an error depending on order of cells being run!
l.unlink()
dl.unlink()


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/GUI/.ipynb_checkpoints/3 - Widget Events-checkpoint.ipynb".
The first task is:
Linking Widgets
Often, you may want to simply link widget attributes together. Synchronization of attributes can be done in a simpler way than by using bare traitlets events.
Linking traitlets attributes from the server side
The first method is to use the link and dlink functions from the traitlets module.
Can you write Python code for it?

import traitlets

# Create Caption
caption = widgets.Latex(value = 'The values of slider1 and slider2 are synchronized')

# Create IntSlider
slider1 = widgets.IntSlider(description='Slider 1')
slider2 =  widgets.IntSlider(description='Slider 2')

# Use trailets to link
l = traitlets.link((slider1, 'value'), (slider2, 'value'))

# Display!
display(caption, slider1, slider2)

# Create Caption
caption = widgets.Latex(value = 'Changes in source values are reflected in target1')

# Create Sliders
source = widgets.IntSlider(description='Source')
target1 = widgets.IntSlider(description='Target 1')

# Use dlink
dl = traitlets.dlink((source, 'value'), (target1, 'value'))
display(caption, source, target1)


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/GUI/.ipynb_checkpoints/3 - Widget Events-checkpoint.ipynb".
The first task is:
Linking widgets attributes from the client side
When synchronizing traitlets attributes, you may experience a lag because of the latency due to the roundtrip to the server side. You can also directly link widget attributes in the browser using the link widgets, in either a unidirectional or a bidirectional fashion.
Can you write Python code for it?

# NO LAG VERSION
caption = widgets.Latex(value = 'The values of range1 and range2 are synchronized')

range1 = widgets.IntSlider(description='Range 1')
range2 =  widgets.IntSlider(description='Range 2')

l = widgets.jslink((range1, 'value'), (range2, 'value'))
display(caption, range1, range2)

# NO LAG VERSION
caption = widgets.Latex(value = 'Changes in source_range values are reflected in target_range1')

source_range = widgets.IntSlider(description='Source range')
target_range1 = widgets.IntSlider(description='Target range ')

dl = widgets.jsdlink((source_range, 'value'), (target_range1, 'value'))
display(caption, source_range, target_range1)


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/GUI/.ipynb_checkpoints/3 - Widget Events-checkpoint.ipynb".
The first task is:
Signatures
Mentioned in the doc string, the callback registered can have 4 possible signatures:

callback()
callback(trait_name)
callback(trait_name, new_value)
callback(trait_name, old_value, new_value)

Using this method, an example of how to output an IntSlider's value as it is changed can be seen below.
Can you write Python code for it?

int_range = widgets.IntSlider()
display(int_range)

def on_value_change(name, value):
    print(value)

int_range.on_trait_change(on_value_change, 'value')


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/GUI/.ipynb_checkpoints/3 - Widget Events-checkpoint.ipynb".
The first task is:
Traitlet events
Widget properties are IPython traitlets and traitlets are eventful.  To handle  changes, the on_trait_change method of the widget can be used to register a callback.  The doc string for on_trait_change can be seen below.
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/GUI/.ipynb_checkpoints/4 - Widget List-checkpoint.ipynb".
The first task is:
Boolean widgets
There are three widgets that are designed to display a boolean value.
ToggleButton
Can you write Python code for it?

widgets.ToggleButton(
    description='Click me',
    value=False,
)


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/GUI/.ipynb_checkpoints/4 - Widget List-checkpoint.ipynb".
The first task is:
BoundedFloatText
Can you write Python code for it?

widgets.BoundedFloatText(
    value=7.5,
    min=5.0,
    max=10.0,
    description='Text:',
)


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/GUI/.ipynb_checkpoints/4 - Widget List-checkpoint.ipynb".
The first task is:
Button
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/GUI/.ipynb_checkpoints/4 - Widget List-checkpoint.ipynb".
The first task is:
FloatProgress
Can you write Python code for it?

widgets.FloatProgress(
    value=7.5,
    min=5.0,
    max=10.0,
    step=0.1,
    description='Loading:',
)


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/GUI/.ipynb_checkpoints/4 - Widget List-checkpoint.ipynb".
The first task is:
Numeric widgets
There are 8 widgets distributed with IPython that are designed to display numeric values.  Widgets exist for displaying integers and floats, both bounded and unbounded.  The integer widgets share a similar naming scheme to their floating point counterparts.  By replacing Float with Int in the widget name, you can find the Integer equivalent.
FloatSlider
Can you write Python code for it?

widgets.FloatSlider(
    value=7.5,
    min=5.0,
    max=10.0,
    step=0.1,
    description='Test:',
)


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/GUI/.ipynb_checkpoints/4 - Widget List-checkpoint.ipynb".
The first task is:
RadioButtons
Can you write Python code for it?

widgets.RadioButtons(
    description='Pizza topping:',
    options=['pepperoni', 'pineapple', 'anchovies'],
)


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/GUI/.ipynb_checkpoints/4 - Widget List-checkpoint.ipynb".
The first task is:
SelectMultiple
Multiple values can be selected with shift and/or ctrl (or command) pressed and mouse clicks or arrow keys.
Can you write Python code for it?

w = widgets.SelectMultiple(
    description="Fruits",
    options=['Apples', 'Oranges', 'Pears'])

display(w)

w.value


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/GUI/.ipynb_checkpoints/4 - Widget List-checkpoint.ipynb".
The first task is:
Selection widgets
There are four widgets that can be used to display single selection lists, and one that can be used to display multiple selection lists.  All inherit from the same base class.  You can specify the enumeration of selectable options by passing a list.  You can also specify the enumeration as a dictionary, in which case the keys will be used as the item displayed in the list and the corresponding value will be returned when an item is selected.
Dropdown
Can you write Python code for it?

from IPython.display import display

w = widgets.Dropdown(
    options=['1', '2', '3'],
    value='2',
    description='Number:',
)
display(w)

# Show value
w.value


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/GUI/.ipynb_checkpoints/4 - Widget List-checkpoint.ipynb".
The first task is:
Sliders can also be displayed vertically.
Can you write Python code for it?

widgets.FloatSlider(
    value=7.5,
    min=5.0,
    max=10.0,
    step=0.1,
    description='Test',
    orientation='vertical',
)


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/GUI/.ipynb_checkpoints/4 - Widget List-checkpoint.ipynb".
The first task is:
String widgets
There are 4 widgets that can be used to display a string value.  Of those, the Text and Textarea widgets accept input.  The Latex and HTML widgets display the string as either Latex or HTML respectively, but do not accept input.
Text
Can you write Python code for it?

widgets.Text(
    description='String:',
    value='Hello World',
)


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/GUI/.ipynb_checkpoints/4 - Widget List-checkpoint.ipynb".
The first task is:
Textarea
Can you write Python code for it?

widgets.Textarea(
    description='String:',
    value='Hello World',
)


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/GUI/.ipynb_checkpoints/4 - Widget List-checkpoint.ipynb".
The first task is:
ToggleButtons
Can you write Python code for it?

widgets.ToggleButtons(
    description='Speed:',
    options=['Slow', 'Regular', 'Fast'],
)


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/GUI/.ipynb_checkpoints/5 - Widget Styling-checkpoint.ipynb".
The first task is:
After the parent is displayed
Children can be added to parents after the parent has been displayed.  The parent is responsible for rendering its children.
Can you write Python code for it?

container = widgets.Box()
container.border_color = 'red'
container.border_style = 'dotted'
container.border_width = 3
display(container)

int_range = widgets.IntSlider()
container.children=[int_range]


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/GUI/.ipynb_checkpoints/5 - Widget Styling-checkpoint.ipynb".
The first task is:
Alignment
Most widgets have a description attribute, which allows a label for the widget to be defined.
The label of the widget has a fixed minimum width.
The text of the label is always right aligned and the widget is left aligned:
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/GUI/.ipynb_checkpoints/5 - Widget Styling-checkpoint.ipynb".
The first task is:
Another example
In the example below, a form is rendered, which conditionally displays widgets depending on the state of other widgets.  Try toggling the student checkbox.
Can you write Python code for it?

form = widgets.VBox()
first = widgets.Text(description="First:")
last = widgets.Text(description="Last:")

student = widgets.Checkbox(description="Student:", value=False)
school_info = widgets.VBox(visible=False, children=[
    widgets.Text(description="School:"),
    widgets.IntText(description="Grade:", min=0, max=12)
    ])

pet = widgets.Text(description="Pet:")
form.children = [first, last, student, school_info, pet]
display(form)

def on_student_toggle(name, value):
    if value:
        school_info.visible = True
    else:
        school_info.visible = False
student.on_trait_change(on_student_toggle, 'value')


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/GUI/.ipynb_checkpoints/5 - Widget Styling-checkpoint.ipynb".
The first task is:
Fancy boxes
If you need to display a more complicated set of widgets, there are specialized containers that you can use.  To display multiple sets of widgets, you can use an Accordion or a Tab in combination with one Box per set of widgets (as seen below).  The "pages" of these widgets are their children.  To set the titles of the pages, use set_title.
Accordion
Can you write Python code for it?

name1 = widgets.Text(description='Location:')
zip1 = widgets.BoundedIntText(description='Zip:', min=0, max=99999)
page1 = widgets.Box(children=[name1, zip1])

name2 = widgets.Text(description='Location:')
zip2 = widgets.BoundedIntText(description='Zip:', min=0, max=99999)
page2 = widgets.Box(children=[name2, zip2])

accord = widgets.Accordion(children=[page1, page2], width=400)
display(accord)

accord.set_title(0, 'From')
accord.set_title(1, 'To')


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/GUI/.ipynb_checkpoints/5 - Widget Styling-checkpoint.ipynb".
The first task is:
If a label is longer than the minimum width, the widget is shifted to the right:
Can you write Python code for it?