Rangos…

--Originally published at Mike's Blog

Los rangos son una rapida manera de imprimir números deseados. Estos son entre los valores que le pusimos.  Estos rangos son utilizados en los ciclos for, para poder dar los parametros del ciclo.  El comando es de esta manera:

  • for var in range(num inicial, num final, saltos)

Python el primer parametro es el número con el que empieza, el segundo es el número con el que termina, y trecero es cuanto va a saltar.

Por ejemplo:

zettayotta1

Aqui queremos hacer una lista que vaya guardando los valor del contador.  En este caso el número inicial es 1 y va contando de dos en dos hasta que llega a 29. Recordemos que Python tomaría como número inicial al 1 y como final al 29. El número final escrito no se incluye, solo se incluyen valores menores que este. De aqui sale que tomaría hasta el 29.

El resultado de este programa es una lista.

holshols

MAS INFO AQUI

 

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


Creation and use of dictionaries

--Originally published at Programming Fundaments

A Dictionary  is a way to store data just like a list, but instead of using only numbers to get the data, you can use almost anything. This lets you treat a dictionary like it’s a database for storing and organizing data any kind of data:

>>> stuff = {'name': 'Zed', 'age': 39, 'height': 6 * 12 + 2}
>>> print stuff['name']
Zed
>>> print stuff['age']
39
>>> print stuff['height']
74
>>> stuff['city'] = "San Francisco"
>>> print stuff['city']
San Francisco

And that’s it. It is just really another kind of list, and a little bit simple once you get the hang of it

Examples and more at: https://learnpythonthehardway.org/book/ex39.html

 


Creation and use of ranges

--Originally published at Programming Fundaments

Range() is a function, it is used to generate a list of numbers. And it has a set of parameters:

  • start: Starting number of the sequence.
  • stop: Generate numbers up to, but not including this number.
  • step: Difference between each number in the sequence.

Some note:

  • All parameters must be integers.
  • All parameters can be positive or negative.
  • range() (and Python in general) is 0-index based, meaning list indexes start at 0, not 1. eg. The syntax to access the first element of a list is mylist[0]. Therefore the last integer generated by range() is up to, but not including, stop. For example range(0, 5) generates integers from 0 up to, but not including, 5.

Some Examples:

>>> # One parameter
>>> for i in range(5):
...     print(i)
...
0
1
2
3
4
>>> # Two parameters
>>> for i in range(3, 6):
...     print(i)
...
3
4
5
>>> # Three parameters
>>> for i in range(4, 10, 2):
...     print(i)
...
4
6
8
>>> # Going backwards
>>> for i in range(0, 10, 2):
...     print(i)
...
0
2
4
6
8

Reading and writing of text files

--Originally published at Programming Fundaments

In Python, you don’t need to import any library to read and write files., you just eed the flie to open, and for doing so, you will have to use the “open()” command:

file_object = open(filename, mode) #where file_object is the variable to put the
file object.

There are two types of files: text and binary; A text file is often structured as a sequence of lines and a line is a sequence of characters. And a binary file is basically any file that is not a text file. Binary files can only be processed by application that know about the file’s structure.

and you have to define a mode, which the are some type of:

  • ‘r’ when the file will only be read
  • ‘w’ for only writing (an existing file with the same name will be erased)
  • ‘a’ opens the file for appending; any data written to the file is automatically added to the end.
  • ‘r+’ opens the file for both reading and writing.

At the end it will create something like this:

>>> f = open('workfile', 'w')
>>> print f

To create an text file just follow the example:

file = open("newfile.txt", "w")

file.write("hello world in the new file
")

file.write("and another line
")

file.close()

Resulting in:

$ cat newfile.txt 
hello world in the new file
and another line

Examples and More at: http://www.pythonforbeginners.com/files/reading-and-writing-files-in-python


Validated user input

--Originally published at Programming Fundaments

In this case you wnat the user to interact with your program; for example, if they want to start making another accion by simply using the srings “yes” and “no”. Example:

endProgram = 0;
while endProgram != 1:

    #Prompt for a new transaction
    userInput = input("Would you like to start a new transaction?: ");
    userInput = userInput.lower();

    #Validate input
    while userInput in ['yes', 'no']:
        print ("Invalid input. Please try again.")
        userInput = input("Would you like to start a new transaction?: ")
        userInput = userInput.lower()

    if userInput == 'yes':
        endProgram = 0
    if userInput == 'no':
        endProgram = 1

The last program has en error, that uin every time you answer something else it will accept it and restart the program

It simply need a codeeditor to export it and that’s it

Examples & More at :http://stackoverflow.com/questions/16635073/validating-user-input-strings-in-python


Strings

--Originally published at Programming Fundaments

Strings are some of teh most popular types in python. We can create them simply by enclosing characters in quotes (Note: double quotes are treated as single quotes)

var1 = 'Hello World!'
var2 = "Python Programming"

You can also change or update these strings, to make small changes or to change it completly:

var1 = 'Hello World!'

print "Updated String :- ", var1[:6] + 'Python'

Resulting in:

Updated String :-  Hello Python

 

 


Python Lists and Tuples

--Originally published at Programming Fundaments

These are the most common build-in data type for python. These are used to store objects or values in a specific order. These are really easy to create. Here:

# Lists must be surrounded by brackets
>>> emptylst = []
# Tuples may or may not be surrounded by parenthesis
>>> emptytup = ()
Those were empty list. To create non-empty lists or tuples, the values are separated by commas:
# Lists must be surrounded by brackets
>>> lst = [1, 2, 3]
>>> lst
[1, 2, 3]
# Tuples may or may not be surrounded by parenthesis
>>> tup = 1, 2, 3
>>> tup
(1, 2, 3)
>>> tup = (‘one’, ‘two’, ‘three’)
>>> tup
(‘one’, ‘two’, ‘three’)
 (To create a tuple with only one value, add a trailing comma to the value.)
Example & More at: http://pythoncentral.io/python-lists-and-tuples/

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