(“Tuplas”, “TC”, 101)

--Originally published at Eduardo's Projectz

En la programación, así como en la vida real, es muy probable que se describa un objeto como un agrupamiento de datos distintos. Esto son las “Tuplas”.

Para declarar una tupla es tan simple como asignar a una variable valores encerrados en paréntesis.

a = (1, “a”, 2.5)

Un ejemplo de esto puede ser una fecha, en donde se necesitan tres elementos; día, mes y año.

Por lo que podemos decir:

captura-de-pantalla-de-2016-10-28-19-26-18

Al igual que en las listas, los datos en las tuplas tienen asignados un orden, por lo que en este caso el día de cumpleaños (2) está asignado a la posición 0; el mes (“septiembre”), a la posición 1 y el año (1998) a la posición 2.

A diferencia de las listas, las tuplas no pueden ser modificadas.

También es posible asignar muchos valores a una variable separados por comas y esto crearía una tupla.

captura-de-pantalla-de-2016-10-28-19-32-05

Para más información en este tema visita: https://www.tutorialspoint.com/python/python_tuples.htm

Para un video explicativo sobre el tema: https://youtu.be/R8mOaSIHT8U

 

 


Métodos para listas

--Originally published at Eduardo's Projectz

Dentro de las listas existen varios métodos y funciones que se utilizan para obtener un mayor beneficio de estas.

Las principales funciones son:

len()

Se utiliza para conocer la longitud total de una lista.

Para utilizarse, simplemente se escribe “len” y entre paréntesis el nombre de la lista que deseas.

captura-de-pantalla-de-2016-10-28-18-36-45captura-de-pantalla-de-2016-10-28-18-36-57

Nótese que esto te da la longitud, no la última posición que sería, en este caso, el 2.

append()

Se utiliza para añadir un valor al final de una lista, este valor tiene que ser del mismo tipo de dato que la lista.

Para utilizarse, escribe el nombre de la lista seguido por “.append” y, entre paréntesis, el valor que deseas añadir.

captura-de-pantalla-de-2016-10-28-18-38-24

captura-de-pantalla-de-2016-10-28-18-38-41

insert()

Este método permite añadir un valor a la lista en una poción determinada.

Para utilizarse, escribe el nombre de la lista seguido por “.insert” y, entre paréntesis, la posición en donde deseas poner un valor seguido de el valor, separados por una coma.

captura-de-pantalla-de-2016-10-28-18-39-41

captura-de-pantalla-de-2016-10-28-18-39-50

remove()

Esto se utiliza para quitar un valor existente en una lista.

Para utilizarse, se escribe el nombre de la lista seguido por “.remove” y el valor que se desea remover entre paréntesis.

captura-de-pantalla-de-2016-10-28-18-40-40

captura-de-pantalla-de-2016-10-28-18-40-49

index()

Esto se utiliza para conocer en que posición se encuentra un determinado valor.

Para utilizarse, se escribe el nombre de la lista seguido por “.index” y el valor que se desea conocer entre paréntesis.

captura-de-pantalla-de-2016-10-28-18-42-03

captura-de-pantalla-de-2016-10-28-18-42-13

 

images

Para más información en el tema, visita: https://docs.python.org/2/tutorial/datastructures.html

O si prefieres un video: https://youtu.be/zEyEC34MY1A

 


Recursion

--Originally published at Python

Recursion is when you call a function inside of itself. It can be used in several ways, for example, you could create a function that will give you a final result after repeating itself several times, or it could give you several answers, depending on how many times it went through itself. The most common and probably the easiest example to understand on this subject is when writing a program that gives you the factorial of a number.

Code:

num = int(input(“Type a number: “))

def Factorial(num):
if num<=1:
return 1

else:
return num*Factorial(num-1)

print(Factorial(num))

2recursion

If the number is 1 or 0, the function won’t call itself, it will just return 1. If the number is bigger, then the recursion begins. Every time it goes through the else, it multiplies n by the answer to factorial n-1. This answer will depend on the number you get in the new factorial, and it will keep on decreasing until you get to 1, which is when all the previous numbers will start multiplying. These answer will stack up until the program gets to the first time the function was called, and it will return the final answer. It might be confusing at times, but ultimately, it follows this idea.


Validated user input

--Originally published at Python

When writing a user influenced program you need to ensure that the user does what he is expected to. Usually you want the user to type a certain type of variable, and there’s times when the user will type in something else. You need to validate the user input, otherwise, the program will crash and it won’t work. The simplest way I could find to do this is by using a While Loop using “try” and “except”. Here’s some code that you can use as a guide.

Code:

while True:
try:
age = int(input(“Please enter your age in years: “))

except ValueError:
print(“Only numbers please”)

else:
break

print(“Thanks for the info”)

2validating

The program enters a while loop and asks for an input. When the input is given, the program will check for exceptions, the exception here being when there’s a value error. This means that when someone inputs something that isn’t an integer, the program will enter the exception part which tells the user to type numbers only. Then it will continue looping until an integer is given. Once it is, the program will move on to the else, in case no exception was made. This else has a break which will end the loop, and after that, the processes outside the loop are done, and the program ends.


Importing and using modules/libraries

--Originally published at Python

Importing helps you use libraries or modules already available in Python 3. This means you don’t have to create functions from scratch, instead you can use the ones that already exist to save time and effort. There are a lot of libraries you can import, each has specific functions, in this blog, I will only focus in the import Math.

Code:

import math

print(math.fabs(-8))
print(math.ceil(1.1))
print(math.factorial(4))

2import

As you can see, the first thing you need to do is import the module/library, then you have to call it with a variable. For example, I used “math.fabs” which returns the absolute value of a number. So as a variable I used -8 and the program returned 8. There are 2 more examples below, but there are way more libraries you could use. If you want to learn more about them, check this link. It has all the functions you can use, as well as other modules/libraries.


Nesting Conditional Statements

--Originally published at Python

Nesting conditional statements refers to the process of writing a conditional statement inside of another. For example, if we were to use “if” we could write another “if” inside of it but with a more specific condition. It’s like having several filters in order to see which condition is true. And depending on that condition, a specific process will be done. Here’s an example:

Code:

num = int(input(“Type a number: “))

if num<=0:
if num<=-10:
if num<-100:
print(“Your number is smaller than -100”)
else:
print(“Your number is between -10 and -100”)
else:
print(“Your number is between 0 and -10”)
else:
print(“Your number is bigger than 0”)

2nesting

 


Basic Types

--Originally published at Python

Basic types in Python 3 refers to most common variables that are used to program. These are known as numbers, string (words), List (group of variables), Tuple (similar), and Dictionary (again, very similar to the lists). Here’s a picture showing every basic type in use:

Code:

num = int(5)
print(“Number: “, num)

word = str(‘Hello’)
print(“String: “, word)

list1 = [‘Dog’, ‘Cat’, 9, 15]
print(“List: “, list1)

tuple1 = (‘Cat’, ‘Dog’, 15, 9)
print(“Tuple: “, tuple1)

dict = {‘Animal’ : ‘Dog’, ‘Age’ : 5, ‘Breed’ : ‘Pug’, ‘Name’ : ‘Bono’}
print(“dict[Animal]: ” , dict[‘Animal’])
print(“dic[Name]: ” , dict[‘Name’])

2basic

It may be hard to understand the difference between List, Tuple, and Dictionary by just looking at the program. List stores different types of variables that can be modified later on. Tuple does the same but can’t be changed. Finally, the variables in a Dictionary are accessed through keywords, not the position of the variable itself. Well that’s pretty much it for the basic types, hope you understood.


Zen of Python

--Originally published at Python

2zen

I’ve been looking more into the Zen of Python and what it actually says. First I disregarded it because I knew most of the things it talks about, but the I thought “What about people who are just starting?” Of course they won’t know how to guide themselves through the world of programming. So I decided to talk about the points that I believe are the most important in the Zen of Python.

The first one being “simple is better than complex”. It is important to understand this point because there are times when people try to do a super complex programs when in reality, it can be simplified into something everyone can understand. Making something complex will only bring you trouble in the future. If something goes wrong, then you will have to go through your complex program, understand the problem, why it is there, and then come up with a solution. Keeping things simple makes your life way easier.

Next is “Readability counts”. It is important that your code is readable. This point is similar to the last one, but a little more general. You want your code to be readable so that you can understand it, as well as others. If it is hard to understand, then you won’t be able to figure out your problem as easy as you could if it was. Also, if you ever show this code to others, they will be just as confused as you because they won’t understand anything.

Finally, I just want to talk about the point stating “Now is better than never.” Everyone that is starting to program has to take this one into account. Leaving everything for later won’t help you at all. If you want to be good at programming, you need to start

Continue reading "Zen of Python"

Strings

--Originally published at Python

Creating and using strings is simple. You just need to define a variable  using an apostrophe. Ex: string1 = ‘Hello’

After this, you can play around with the string. You can update it, print all of it, print only some parts, etc. Here are some examples:

Code:

str1 = ‘I like dogs’

print(str1)
print(str1[0])
print(str1[7:10])

2strings

As you can see, it’s easy, you just need to understand the positioning and how everything inside of it is arranged.