Validating User Input in Python

--Originally published at Ed_Alita

 

User do not know how to use a computer

This mentally you need to have in order to have a great code.

Lets see if I have the next code:

validating

If the user gave you for any reason a letter because he or she is stupid the code will crash:

validating-2gif

In order to prevent this we are going to validate what the user gave us is corect in this case first we are going to obtain the input without any type we do this by puting raw_input.

the next thing is to do the text if it is a number with int(User_Input). since we know that if this obtain a number it will crash we are going to do a cheat to stop this.

We use Try and except:

What try does it proves the code and Except will do an action if the codecrash.

The complete code will look like this:

validating3

In this case if the user gave us a string it should make this:

validating4

If the user gave us a integer it should run smothly:

validating5

Go and Have fun as a Code Master


Use of Range in Pytho

--Originally published at Ed_Alita

Don’t be scared by the word there are easy as pie

Let’s see that you want to print all number between 1 and 5; therefore you need a range. But let me tall you a little secret in range it only takes until the number you tell it but do not  take the actual number in consideration. Let’s see an example:

range1 In this the 5 willnot be printed.

The actual result of this code is the next one:

range2

Now lets see a more complex range with two variables:

range3

in this case the result will be:

range4

If you want to see more info in the next link:

http://pythoncentral.io/pythons-range-function-explained/


Reading and writing of text files

--Originally published at Ed_Alita

 

Computers do even read and write?

YES, they do.

Calm down it is not wichcraft.

Lets see how to do it.

Firts we need to create a .txt file and we do this by typing file = open(“file name”, “action”)

The actions that you can do are the next ones:

  • “w” this is use to write in a .txt file
  • “r” this is use to read
  • “a” open the file for apending

The action that we are going to do is to write so we put file.wite(“Hello”)

The code should look like this.

write1

Now in other to see this we need to open it again and put print(file.read())

read1

The result of the code is the next one:

write


Use of recursion for repetitive algorithms in Python

--Originally published at Ed_Alita

The term recurssion is simple it means the use of a repetive funtion inside the funtion. Let’s see if we want to do the factorial funtion we are going to encounter to case the case of factorial 0 and the other cases. Having this in mind we have to make these two in code.

Therefore the code is the next one:

recrussion1

The result is the next one:

recrussion2

This is easy only having in mind that we are having ti use the same funtion between the repetitive one.

You can check these link for more information.

http://stackoverflow.com/questions/479343/how-can-i-build-a-recursive-function-in-python


(“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

 


While vs For in Python

--Originally published at Ed_Alita

The backgroud

This two funtions are used to create loop that inside is a code that you wish to repeat it self. The question is if they are the same how to choose between them. I will explain each one and then teach you how to choose between them.

For

This funtion repeats itself only the times that you indicate or until it condition is not longer true.

Lets see this example:

for1

This code for each letter in the word Python will run the code.

Let’s see what it does.

forex1

While

This funtion repeats itself until it make false it’s value.

This is the logic that While follows:

while1

The next Example will make it clear:

while2

This program will run each time until count be 9. Lets see what it does:

whileex1

Which one I use?

The use of each one depends on what you need. Lets see if you know how many times the user will put the correct answer use for but if you don’t know how many times you can use a infinite while.

The material use can be seen here:

https://docs.python.org/3/reference/compound_stmts.html#while

 


Nesting Condicionals in Python

--Originally published at Ed_Alita

Did you mean this?

No!!!

Nesting is puting a lot of conditional in order to make a more complex decison. For example the joysticks of a Xbox 360 have this kind of thinking.
Lets see a example of a code to see it clear:
nested1
The nested of this conditional take the input and comparte it with a range of cases.
This kind of of coding make us a easy liofe because it make the code to has flow and make it simple to see it.
The Result of this code is the next one:
nestedex1

Nesting of conditional statements

--Originally published at Py(t)hon

You may think there is no more you must know of the conditional statement, well… You are wrong, there is another knowledge call nesting that must master. Perhaps you didn’t know that in a nested if construct, you can have an if…elif…else construct inside another if…elif…else construct.

There may be a situation when you want to check for another condition after a condition resolves to true, this is what is call nesting, a conditional inside another conditional.

Here is an example:

nesting-1

Here is a youtube video:

That’s all #Pug #Nesting #If #Python #ISC #Tec #TC101

 


If, else and elif Python

--Originally published at Ed_Alita

The core of a program is if and else because thaey give the flow to a program therefore in order to make a program you net to know how do if and else work.

 

ifex3

 

 

@SummerBreak chill flow summerbreak summer break

 

 

 

 

To put in python this is the rules to put it:

if

It has three parts the comparator and then the action this is a if context.

To do a else if comparation is the next one.

if2

The last part is the else if the compartor does not apply it goes directly to the else.

If the condition is true:

ifex1

if the cpondition is false:

Now you are a step futher in becoming a code master.

Elif

This operator is use to compare a variable to a lot of expressin if any of them is true you go to a default expression.

Put the next cod eto invoque the elif:

elif

the result is the next one:

elifex

 

The material seen here is in:

https://www.tutorialspoint.com/python/python_if_else.htm