There are two ways to create a range:
In case of ranges, all parameters must be integers, values can be positive or negative and the upper bound in both types is non-inclusive.
There were two types of ranges in python 2, range and x-range, now in python 3 we only have the range we all know and love.
It is also possible to create a random rage of numbers using the rand-range function, but since you have to import a module to use it you should just focus your attention in the first two.
In the python 3 range, ranges have their own data type, and before in python 2, ranges produced lists and x-ranges produced iterators minus a sequence.
]]>To ask the user for a value or “input”, you first have to assign a variable to that value, next you use the “input” command to tell the computer to read and save in the variable we just created whatever the user types on the keyboard. After the “input” command you have to actually ask the user for the information that you desire to obtain, for example: “How many fingers do you have?”, then the user should answer the question returning the information and the input will assign that value to the variable we created.
X = input (“How many fingers do you have?”), user writes “5”, then “X = 5”
Although it is easy to write and very practical in itself, the fact that it generates a human-machine interaction can bring us many problems. For instance, we take it as granted that everyone has five fingers in each hand, but someone can count the fingers of BOTH of their hands, or they can have an extra finger, or just screw with you and give you a random number like 196. All of this outcomes have an impact in the way your program works.
Let’s say that your program is: n = input (“Give me a number”), and while (n>0): print (“Nom”) n=n-1. For this program you expect “n” to be an integer, but if the user gives you a string like “Banana”, then your program will die since the value of n is not valid for that condition.
This is the reason why we VALIDATE the user input, so that even if we can’t control what the user types we can filter that information and retrieve what we desire or just ask the user for a different input again and again until he gets it right.
Following the previews example, in order to avoid the “Banana” error:
We can use an “if”:
n = input (“Give me a number”)
if (n = int(n)) and (n>0):
while (n>0):
print (“Nom”)
n = n – 1
else:
n = input (“Give me another number”)
With this we have two conditions that “guard” the while, if the value of “n” is an integer and it is greater than zero then we can proceed with the loop, any other values will be discarded and the user will be asked for a new one. Of course there are lots of ways to validate, this was just an example of what you could do in this specific situation.
]]>The difference in syntax between a list and a tuple is that to create a list you use “[ ]” and to create a tuple you use “( )”. Plus tuples are defined as “Heterogeneous data structures” and lists are defined as “Homogeneous sequences that have an order”
The use you most probably will use the tuple as reference data, since the values inside it cannot be modified; the list in the other hand can have the values inside it changed, move around, add new values and eliminate existing ones.
If you remember the mastery about “For” loops, in the example we used a list named “L” containing the values [1, 0, 1, 0, 0, 0, 1, 1, 0, 1, 5]. For that program we could use a tuple as well since the “for” only checks for the value within the list, but it doesn’t modify it.
There are a whole bunch of things you can do with lists and tuples, like splitting and indexing them, for a whole list of the things you can do and how to do them please visit this link: http://www.tutorialspoint.com/python/python_lists.htm
You should be very careful not to use lists instead tuples or the other way around since even if you ARE able to do some things with both without negative results, not all of their functions are the same, tuples are more oriented towards indexing and lists are fore managing data.
Lists and tuples have positions, or spaces, and they store the values they are given in those. Those positions start with 0, then 1, next 2 and so on till they cover the length they are needed. So if you need the value stored in the tenth position of a list, you would need to call for the ninth value, since the counter starts from zero instead of one.
Another important thing is that they can contain any amount of data, and they don’t care about dta types, you can just throw integers, floats and strings inside a list and it will be just fine, just be careful when trying to mess around with the information itself, the list doesn’t have a problem with it but other parts of your code may.
]]>The “while” loop will repeat itself as long as the condition that accompanies it remains true, this means that a “while” loop will tend to repeat itself to infinity unless we do something to make the condition that controls it become false.
On the contrary, the “for” loop will tend to run once for each value given, and since we tend to have a finite amount of values to work with the loop tends to be finite as well.
Knowing this difference will save you a lot of work if you learn to differentiate the problem you need to solve.
A very easy way to identify which form of loop to use is reading the contents of the rest of the programs. Most of the time, if we are using lists, ranges, tuples or dictionaries we will be required to use a “for” loop, since the problem at hand is to go through all of the contents of either of the previously stated types and perform an action according to its contents and their value.
As for “while” loops, they come in handy when the amount of cycles we will have to perform in order to solve the problem is unknown to us.
You can even use both at the same time, as I implied earlier, it all depends on your needs.
One example of this is the case of having a list with vive values inside of it, all integers. We need to calculate the factorial of each number. To go over all of the length of the list and check all of the values we need to use a “for” loop, but to actually calculate the factorial we would need a “while” using the value found by the “for” to do the math, then the “for” would move on to the next position and so on.
And just like with the “if, elif, else” business, be warry of indentation.
]]>The way you write a for is the following: “for i in x:”, after that you fill up its guts with what action you want it to perform.
The “in” part makes it so that the “for” gets along especially well with ranges, list, tuples and dictionaries. What it does is that it makes your program search for a special something in the insides of another something, for example a range or a list, and then do something to that something it found, or simply perform an action according to it.
We can convine this with other stuff, like ifs for example:
L [1, 0, 1, 0, 0, 0, 1, 1, 0, 1, 5]
For I in L:
If (I = 1):
Print (“yes”)
Elif (I = 0):
Print (“no”)
Else:
Print (“Get yourself together!”)
This program will check every value within the list “L”, and depending on its magnitude it will perform an action, printing “yes” if the value is one, “no” if the value is zero, or “Get yourself together!” if it finds another value.
Using for statements gets fun when you start working with calculations or “searches” with big amounts of data, it will save your butt a lot of pain.
The main difference between a “while” and a “for” is that the while will run definitively if given the chance, but the “for” fill always have a beginning and an end, since you work with finite things like lists and ranges. A “for” CAN be infinite, but only if the range you are using is infinite itself.
]]>There are different ways to make loops, but right now we will review the one called “While”.
The while loop basically takes a condition, and as long as this condition remains true the loop will continue, meaning that the instructions WITHIN the while will keep repeating themselves.
For instance if we write: while(i>0): print(“hit yourself ”), the condition for the while to happen is i>0, so each time the loop repeats itself their two values will be compared to see if the condition is true or false.
The piece written above has two ENOURMOUS mistakes, number one being that “i” has no assigned value, we can solve this by writing “i=1” before the while. The remaining problem is that, since there is nothing that makes the value of “i” change, it will always be one, meaning that it will always be bigger than zero and that the while will repeat itself endlessly, eating up your RAM and killing your computer, and that is a big no-no.
One very simple way to solve this matter is to write “i= i- 0.1” inside the while, this way the value for i will change every time the while repeats itself, in this case turning into a smaller number, eventually reaching the value of zero.
Now this is very important, once the condition the while has is no longer met, in this case i>0, the while will stop.
For the program we wrote i=1, and each run of the while we subtract 0.1, turning it into 0.9, 0.8, 0.7 and so on till we reach zero, this means that the while will repeat itself ten times, performing the action inside it ten times.
The outcome of our little program will be: “hit yourself hit yourself hit yourself hit yourself hit yourself hit yourself hit yourself hit yourself hit yourself hit yourself”
Of course this is just the basics, things will get scarier as we continue, but be patient and try to understand this as best as you can, since the while itself does not change, EVER, just the things outside it and inside it.
]]>This is an important tool, but you should be very careful when writing a nested condition, since this can get very confusing if you lack order with our thoughts and your programming style.
You have to be very careful with the indentation you use when writing the conditionals, or else the program will fail.
The following is an example of a nested conditional:
v = 100
if v < 200:
print “Expression value is less than 200”
if v == 150:
print “Which is 150”
elif v == 100:
print “Which is 100”
elif v == 50:
print “Which is 50”
elif v < 50:
print “Expression value is less than 50”
else:
print “Could not find true expression”
It I useful to imagine ifs as tree diagrams, every time you get to a road-split you have a certain amount of options to follow and you have to choose one to advance forwards, and the way of visualizing a nested conditional is a crossroad that leads to another crossroad.
This gives you a whole new world of possibilities for filtering and processing data, but you have to be careful, the more intricate the nesting is the more you will have to debug and the harder it will be, so be careful and ONLY use nesting when absolutely necessary.
]]>
This three pals work together to make our life easier and just like the while they work with conditions.
We use if, elif and else when we desire to perform different actions depending on the outcome of a certain conditions, or multiple of them for that instance.
First let’s start with If and else. If will perform an action once IF a condition is met, and we use the else as a complement for this if, this is because if the condition of the “if” is not met, then the program will have nowhere else to go and it will die. Using “else” we suggest a second option, an escape route, for the program to use when the condition for “if” is not met.
Now, the thing with while and if is that they give you only two options to choose from, vanilla or chocolate, that’s why we have the “elif” condition to help us out, with else we can add as many extra conditions as we desire, sparing us a lot of trouble.
As an example:
X=input (“write 1 or 2”)
If (x=1):
Print (“yes”)
Elif (x=2):
Print (“no”)
Else:
Print (“wrong answer”)
In here we are validating the answer given to us by the user, we give the program two specific conditions for pairing the value of x given to us by the user and an “escape route” in case that the value doesn’t fit in any of the two previous conditions.
First the program will get the value of x from the user, and it will pair it with each of the conditions, if the value provided by the user is equal to one then the program will print “yes”, and if I is not it will validate the second condition, in the case that the value is equal to two then the program will print “no”, last but not least, if the value given by the user is neither one or two, then the program will take the “escape route” and print “wrong answer”.
This conditionals can be paired with “While” to make a program that constantly evaluates the values given to it, allowing us to make programs that adapt to a changing value.
]]>First we shall create our own module by opening a new file and writing the following function:
Def smores (x,y):
C = x + y
Return c
Then save the file with the name “Coco.py” in the folder yo store all of your programs.
Now we can make use of it, as you can probably tell the function above makes an addition of two numbers, if you need to perform this operation in a program, instead of writing it again you can just import it with something called “dot notation”.
Get to the first line of your code and type the command “Import”, then write the name of your file, in this case Coco, do not write the “.py”. After that go to the part where you need to implement the function and type “Coco” followed by a dot and then the name of the function, in this case “smores”, it should look like this: “Coco.smores()”, place the values you want added inside the parenthesis and there you go! As simple as that.
As a plus from creating your own modules with useful functions inside of them you can also use some that already come within python or just download some from the internet.
The import process will be the same for all of the modules, you just have to be careful and be sure you save them all in the same place for easy Access.
]]>