Hi, this is my last WSQ. This WSQ was hard for me because i had no idea how to read a file properly by lines. Frida´s blog helped me a lot to figure this out, check it on this link: http://tc1014.blogspot.mx/2015/11/cars.html
The link to my code on Github is this: https://github.com/Jocapear/TC1014/blob/master/WSQ16.py
miércoles, 25 de noviembre de 2015
martes, 24 de noviembre de 2015
WSQ15 - Images
I won´t be able to do this WSQ because i would have to uninstall python and install it in 32 bits to be able to download the library that allows me to manipulate images.
The link to the library site is this:
http://docs.python-guide.org/en/latest/scenarios/imaging/
The link to the library site is this:
http://docs.python-guide.org/en/latest/scenarios/imaging/
Mastery14 - Creating Python modules
A custom module is just a python file with fiunctions in it. You can create a python file and put in the same location as the program where you are going to call it. Here is an example:
I will create a new file called mymodule.py
def banana(filename):
name = open(filename)
content = name.read()
list = content.split(" ")
print (list)
counter = 0
for i in list:
if i.lower() == "banana":
counter += 1
print (counter)
def calculate_e(precision):
counter = 1
accumulative = 1
variable = 1
while True:
accumulative += variable*(1/counter)
variable = (1/counter)*variable
new = accumulative + variable*(1/counter)
if (new - accumulative) < precision:
break
counter += 1
return accumulative
And now i´m going to call that file just like if it were a module. This file is called file.py and is located in the same directory as mymodule.py:
import mymodule.py
a = mymodule.banana("text.txt") #You must have a file named "text" called "text"
b = mymodule.calculate_e(35)
print (a)
print(b)
2
2.71825
As you can see in file.py i used the functions inside of mymodule.py by calling them as if they were a module(well, it is a module now)
I will create a new file called mymodule.py
def banana(filename):
name = open(filename)
content = name.read()
list = content.split(" ")
print (list)
counter = 0
for i in list:
if i.lower() == "banana":
counter += 1
print (counter)
def calculate_e(precision):
counter = 1
accumulative = 1
variable = 1
while True:
accumulative += variable*(1/counter)
variable = (1/counter)*variable
new = accumulative + variable*(1/counter)
if (new - accumulative) < precision:
break
counter += 1
return accumulative
And now i´m going to call that file just like if it were a module. This file is called file.py and is located in the same directory as mymodule.py:
import mymodule.py
a = mymodule.banana("text.txt") #You must have a file named "text" called "text"
b = mymodule.calculate_e(35)
print (a)
print(b)
2
2.71825
As you can see in file.py i used the functions inside of mymodule.py by calling them as if they were a module(well, it is a module now)
Mastery30 - Reading and writing files
Reading files:
To read a file you should know this functions: open("filename","r") and filename.read()
The first one is used to open a file, read it and pass that information to a variable ( if you want) or to simply work with it directly.
The second one will just read a file, to use this function ou should have used the open function first like this:
a = open("filename")
print (a.read())
As you can see im not using the "r" because that means that i read it at the same time i open it, if you just want to open the file but not read it right there and use that information for later you should do something like what i did above. This has a lot of functionalities if you mix this with strings manipulation. You look for a specific word, count the lines, the total words etc. Here is an aplication for that, this documento opens and reads a file and counts how many times the word "banana" is in it (WSQ14):
def process_file(filename):
name = open(filename)
content = name.read()
list = content.split(" ")
print (list)
counter = 0
for i in list:
if i.lower() == "banana":
counter += 1
print (counter)
process_file("file.txt")
To be sure that this file works correctly i must have a text file named "file" and be sure that each word written in it is separated by a space. If you noticed, reading a file is reading a file is really simple. Is just taking a value from a different file and assigning it to a varible, works like an input. What matters is how you control or process that information.
Writing a file:
To write a file you have to use the same function as before but this time with a different parameter: open("filename","w")
This "w" thing will thell python that you want to edit/write the file, be careful because this will erase the content of that file and create a new file. To write a line use fout.write() and use as a parameter a string (or a variable with a string), when you are done use fout.close(). It is very important that you understand that the file will star writing in the last empty line. Here is an example:
def process_file(filename):
name = open("filename","w")
a = "no"
while a == "yes":
line = input("Write here the new data")
fout.write(line)
a = input("want to close?")
fout.close()
process_file("file.txt")
This function will add new strings to the "file.txt" document until the user decides to stop.
To read a file you should know this functions: open("filename","r") and filename.read()
The first one is used to open a file, read it and pass that information to a variable ( if you want) or to simply work with it directly.
The second one will just read a file, to use this function ou should have used the open function first like this:
a = open("filename")
print (a.read())
As you can see im not using the "r" because that means that i read it at the same time i open it, if you just want to open the file but not read it right there and use that information for later you should do something like what i did above. This has a lot of functionalities if you mix this with strings manipulation. You look for a specific word, count the lines, the total words etc. Here is an aplication for that, this documento opens and reads a file and counts how many times the word "banana" is in it (WSQ14):
def process_file(filename):
name = open(filename)
content = name.read()
list = content.split(" ")
print (list)
counter = 0
for i in list:
if i.lower() == "banana":
counter += 1
print (counter)
process_file("file.txt")
To be sure that this file works correctly i must have a text file named "file" and be sure that each word written in it is separated by a space. If you noticed, reading a file is reading a file is really simple. Is just taking a value from a different file and assigning it to a varible, works like an input. What matters is how you control or process that information.
Writing a file:
To write a file you have to use the same function as before but this time with a different parameter: open("filename","w")
This "w" thing will thell python that you want to edit/write the file, be careful because this will erase the content of that file and create a new file. To write a line use fout.write() and use as a parameter a string (or a variable with a string), when you are done use fout.close(). It is very important that you understand that the file will star writing in the last empty line. Here is an example:
def process_file(filename):
name = open("filename","w")
a = "no"
while a == "yes":
line = input("Write here the new data")
fout.write(line)
a = input("want to close?")
fout.close()
process_file("file.txt")
This function will add new strings to the "file.txt" document until the user decides to stop.
lunes, 23 de noviembre de 2015
Mastery 5 - Linux sufficient for exams
To execute a file in Linux all you have to do is go to the terminal and write "python3" and then the location of the file. Be sure to write the name of the file and ".py" after it. To make the location shorter save the file in the main directory. An example is this:
python3 filename.py
If you are having trouble try to star again but this time write first "lb", this will take you to the main directory. Then you can continue writing as usual.
python3 filename.py
If you are having trouble try to star again but this time write first "lb", this will take you to the main directory. Then you can continue writing as usual.
Mastery 22 - Types of repetition
There are 3 types of repetition:
-For loop
-While loop
-Recursion
The FOR loop is used when you know the number of repetitions. It can be used with ranges, list tuples or dictionaries(iterable objects). It takes a value inside the object, work with it, and then do the same thing with the next value until the iterable object is finished.
The WHILE loop is used when you dont how the number of repetitons. It works with a condition and it will repeat until the condition is false.
Recursion is when you call a function inside the same function. It can be used in special cases where you need to take a value from the function itself, this job can be done with FOR or WHILE loops but it´s shorter to write a recursion.
-For loop
-While loop
-Recursion
The FOR loop is used when you know the number of repetitions. It can be used with ranges, list tuples or dictionaries(iterable objects). It takes a value inside the object, work with it, and then do the same thing with the next value until the iterable object is finished.
The WHILE loop is used when you dont how the number of repetitons. It works with a condition and it will repeat until the condition is false.
Recursion is when you call a function inside the same function. It can be used in special cases where you need to take a value from the function itself, this job can be done with FOR or WHILE loops but it´s shorter to write a recursion.
WSQ14 - Estimating e
This WSQ is easy if you understand what you have to do.
Here is the program working witha precision of 35
If you want to see my code i will post the Github link here:
https://github.com/Jocapear/TC1014/blob/master/WSQ14.py
Here is the program working witha precision of 35
If you want to see my code i will post the Github link here:
https://github.com/Jocapear/TC1014/blob/master/WSQ14.py
domingo, 22 de noviembre de 2015
Mastery 8 - Python conventions
Here i will show you what are the python conventions.
First of all, in python the indentation does matter. Indentantion is the way that python recognize if a code block has ended. For example:
if (a < b):
counter + =1
print (counter)
This is wrong because the IF has nothing inside it, instead it will always add 1+ to the counter because is at the same level as the IF. This is not C++ or JS where you can tell the program when your if ends with {}. The right way to do it is this:
if ( a < b):
counter += 1
print(counter)
Also here are some tips to give a standar python style to your code:
-Just do one statement per line
Please don´t do this:
def ejercicio3(diccionario): return (("Homework promedio:", sum(diccionario["homework"])/len(diccionario["homework" ])), ("Quizzes promedio:", sum(diccionario["quizzes"])/len(diccionario["quizzes"])), ("Tests promedio:", sum(diccionario["tests"])/len(diccionario["tests"])))
Yes, this is a python program that actually works. As you can see it is very hard to read and you will make others to have a bad time trying to understand what you want to do. Don´t be a smart a** and put order to your code so that everyone can understand it.
-Keep spaces between variables if necessary, just to make it more readable
-Build your functions on the top part of the code
I think that this is clear, declare your functions first and call them below. Try to declare all the functions you can on the top part and write the main program after that, this will make your code easier to read because if someone wants to follow the executuion order of your code he/she doesn´t have to look for a specific function on all the code; otherwise, he/she will know where the functions are and you will save him/her time.
-Keep your code simple
Here is an example of the last point:
a = input("Write a number"))
a = int(a)
for i in range(0,50)
if i/a % 0:
counter = counter + 1
b = counter*2
c = b+18
print (c)
This code is really simple but it can be done in less words and space, the proper way to do it is:
a = int (input("Write a number" ))
for i in range( 0 , 50 )
if (i/a) % 0:
counter += 1
print(counter*2+18)
First of all, in python the indentation does matter. Indentantion is the way that python recognize if a code block has ended. For example:
if (a < b):
counter + =1
print (counter)
This is wrong because the IF has nothing inside it, instead it will always add 1+ to the counter because is at the same level as the IF. This is not C++ or JS where you can tell the program when your if ends with {}. The right way to do it is this:
if ( a < b):
counter += 1
print(counter)
Also here are some tips to give a standar python style to your code:
-Just do one statement per line
Please don´t do this:
def ejercicio3(diccionario): return (("Homework promedio:", sum(diccionario["homework"])/len(diccionario["homework" ])), ("Quizzes promedio:", sum(diccionario["quizzes"])/len(diccionario["quizzes"])), ("Tests promedio:", sum(diccionario["tests"])/len(diccionario["tests"])))
Yes, this is a python program that actually works. As you can see it is very hard to read and you will make others to have a bad time trying to understand what you want to do. Don´t be a smart a** and put order to your code so that everyone can understand it.
-Keep spaces between variables if necessary, just to make it more readable
-Build your functions on the top part of the code
I think that this is clear, declare your functions first and call them below. Try to declare all the functions you can on the top part and write the main program after that, this will make your code easier to read because if someone wants to follow the executuion order of your code he/she doesn´t have to look for a specific function on all the code; otherwise, he/she will know where the functions are and you will save him/her time.
-Keep your code simple
Here is an example of the last point:
a = input("Write a number"))
a = int(a)
for i in range(0,50)
if i/a % 0:
counter = counter + 1
b = counter*2
c = b+18
print (c)
This code is really simple but it can be done in less words and space, the proper way to do it is:
a = int (input("Write a number" ))
for i in range( 0 , 50 )
if (i/a) % 0:
counter += 1
print(counter*2+18)
Masteries 24 and 27 - Creation and use of tuples and diccionaries
A tuple is like a list and is used in the same way, the only difference is that a tuple cannot be modified or changed.
A diccionarie is a colleccion of anything that can be labeled with any other thing. It is used as a list too but to use a slot in the diccionarie you have to call the key instead of the value.
Here is some code where i show that i know how to use tuples and diccionaries:
A diccionarie is a colleccion of anything that can be labeled with any other thing. It is used as a list too but to use a slot in the diccionarie you have to call the key instead of the value.
Here is some code where i show that i know how to use tuples and diccionaries:
viernes, 20 de noviembre de 2015
Quiz11
The first excercise was the same as a WSQ, i just had to change it a little bit. I got in trouble when i tried to make excercise 2 because i didn´t know how to work with files.
I researched a little bit on the book and then i played a little bit with what i found, to make the excercise i just had to combine my new knowledge with my list and string knowledge and that was all. At the end the excercise was very simple, i just had to know how to open a file.
Hint (thinks that you need to know to open a file):
open( "filename.txt") This will return a file value so put it on a variable
file = open( "filename.txt")
file.read() This read what is inside that file, returns whatever is written on it so i recommend you to put in on a variable too
If you want to see my code i will post it on Github, here is the link:
https://github.com/Jocapear/TC1014/blob/master/Quiz11.py
I researched a little bit on the book and then i played a little bit with what i found, to make the excercise i just had to combine my new knowledge with my list and string knowledge and that was all. At the end the excercise was very simple, i just had to know how to open a file.
Hint (thinks that you need to know to open a file):
open( "filename.txt") This will return a file value so put it on a variable
file = open( "filename.txt")
file.read() This read what is inside that file, returns whatever is written on it so i recommend you to put in on a variable too
If you want to see my code i will post it on Github, here is the link:
https://github.com/Jocapear/TC1014/blob/master/Quiz11.py
viernes, 13 de noviembre de 2015
martes, 10 de noviembre de 2015
WSQ13 - Babylonian method
Hello there, this WSQ was an easy one; howhever, it was useful to research a bit from this page about the baylonian method http://mathlesstraveled.com/2009/05/18/square-roots-with-pencil-and-paper-the-babylonian-method/
Here is the complete formula of the babylonian method, you just have to do it on code. EZPZ
Here is my program working:
If you want to see my code is on this link on Github:
https://github.com/Jocapear/TC1014/blob/master/WSQ13.py
Here is the complete formula of the babylonian method, you just have to do it on code. EZPZ
Here is my program working:
If you want to see my code is on this link on Github:
https://github.com/Jocapear/TC1014/blob/master/WSQ13.py
viernes, 6 de noviembre de 2015
WSQ12 - Greatest common divisor
This WSW was a littel tricky because i had to look for the algorith in google. Here is the code working:
If you want to see my code in Hithub is on this link:
https://github.com/Jocapear/TC1014/blob/master/WSQ12.py
If you want to see my code in Hithub is on this link:
https://github.com/Jocapear/TC1014/blob/master/WSQ12.py
martes, 27 de octubre de 2015
Mastery 9 - Basic types
Here im going to prove that i know the basic types of Python.
x = 7
x + 3 = 10
It canbe used for calculations
x = .7
1.4456
0.1234
x = "Hello World"
It can be added to integers and other strings
print (x,"I´m jose carlos and im",18,"years old")
Hello World I´m jose calros and im 18 years old
x = (1,2,3)
x = [6,1,9,"hola","hello"]
x = {"hola":1,"jose":2, 15:15,"new word":0}
You can modify the type of a variable with preset functions, sometimes it doesnt work
x = 12
str(x)
"12"
x = "hola"
int(x)
Error
- Integers
An integer numberx = 7
x + 3 = 10
It canbe used for calculations
- Floats
It´s a decimal numberx = .7
1.4456
0.1234
- Strings
Is a word, you need to tell pyhton that you are writing a string and not a variable with "x = "Hello World"
It can be added to integers and other strings
print (x,"I´m jose carlos and im",18,"years old")
Hello World I´m jose calros and im 18 years old
-Tuples
An uneditable list, to make one you need to use parenthesisx = (1,2,3)
-Lists
A list that can me edited, to make one you need to use bracketsx = [6,1,9,"hola","hello"]
-Dictionaries
You link elements with other type, you create one with {} and link each element with :, it is comonly used to map strings to integers.x = {"hola":1,"jose":2, 15:15,"new word":0}
You can modify the type of a variable with preset functions, sometimes it doesnt work
x = 12
str(x)
"12"
x = "hola"
int(x)
Error
Mastery 13 - Python modules
Here is a code i wrote that imports and use the math module:
The math module is useful to do calculations, on this example i used math.sqrt() because i didnt know that x ** 2 == x^2
Here is another code with another module, this time the statistics module:
I used statistics.stdev() to calculate the standart deviation, i did this because i didnt want to build the formula myself.
The math module is useful to do calculations, on this example i used math.sqrt() because i didnt know that x ** 2 == x^2
Here is another code with another module, this time the statistics module:
I used statistics.stdev() to calculate the standart deviation, i did this because i didnt want to build the formula myself.
domingo, 25 de octubre de 2015
WSQ11 - Yo soy 196
This WSQ was veeeery tricky to me.I had to see code from others to understand the problem, the blog from Charlie helped me a lot. Here is the link if you want to check his blog and code:https://charliegdrummer.wordpress.com/2015/10/23/wsq11-a-pain-in-the-feelings/
I saw some problems on charlie´s code so i managed to solve them, now the program works as it shoul work. Also, i made the code shorter and now is easier to read (at least for me). This is the program working:
I printed the list to check that all the number are there.
If you want to see the code check my Github:
https://github.com/Jocapear/TC1014/blob/master/WSQ11.py
I saw some problems on charlie´s code so i managed to solve them, now the program works as it shoul work. Also, i made the code shorter and now is easier to read (at least for me). This is the program working:
I printed the list to check that all the number are there.
If you want to see the code check my Github:
https://github.com/Jocapear/TC1014/blob/master/WSQ11.py
sábado, 24 de octubre de 2015
Mastery 21 - Recursion
Recursion is when you call a function inside the same function to do repetitive algorithms. I used this method in a Quiz to make a function that returns to you the position on the fibonacci sequence. Here is the code i used:
As you can see i did not use loops whit excersice.
As you can see i did not use loops whit excersice.
Mastery 29 - Validated input
I had some trouble figuring out how use a condition with the input type but i solved it with some reading. Here is the code that prove it:
The program will only start to work if it is a positive integer number, otherwise (if it is a string or a negative number) it will ask the user for the number repetitive times until the program receives a positive integer number
The program will only start to work if it is a positive integer number, otherwise (if it is a string or a negative number) it will ask the user for the number repetitive times until the program receives a positive integer number
Mastery 17 and 18 - Use of elif and nesting of conditional statements
The elif is a conditional used to expand options of a normal conditional of If-Else. It´s very useful when you want to check different conditions at once but at the same time you want to save time at writing the code. Lets see an example, first a program without elif:
x = input("¿What do you want to do next?")
if x == "exit":
#close the program
else:
if x == "pay":
#go to the pay window
else:
if x == "back":
#move to the previous window
else:
if x == "next":
#move to the next window
else:
if x == "add":
#add the item to the shopping list
else:
print ("please write exit, pay, back, next or add")
This program is acheap and lazy representation of an online store. It receives an input from the user and do whatever the user writes, to do this we need to check several conditions at the same time (aka a nesting of conditions): if the user wants to exit, pay, go back, go next or add the item to the list. As you can see it took me a lot of space to write those conditions in the regular way. If the first condition didn´t work it will pass to the else that is another condition and if that condition is false it will pass the the next else that is another condition and it keeps going on until one condition is true or it reaches the final else. The easy and clean way to do it is with the elif, let´s see an example of the same program but this time with elifs:
x = input("¿What do you want to do next?")
if x == "exit":
#close the program
elif x == "pay":
#go to the pay window
elif x == "back":
#move to the previous window
elif x == "next":
#move to the next window
elif x == "add":
#add the item to the shopping list
else:
print ("please write exit, pay, back, next or add")
This program do exaclty the same but it took me less time to write it and is easier to understand than the other one. The elif is like the combination of else-if, Python reads it exactly in the same way.
Notice that each elif is used as an if, with the condition by the side, the ":" at the end and the instructions are indented. To finish the nesting of conditions we put an else just as if it were a normal if/else. If the user writes "back" the first and second conditions will be false and it will execute the code inside the second elif. Have in mind that after the program ends executing the code inside the elif it will jump to the end of the nesting and continue going, what i mean is that the program will not continue checking if the other conditions are true because one has already been executed. Also, the program reads from top to botton the conditions, not at the same time; so if two conditions are true it will only execute the first one. Let´s see an example of this:
x = 3
if x > 0:
print ("X is greater than 0")
elif x < 10:
print ("X is less than ten")
elif x < 0:
print ("X is a negative number")
else:
print ("X is greater than 10")
X is greater than cero
Well, what´s wrong with this program? What´s wrong is that no matter what number you put, it will print "X is greater than 0" or "X is a negative number" completely ignoring the other two conditions. Lets see, if we write a 9 it should print "X is less than then" but also the first condition is true so it should also print "X is greater than 0" but as a nesting of conditions can only take one condition it will go for the first one to be true si it will print "X is greater than 0". If we write number 20 the first condition to be true will be x > 0 so it will print "X is greater than 0" again. Just in case that you write a negative number it will print "X is a negative number" but for all the other numbers the first condition will always be true first. If you want to make a good condition nesting with elif (also with else/if) always have in mind which condition you give the preference. Nothing happens if two or more conditions are true, the program can still work as you want if you put them in the right order. I recommend you to order the condition from specific to general, in that way if the specific condition is true but also the general is true the program is going to take the specific condition first. Here is the same program but this time taking all the posibilities from the specific to the general:
x =0
if x == 0:
print ("X is equal to 0")
elif x < 10:
print ("X is less than ten")
elif x > 10:
print ("X is greater than 10")
else:
print ("X is a negative number or is a string")
X is equal to 0
x = input("¿What do you want to do next?")
if x == "exit":
#close the program
else:
if x == "pay":
#go to the pay window
else:
if x == "back":
#move to the previous window
else:
if x == "next":
#move to the next window
else:
if x == "add":
#add the item to the shopping list
else:
print ("please write exit, pay, back, next or add")
This program is a
x = input("¿What do you want to do next?")
if x == "exit":
#close the program
elif x == "pay":
#go to the pay window
elif x == "back":
#move to the previous window
elif x == "next":
#move to the next window
elif x == "add":
#add the item to the shopping list
else:
print ("please write exit, pay, back, next or add")
This program do exaclty the same but it took me less time to write it and is easier to understand than the other one. The elif is like the combination of else-if, Python reads it exactly in the same way.
Notice that each elif is used as an if, with the condition by the side, the ":" at the end and the instructions are indented. To finish the nesting of conditions we put an else just as if it were a normal if/else. If the user writes "back" the first and second conditions will be false and it will execute the code inside the second elif. Have in mind that after the program ends executing the code inside the elif it will jump to the end of the nesting and continue going, what i mean is that the program will not continue checking if the other conditions are true because one has already been executed. Also, the program reads from top to botton the conditions, not at the same time; so if two conditions are true it will only execute the first one. Let´s see an example of this:
x = 3
if x > 0:
print ("X is greater than 0")
elif x < 10:
print ("X is less than ten")
elif x < 0:
print ("X is a negative number")
else:
print ("X is greater than 10")
X is greater than cero
Well, what´s wrong with this program? What´s wrong is that no matter what number you put, it will print "X is greater than 0" or "X is a negative number" completely ignoring the other two conditions. Lets see, if we write a 9 it should print "X is less than then" but also the first condition is true so it should also print "X is greater than 0" but as a nesting of conditions can only take one condition it will go for the first one to be true si it will print "X is greater than 0". If we write number 20 the first condition to be true will be x > 0 so it will print "X is greater than 0" again. Just in case that you write a negative number it will print "X is a negative number" but for all the other numbers the first condition will always be true first. If you want to make a good condition nesting with elif (also with else/if) always have in mind which condition you give the preference. Nothing happens if two or more conditions are true, the program can still work as you want if you put them in the right order. I recommend you to order the condition from specific to general, in that way if the specific condition is true but also the general is true the program is going to take the specific condition first. Here is the same program but this time taking all the posibilities from the specific to the general:
x =0
if x == 0:
print ("X is equal to 0")
elif x < 10:
print ("X is less than ten")
elif x > 10:
print ("X is greater than 10")
else:
print ("X is a negative number or is a string")
X is equal to 0
Masteries 20 and 23 - Loop for and creation and use of lists
I want to start explaining the lists because to use the loop for you have to know how to create lists. First of all, a list is a variable that countains several values, they can be integers or strings. The list can be differentiated from a common variable because they use "[]" and the values are separated from commas. Here is an example:
friends = ["maria","pepe","juan","roberto"]
this_is_a_list = list()
this_is_a_list = []
Lists are created in the same way as a variable, but here you can choose for giving the variable a value of a list function or the value of an empty list.
print (friends[2])
juan
As you can see "juan" is the third element on the list but i wrote 2. That happens because Python takes the first element as a 0, the second as a 1 and go on. If i want to take the fifth element on the list i have to write 4 because we are also counting the 0. If you want to add elements to the list you can use .append, it push the list one slot more and then add the value you want. For example if i want to add a new friend in my friends list:
friends.append("jose")
print (friends)
[maria,pepe,juan,roberto,jose]
Notice that i write .append right next to the list name and the put the value i want to add inside parenthesis.
There is also a way to count the number of elements inside a list. Is a function called len from lenght and is very easy to use. The function returns the number of elements and you can use it to do calculations. Let´s see how many friends i have:
print (len(friends))
5
You could also assign that value to a variable and use it later on.
There are a lot of more uses for a list but im not going to get to deep into it. This are the most common and useful but if you want to learn some more be sure to read the course book.
for i in friends:
print (i,"is my friend")
maria is my friend
pepe is my friend
juan is my friend
roberto is my friend
jose is my friend
The "i" in the for loop works exactly as a function, it takes a value from somewhere and sustitute that value inside the block. The condition is to take all the values of the list friends. The "i" is going to take the value from the first element and then sustitute that value inside the print function, when it ends it will move to the next value until the list is over.
Another way to use the for loop is to use a range. Instead of using a list as a condition we can tell "i" to take the value from a range of numbers. This is an example of a for loop with a range:
for i in range (1,3):
print (i)
1
2
The loop printed only 1 and 2 but not 3 because the range is exclusive, this means that does not include the last number. It takes all the values from 1 to 3 without incluiding the 3, its like saying 1<=i>3 ("i" is greater or equal than 1 and less than 3 but not 3). Always add 1 to your real range because the loop is not going to take the last value, this is very important to undertand because by knowing you could avoid a lot of mistakes and hours of trying to fix a program.
You should also know that the "i" can be replaced by any other letter you want as you include it inside the loop.
There are some more iterators but these are the most common and useful for us. If you want to know more about this, you should read the course book.
friends = ["maria","pepe","juan","roberto"]
creating lists
There are two ways of creting a list:this_is_a_list = list()
this_is_a_list = []
Lists are created in the same way as a variable, but here you can choose for giving the variable a value of a list function or the value of an empty list.
using lists
If you want to take just one value of the list you have to use the variable with the position you want to take the value from. Let´s take the list of friends as an example, if i want to print "juan" i have to write this:print (friends[2])
juan
As you can see "juan" is the third element on the list but i wrote 2. That happens because Python takes the first element as a 0, the second as a 1 and go on. If i want to take the fifth element on the list i have to write 4 because we are also counting the 0. If you want to add elements to the list you can use .append, it push the list one slot more and then add the value you want. For example if i want to add a new friend in my friends list:
friends.append("jose")
print (friends)
[maria,pepe,juan,roberto,jose]
Notice that i write .append right next to the list name and the put the value i want to add inside parenthesis.
There is also a way to count the number of elements inside a list. Is a function called len from lenght and is very easy to use. The function returns the number of elements and you can use it to do calculations. Let´s see how many friends i have:
print (len(friends))
5
You could also assign that value to a variable and use it later on.
There are a lot of more uses for a list but im not going to get to deep into it. This are the most common and useful but if you want to learn some more be sure to read the course book.
for loop
The for loop is a packed version of a while loop. The difference between a for loop and a while loop is that the for loop works with an iterator (a counter that works automatically), it works with lists and ranges (and more), and also the condition does not returns a boolean value . This is an example of the for loop:for i in friends:
print (i,"is my friend")
maria is my friend
pepe is my friend
juan is my friend
roberto is my friend
jose is my friend
The "i" in the for loop works exactly as a function, it takes a value from somewhere and sustitute that value inside the block. The condition is to take all the values of the list friends. The "i" is going to take the value from the first element and then sustitute that value inside the print function, when it ends it will move to the next value until the list is over.
Another way to use the for loop is to use a range. Instead of using a list as a condition we can tell "i" to take the value from a range of numbers. This is an example of a for loop with a range:
for i in range (1,3):
print (i)
1
2
The loop printed only 1 and 2 but not 3 because the range is exclusive, this means that does not include the last number. It takes all the values from 1 to 3 without incluiding the 3, its like saying 1<=i>3 ("i" is greater or equal than 1 and less than 3 but not 3). Always add 1 to your real range because the loop is not going to take the last value, this is very important to undertand because by knowing you could avoid a lot of mistakes and hours of trying to fix a program.
You should also know that the "i" can be replaced by any other letter you want as you include it inside the loop.
There are some more iterators but these are the most common and useful for us. If you want to know more about this, you should read the course book.
Masteries 11 and 12 - Calling and creating functions
Functions in Python are very easy to use, they do specific actions with the value you call them. The function substitute a value into a block of code and the returns the calculation (or sometimes they do nothing). For example, you have probably used before the print function:
Print(“Hello
world”)
This funtion is a built-in-function that takes an integer or a string (or a combination of them) and prints them for the user. There are a lot of built-in-funtions but we are not going to ge into all of them, the way to recognize a function is to see a word and then a value(or values) between parenthesis.
Name_function(value)
Name_function(value,value1,value2)
Calling a function
In order to work all functions need to be called. You can just write the name of the function with some values inside but that is just going to calculate whatever the function do without responding to the user. If you want to show the calculation to the user you can include the function in a print function or asign the value of the calculation to a variable:
superpower(2,3) #Gives you the value of x raised to the y
nothing happens
print (superpower(2,3))
8
value = superpower(2,3)
print (value)
8
Keep in mind that if you want that the function takes a value and return it (adquire the value) you need to put the word return inside the function. If you dont do this the function will do nothing and you wont b able to use it for more calculations.
Creating a function
Now that you know how to call a function you can create one. The stepts are really simple. Fisrt lets see the body of a function:
def function_sum(x,y,z):
return x+y+z
As you can see to create a function we need to tell Python that we want to make one so we write def, this way Python will know that you are creating a function and not calling it. The next step is to write the name, you can use whatever name you want but keep in mind that if you are in a big project you are going to use a lot of functions so use names easy to remember. I recommend you to name the function with something related to it like:
def root_square(x) #It calculates the root square of a number
def pyramid(x) #It prints a pyramid made of strings
def fibonacci(x) #It prints the value of n in the fibonacci sequence
The next ting to do is to write the parameters that you want the function to take, it can be anything as long as you use them inside the function. It works as a variable but they are not a variable, it just sustitute the values inside the function. Look at the first example and you can see that I used 3 parameters (x, y and z) and later on I used them inside the function to retunr the value of a sum of the 3 parameters. Lets see some examples of the function working:
print (function_sum(1,2,3))
6
print (function_sum(10,4,16))
30
Remember to use the return so that we can use it as the value of the calculation
function_sum(1,2,3) + 10 #6 + 10
nothing
Remember that we need to print it or asing it to a value. Otherwise the calculation will be useless.
print (funtion_sum(1,2,3) + 10)
16
Notes
-While creating the function remeber to use the : at the end and then put the code inside the function with identation
-Remember that most of the time the function needs the return
-You can use as many parameters as you want
-While calling the function remember to give the value some use, print it or asign it to a variable
Suscribirse a:
Entradas (Atom)
