YOUR ARGUMENT IS INVALID, isn’t it?

--Originally published at Coding The Future

via GIPHY

If you had been in my house while I was watching the US Presidential Debates you would probably had heard me scream to my computer "YOUR ARGUMENT IS INVALID DONALD!". Not only do I hate that guy for being so racist, but also because everything he says is just so dumb. And then my girl Hillary comes in saying that you can fact-check Donald from her website in real time. Gotta love that QUEEN!

But aside from US politics, let's move on to today's topic: validating user input. This will not exactly help us to fact-check Donald, but to make sure that the user is entering the right kind of information.

Let's take a registration form for example. We want to collect the user's name, email, and phone number. Therefore, we must make sure that the user includes an @ and a .something and that only numbers are inputted in the phone number field. Here's how it works...

Using the "Try" Approach

To validate input, we could use if-statements, but there's a more effective approach commonly known as Try-catch. This method tries to do something, and if it can't, instead of crashing the program, makes it do something else.

Take a look at the following sample code:

try: phoneNum = int(input("Please enter your phone #: ")) except ValueError: print("Sorry, that phone number is not valid.")

As you can see, the first step was to type try followed by the code you need to validate, which in this case is making sure the input only whole numbers, and then using an except statement to break out of if an error was returned. This prevents the program from crashing, and if combined with a while loop, can prompt the user to enter their number again until they get Continue reading "YOUR ARGUMENT IS INVALID, isn’t it?"

Else and Elif

--Originally published at Py(t)hon

Continuing with the course, we have the next step that is the else and elif statement. Let’s start with else, in the else statement is where you are going to put the block of code that you want to execute if the conditional in the if statement turns out to be False or 0.

Here is an example:

else-1

On the other hand, we have the elif expression, that allows you to check for multiples condition for True and as soon as one of then turns out to be True, run.

Here is an example:

elif-1

Here is a video, for the people than didn’t understand me:

#Tec#Python#Else#Elif#ISC#TC101#Pug


Si sí entonces:

--Originally published at Eduardo's Projectz

En pyhton, como en muchos otros lenguajes de programación, existe algo llamado “condiciones”. Lo que hacen estas “condiciones” es evaluar una declaración y decidir si esta es verdadera o falsa y ejecutar un comando diferente según el resultado.

En esta ocasión vamos a ver la condicional “if”, esta significa, literalmente, si.

python_if_statement

El “if” evalúa si algo es correcto, en caso de que sí sea correcto se ejecutará un algoritmo, y si lo evaluado es incorrecto continuará el programa sin correr el algoritmo que está adentro del “if”.

captura-de-pantalla-de-2016-09-14-22-37-48

En este caso si la variable edad es menor que 18 se mostrará en pantalla “¡Sal de aquí niño!”, pero si la variable edad es igual o mayor que 18 no pasará nada.

Para crear una condición del tipo “if” se tiene que escribir if seguido de la condición y por último dos puntos (“:”).

if condicion:

 

Existen complementos a la condicional “if” llamados “else” y “elif”, estos significan lo demás  y lo demás que sea, respectivamente.

La primera permite ejecutar una acción solamente si la condición establecida por el “if” es falsa.

captura-de-pantalla-de-2016-09-14-22-47-27

En este caso se establece que si la edad no es menor a 18 se mostrará en pantalla la frase “Bienvenido”.

Para utilizar la condición “else” simplemente debes escribir else seguido de dos puntos (“:”). La condición “else” debe de estar con los mismos espacios a la izquierda que la condición “if”.

else:

 

La condición “elif” hace que se ejecute un algoritmo siempre y cuando la condición del “if” (y de los “elifs” antes de este) sea falsa, pero una condición designada sea verdadera.

captura-de-pantalla-de-2016-09-14-22-56-51

En el código anterior podemos ver que si la edad dada no es menor a 18 pero sí es mayor a 50 se correría la linea 5 que imprimiría “Pase usted señor”)

59943535
Continue reading "Si sí entonces:"

FOR ALL THOSE PROCRASTINATORS

--Originally published at Coding The Future

If you are reading this right now, you were probably procrastinating, and just started studying for tomorrow's test, right?

Well, as always, I've got you covered. Here's a quick video summary of what you need to know for the first partial. I hope things are not too strange.

Good luck!

I WILL LOVE YOU WHILE [condition]:

--Originally published at Coding The Future

Image via GIPHY

I know. I've gotta stop with the song references. But today's topic reminds me of Whitney Houston's "Love You". That song is so beautiful, so inspiring, but it's all FALSE! Well, kind of... Why? Because nothing lasts forever. Well, maybe true love does. But in code, the chances you'll encounter a loop that never ends are super rare.

Today we'll be talking about while loops, which helps us run a piece of code while a certain condition is met.

For example, let's say we wanted to print a countdown. Instead of writing a single line for each number, we would just go to while loops!

While loops are super simple in Python. Begin with the keyword while and then write the condition –without brackets! The following lines, which are obviously indented, is where you put the code that'll loop. Take a look:

count = 0
while (count > 0): print ('The count is:' + count) count = count - 1

As you can see, the loop will run while count is grater than 0, and will stop running once count reaches 0. The count is decreased by 1

For your condition, you can use counters like the example above, or you could use a boolean value by nesting if-statements inside of your while loop. You've gotta be careful though, because as I said, you could get stuck into an infinite loop, which could break your program.

That's pretty much it for today. Until next time!
@emamex98

WHAT IF? Exploring If-statements

--Originally published at Coding The Future

Photo by Matthew Smiths

Many times in life we are faced with crossroads and have to make a decision. In coding, things work similarly. Sometimes, actions that the program triggers depend on what the user chooses or inputs. This is where if-statements come in handy.

An if-statement triggers different actions depending on a certain condition. By using if-statements, you can tell a computer to do this if a certain condition is met, and do something else if it isn't.

In Python 3, declaring an if-statement is quite simple. All you have to do is to type the keyword if followed by a condition, and close with a colon. Here's a quick example:

if logWeight > 23: print("Your suitcase exeeds the maximum weight allowed.")

As you can see, in the first line, I start by declaring an if, and then I state the condition, and close with a colon. The following indented lines specify the code that will be triggered if the condition is met. In natural language, it reads "if the suitcase's weight is greater than 23kg, print a warning message".

Let's say, however, you wanted to trigger a different action if the condition wasn't met. For example, if the suitcase's weight was less than 23kg. Then all you need to do is add an else to your statement. Take a look:

if logWeight > 23: print("Your suitcase exeeds the maximum weight allowed.")
else: print("Thank you for your business.")

As you can see, all I did was to add new line (non-indented though) with the keyword else, and told the program that if the weight was anything but greater than 23, then print a message thanking the the customer.

But let's say, you wanted to get really specific, and have different actions for different conditions. Instead

Continue reading "WHAT IF? Exploring If-statements"

IF you are awesome read this, ELSE go away.

--Originally published at Hackerman's house

I created an awesome program that uses the function IF and the function ELSE. It can be used to determine if one input is bigger than other. These inputs are related to the cost of a product, and the money a person can expend.

giphy (3)

There are 2 ways of using the functions if and else. In separate lines, and in the same line. Both ways are used in my program, each one show one sentence as an answer to the user.

If, else

Here is how the program works if the user has more money than the cost of the product.

IF yes

Here is how the program looks if the user doesn’t have enough money to buy the product.

IF no

I learn about this function using the Basic Python 3 course at Lynda.com

Thank you for reading me.

giphy (4)