Recursions

--Originally published at Sierra's Blog

Recursion is what you have when you call a function inside a function, this can be done for different purpouses, the common example to explain recursions in python is a program that gives you the factorial of “n”:

def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
x = factorial(5)
print (x)

the function gives you the factorial of number n, which in this case is 5. The function starts being factorial(5) but at the moment that it reads the underlined part the program it needs to start again to find what’s the answer of factorial(n-1) and it goes on and on till when n reaches number 1, then, after knowing what does every factorial(n-1) value is, it starts working backwards by multiplying the factorial * the current n number, here’s how python thinks:

Python: Ok, User’s asking me to save in the variable x whatever factorial(5) returns.

Python: I need to ejecute the function factorial(n). n isn’t equal to 1 so i’ll choose the else’s part.

Python: i’ll do this step by step

1.- n = 5…  factorial(n) = n * factorial(n-1) = 5 * factorial(5-1)  return 5 * factorial(4)

2.- n = 4… factorial(n) = n * factorial(n-1) = 4 * factorial(4-1) return 4 * factorial(3)

3.- n = 3… factorial(n) = n * factorial(n-1) = 3 * factorial(3-1) return 3 * factorial(2)

4.- n = 2… factorial(n) = n * factorial(n-1) = 2 * factorial(2-1) return 2 * factorial(1)

5.- n = 1… factorial(n), n == 1 then the if statement is true! i’ll return 1

Python: now I know what factorial(2) is: 2*1 = 2

Python: now i know what factorial(3) is: 3 * factorial(2) = 3 * 2 = 6

Python: now i know what factorial(4) is:

Continue reading "Recursions"

Range!

--Originally published at Sierra's Blog

I’ve used in others posts the range function but I have never explained it.

The range function is a python predeterminated function that creates a list and are principaly used in loops.

There are different ways of using the range functions, here are them:

1.- range(Number): this will create a list which starts in 0 and end up one number before the one you wrote, for example:

for i in range(7):

print(i)

 

will produce this outcome:

0

1

2

3

4

5

6

2.-range(First number, Last Number) this way you’re telling python that you don’t want to start in 0.

Note: Python doesn’t read the last number, it stops 1 number before, for example:

for i in range (7,10):

print(i)

will produce this outcome:

7

8

9

 

 

 

Three parameters: range(First Number, Last number, Number that is going to be added)

for example:

for i in range(0, 10, 2):   #will produce:

0

2

4

6

8

#it won’t print 10 because it’s the last number.

 

This page explains a lot of stuffs about range function: http://pythoncentral.io/pythons-range-function-explained/

Thanks for watching;)


Zen of python!

--Originally published at Sierra's Blog

The zen of python is a list of principles to make your code look better, I recommend you to stick to it because it will help you making your code more understandable and simple, these are the rules which I took from this page: https://www.python.org/dev/peps/pep-0020/

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

yoga


For Loops

--Originally published at Sierra's Blog

Foor loops in python are similar to while loops but with a small difference:

While loops are used when you don’t know the exactly amount of times that your code needs to be repeated, for example, a calculator that when it finishes doing the stuff that the user asked for asks if he wants to do something else.

For loops are the opposite in this case because you, as the programmer, already know how many times do you need the code to be reapeated.

How do I call it in python?

for + Variable + in + range(x1,x2):

for – you need to start with that word

Variable – is going to be the Variable that when the for loop ends it’s going to change

*If the variable is an integer – at the end of the loop it will become variable + 1.

*if the variable is in a list – at the end of the loop it will jump into the next string on the list.

in – you need to add the word in.

range()  – the range…

for x in range (0,100):
print(“do this.”)

this program is going to repeat the phrase “do this” 100 times.

Another example with list instead of range:

Food = [“Meat”,”Ham”,”banana”, “Apple”, “Fish”]

for food in Food:
print (food)

this will print:

Meat

Ham

Banana

Apple

Fish

Notes:

Food is the name of the list.

food is the variable’s name of the strings inside the list.

 


Nesting conditional statements

--Originally published at Sierra's Blog

Sometimes when coding you’ll need to have a conditional statement inside a conditional statement.

for example, you can have an if, elif, else inside an if, elif, else statement.

to practice this you should make a rock, paper, scissors game if you dont know how you can check my version:

import random

print("Bienvenido a Piedra Papel o Tijera.")
User1 = input("¿Desea comenzar? (Si o No)")

while User1 == "Si":
    UserAnswer = input("Elige una opción (Piedra, Papel o Tijera)")

    ComputerAnswer = random.sample(["Piedra", "Papel", "Tijera"],1)
    if ComputerAnswer == ['Piedra']:
        StrcompAns = "Piedra"
    elif ComputerAnswer == ['Papel']:
        StrcompAns = "Papel"
    elif ComputerAnswer == ['Tijera']:
        StrcompAns = "Tijera"

    print("Yo he elegido " + StrcompAns +".")

    if StrcompAns == UserAnswer:
        print("Parece que hemos empatado.")
    else:
        if UserAnswer == "Piedra":
            if StrcompAns == "Papel":
                print("Parece que te he ganado")
            elif StrcompAns == "Tijera":
                print ("Parece que me has ganado")

        elif UserAnswer == "Papel":
            if StrcompAns == "Piedra" :
                print("Parece que me has ganado")
            elif StrcompAns == "Tijera":
                print("Parece que te he ganado")

        elif UserAnswer == "Tijera":
            if StrcompAns == "Piedra":
                print("Parece que te he ganado")
            elif StrcompAns == "Papel":
                print("Parece que me has ganado")
    User1 = input("¿Deseas continuar?")

print("Adios, hasta la próxima!")