EASY AS 1,2,3?

--Originally published at Coding The Future

Image by Austris Augustus

Greetings everyone! And welcome to my last mastery article. To be honest, I thought I was done, but I just noticed I was missing an important concept in Python: ranges.

Ranges in Python are quite peculiar, because they work a little differently from other languages and also a little differently from what we're used to in Math class. Let's get right into it.

Declaring Ranges

Ranges can be used when we need to work with a set number of elements, like running a loop for a determined range.

To declare a range, we simply call the range( ) function, like in the following example:

range(7)

In this example, where only one number is included, Python asumes that your range will begin at zero, and end in 7. This range has seven elements, and it starts at zero. So if I printed a counter for the range, it would return 0,1,2,3,4,5,6.

However, things get a little tricky when we add a second number to the function, like this:

range(1,7)

In this example, I am working with a range from 1 to 7, but in Python this means from 1 to 6. The first number indicates where the range starts, but the second number represents the number after the last number in the range. So once again, if I were to print a counter, I would get 1,2,3,4,5,6. See? The seven is not included, and even though there is mathematically seven numbers between 1 and 7, the range only has six.

Using Ranges

We can use ranges for a variety of things, but the most common use is for loops. Here's an example of a for loop that prints Hello #n 5 times:

for n in range(1,6): print("Hello #" + n)

If we run this loop, it would Continue reading "EASY AS 1,2,3?"

Validation

--Originally published at Hector Martinez Alcantara

A validation is when you request an specific type of value from the user, so, you have to force the user to type what you want.

Let’s do an example:

var=input("Type a number\n")
while str.isnumeric(var)== 0:
 var=input("That's not a number, please type a number\n")
print("%s is the number you typed"%(var))

First, you require a string from the user, if the string is not a number, the program will request the number again.

That’s the main idea of a validation, depends on you how many conditions you want in your validation.


Loops, loops, loops …

--Originally published at Py(t)hon

Is time for us to learn about loops, the loops help us to repeat a piece of code several times instead of writing the code all over again. There are two kinds a while loop and a for loop, the while loop  tests the condition before executing the loop body, while a given condition is TRUE, it will repeat a statement or a group of statements. On the other hand, we have the for loop that executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.

Here is an example of for loop:

loop-1

and for while loop:loop-2

That will be all here is a video for better understanding:

#Pug#TC101#Tec#ISC#Loops#While#For

 


TEACH ME HOW TO BOT – Building a simple Twitter Bot

--Originally published at Coding The Future

Greetings everyone! I am back, and although this is long overdue, it's finally here!

Today I am releasing my tutorial on how to build a simple Twitter Bot. I have been working on a bot called Manny's Fortune Ball, a simple bot that replies with future predictions every time you ask it a question. You can go check it out by visiting its Twitter profile, and asking him a question. Its handle is @askemanuel.

Above I have attached a interactive slideshow. To move on to the next slide, just click on it, or tap the arrows.

Finally, this is the link to the GitHub repository so that you can check my source code: https://github.com/emamex98/TwitterFortuneBall

I hope you enjoy the tutorial! If you have any questions, do not hesitate to contact me:
Twitter: @emamex98
Email: em (at) nuel.xyz

comments powered by Disqus

“For” loops

--Originally published at Luis Santana's Blog

What’s up lads! It’s been a while since my last post but that will change during this day, because I’ll do in a single day all the posts I didn’t finish in this partial hehe so brace yourselves.

 

635656667301311336741304865_resized_winter-is-coming-meme-generator-brace-yourselves-finals-are-coming-45e03b
Here’s the link

 

So, this post is dedicated to “for” loops, this loop is an iterator based for loop. It steps through the items of lists, tuples, strings, the keys of dictionaries and other iterables. The Python for loop starts with the keyword “for” followed by an arbitrary variable name, which will hold the values of the following sequence object, which is stepped through.

Here’s an example of “for” loops:

for

In this example the “for” loops work fine because you know exactly the amount of teams you have and won’t repeat infinitely.

You can check this link with examples, it helped me a lot


Recursion

--Originally published at Hector Martinez Alcantara

Let’s talk about recursion. Personally, recursion is the  most dificult thing in programming, but I’ll try to explain it by the most common recursive function, the factorial.

Let’s see the example code:

def factorial(var):
    if var>1:
       var=var*factorial(var-1)
       return var
    else:
       return 1
 
x=int(input("Type a number to calculate the factorial:\n"))
print("The factorial of "+str(x)+" is:")
print(factorial(x))

The result of this is:

Type a number to calculate the factorial:
5
The factorial of 5 is:
120

But why?

Let’s see step by step, what happens.

First of all, we call the function with one parameter.

factorial(5) #factorial of 5

The number 5 enters to the function then if the number is 1 it returns 1, and then, the interesting part, if there’s some number higher than 1 the next function will be realized

var=var* factorial(var-1)

What happen here? Let’s see step by step.

First the value is 5, it’s greater than 1, so the function will be

var= 5 * factorial(var-1)

Now we can see that the value of factorial var-1 will be the same function, so we can see that the value of var in the function will be 4 that part will be like this:

var= 5 * (4*factorial((var-1)-1)

As you can see the value of the function factorial is the same function nested in the other sentence, so I’m goin to show you how the function looks doing the same procedure.

var=5 * ( 4 * ( 3 * ( 2 * (factorial ((((var-1)-1)-1)-1) ) ) ) )
#Remember the var==5
#((((var-1)-1)-1)-1) is like ((((5-1)-1)-1)-1) == 1

So…

var=5 * ( 4 * ( 3 * ( 2 * (factorial(1) ) ) )

What happens with factorial of 1? Remember that we typed that if the variable of the function is 1 or less, then the function will return

Continue reading "Recursion"

While loop

--Originally published at Hector Martinez Alcantara

This post is about the other loop, the while loop, it’s often used to do an action until a variable changes it’s value.

Here’s the sintaxis of the while loop

while condition:
      statements

And here’s an example of this:

#Introducing 5 lines of text
list=[]
x=1
while x<6:
      list.append(input("type some words"))
      x=x+1
print(list)

An example of while used as a returning menu:

op=""
while op!= "c":
      print("a)Print Hello")
      print("b)Print something")
      print("c)Exit")
      op=input("Select an option\n")
      op=op.lower()
      if(op=="a"):
           print("Hello")
      elif(op=="b"):
           print("Something")
      elif(op=="c"):
           print("Goodbye")
      else:
           print("Thats not a letter of the menu")

The result is

a)Print Hello
b)Print something
c)Exit
Select an option
>>a
Hello
a)Print Hello
b)Print something
c)Exit
Select an option
>>b
Something
a)Print Hello
b)Print something
c)Exit
Select an option
>>z
Thats not a letter of the menu
a)Print Hello
b)Print something
c)Exit
Select an option
>>c
Goodbye

Thanks for reading, ask me in comments.

Special thanks to Python while loop from Tutorialspoint


For loop

--Originally published at Hector Martinez Alcantara

Hi, I’m writing this post about the control flow tool called for loop. It’s used to repeat an action many times, but not only that, you can make a loop with specific conditions, and use it as a ‘foreach’ in C.

Another tool that we’re going to use is the range funtion that returns a list of a range of numbers.

I’m going to explain how the different uses of this for loop works.

First the sintaxis of the range tool:

range('initial number','last number range','conditional number')

Examples of use of range function:

#It can be used only as a quantity of numbers
range(5)
#The result is a list of numbers between 0 and 5 = [0,1,2,3,4]

#Used as a range of numbers
range(4,14)
#The result is a list of the range of numbers between 4 and 14 = [4,5,6,7,8,9,10,11,12,13]

#Used as a range of numbers with a jump condition
range(0,100,10)
#The result is a list of the range between 0 and 100 every 10 numbers = [0,10,20,30,40,50,60,70,80,90]

Now the sintaxis of the for tool:

for 'variable' in 'list' :
     #conditions

Examples of for loop function:

#Doing a quantity of actions
for number in range(8):
    print("Hello")
#The result is a print of the word 'Hello' 8 times

#Using a range of numbers
for number in range(10,20):
    print(number)
#The result is a print of numbers from 10 to 19

#Using a range of numbers with a special jump condition
for number in range(0,10,2):
    print(number)
#The result is the pair numbers from 0 to 8

#Using a variable
word="Hello"
for letter in word:
    print(letter)
#The result is a print of every letter in the word 'Hello' = ['H','e','l','l','o']

The explanation is that the for function takes every component in a list of components and use the component as the variable, for each component, the actions

Continue reading "For loop"

FORever ALONE

--Originally published at Coding The Future

Image via GIPHY

Today, I will share the very sad story of my relationship life: I am, and forever will be a forever alone. But that's ok. To be honest, I don't mind the single life. Love's just complicated for me.

But anyways, you are probably wondering why am I telling you this, which is probably useless. Well it kind of is useless, but today's topic, For Loops, got me thinking.

So, let's dive into today's topic: For Loops. Remember while loops? Well for loops are not so difference. Only difference is that this time, we know exactly how many times the loop needs to run.

Here's an example: Let's say we wanted to ask a user to enter their password, and we need the user to enter it twice. Since we know that the loop will run exactly twice, the most appropriate way to accomplish this is a for loop. Let's take a look at the following program:

password = ["pass1","pass2"]
i=0;

for counter in range(0,2):
⠀⠀password[counter] = input("Please enter your password: ")
⠀⠀i= i+1

if (password[0] == password[1]):
⠀⠀print("Both passwords match")
else:
⠀⠀print("Passwords do not match")

As you can see, the first two lines simply declare a list and an integer. The following lines is where the magic happens. As you can see, I started with the keyword for, and declared a counter variable called counter, followed by the key words in range and the range from which the loop will run. As you can see, this range is in brackets, and it says (0,2). Check the footnote to know why this means it will run twice.1 I end off with a colon.

The code bellow just asks the user for input, stores it in a list, and at the end of the loop Continue reading "FORever ALONE"

Mientras tanto…

--Originally published at Eduardo&#039;s Projectz

La herramienta de “while” es una de las más importantes y utilizadas en la mayoría de los lenguajes de programación. Esta permite que se repita un ciclo mientras una condición sea verdadera, y salga de este en cuanto la condición sea falsa.

while-loop

Para establecer un “while” se necesita escribir la palabra while seguido de la condición que se deseé establecer y, al último, dos puntos.

captura-de-pantalla-de-2016-09-15-21-22-43

En este caso, el código establecido para este “while” se correrá siempre y cuando la variable “x” sea menor que 10.

El código designado para un “while” debe de estar abajo de este con cuatro espacios de diferencia respecto a la posición del “while”:

captura-de-pantalla-de-2016-09-15-21-27-09

En caso de que “x” sea menor que 10, se le añadirá 1 a el valor de “x”. Esto continuará sucediendo hasta que el valor de “x” ya no sea menor de 10. En caso de que el valor de “x” nunca fuese menor de 10, el código del “while” nunca se ejecutaría.

Aquí un ejemplo de un pequeño programa utilizando “while”:

captura-de-pantalla-de-2016-09-15-21-39-38

Este programa te dirá cuantas semanas faltan para que consigas el dinero suficiente para algo.

Aquí un ejemplo de como funciona:

captura-de-pantalla-de-2016-09-15-21-42-38

 

 

Para más información a cerca de “while” y otros bucles: https://geekytheory.com/bucles-en-python/ https://www.tutorialspoint.com/python/python_while_loop.htm https://docs.python.org/3/tutorial/controlflow.html http://www.mclibre.org/consultar/python/lecciones/python_while.html

Si te es más fácil seguir un video-tutorial: https://youtu.be/D0Nb2Fs3Q8c https://youtu.be/XkDOJC4hpw0

 

8573117_orig