Dictionaries

--Originally published at Hector Martinez Alcantara

A dictionary is like the lists, is a list of elements of different types, or the same type identified by a special name.

This is the sintaxis:

dict = {'identifier1': 'Element1', 'identifier2': 2, 'identifier3': 'Element3'}

You can access to a dictionary by the identifier of the element.

print(dict['identifier1'])  #Result: "Element 1"
print(dict['identifier2'])  #Result: 2

You can update a dictionary by rewriting it, or by simply assigning a value to the element:

dict['identifier1']= "New value"

To delete an element of the dictionary, you have to use the reserved word del or the method clear to delete all the elements in the dictionary:

del dict['identifier1']
dict.clear()

Python includes the following dictionary functions −

Function with Description
cmp(dict1, dict2)

Compares elements of both dict.

len(dict)

Gives the total length of the dictionary. This would be equal to the number of items in the dictionary.

str(dict)

Produces a printable string representation of a dictionary

type(variable)

Returns the type of the passed variable. If passed variable is dictionary, then it would return a dictionary type.

Python includes following dictionary methods

Methods with Description
dict.clear()

Removes all elements of dictionary dict

dict.copy()

Returns a shallow copy of dictionary dict

dict.fromkeys()

Create a new dictionary with keys from seq and values set to value.

dict.get(key, default=None)

For key key, returns value or default if key not in dictionary

dict.has_key(key)

Returns true if key in dictionary dictfalse otherwise

dict.items()

Returns a list of dict‘s (key, value) tuple pairs

dict.keys()

Returns list of dictionary dict’s keys

dict.setdefault(key, default=None)

Similar to get(), but will set dict[key]=default if key is not already in dict

dict.update(dict2)

Adds dictionary dict2‘s key-values pairs to dict

dict.values()

Returns list of dictionary dict‘s values

Thanks for reading, and special thanks as usual to Tutorialspoint who always have good information.


Ranges in python

--Originally published at Hector Martinez Alcantara

A range is a list of elements from one point to another.

The sintaxis is:

range(condition)

You can do a range to be from some number to another, and with some condition

Examples:

var=range(9) #Result:0,1,2,3,4,5,6,7,8
var=range(3,7) #Result:3,4,5,6
var=range(0,100,10) #Result:0,10,20,30,40,50,60,70,80,90

In the first example the range begins in 0 and finishes in 8 returning a list from 0 to 8.

In the second example the first number represents the first number of the range, and the second number the finish, but always the number of finish will be one less than the specified.

In the third example, is the same as the second, the first number indicate the beginning and the second number indicates the finish, but the third number indicates how many numbers separate one number from another.

Thanks for reading, comment.


Reading and writing of text files

--Originally published at Hector Martinez Alcantara

To write or to read something from a text file, first you have to open a file.

This is the sintaxis of how to open a file:

file object = open("file_name_with_extension_and_directory","type_of_open")

Here is a list of the different modes of opening a file −

Modes Description
r Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode.
rb Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This is the default mode.
r+ Opens a file for both reading and writing. The file pointer placed at the beginning of the file.
rb+ Opens a file for both reading and writing in binary format. The file pointer placed at the beginning of the file.
w Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
wb Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
w+ Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.
wb+ Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.
a Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for
Continue reading "Reading and writing of text files"

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.


Strings

--Originally published at Hector Martinez Alcantara

A string is an array of characters like a word or a phrase which have some properties or specific functions to modify or analyze the string.

First, how to inicialize it?

var="Hello world"

All the characters between the quotes are part of the string, but how to access it?

print(var) #The result is 'Hello world'
print(var[3]) #The result is 'l'
print(var[0:4]) #The result is 'Hello'

You can modify the strings like this:

var="Another value to the string" #Modifying all the string
#Result: Another value to the string
var= var + " with something more" #Add characters to the string
#Result: Another value to the string with something more
a="Something"
a=a * 3 #Repeating the string
#Result: SomethingSomethingSomething

You can also access to strings into another string made by a print with the operator %s:

var="Another value to the string" 
a="Something"
print("There are %s i want to say, like: %s" %(a,var))
#Result: "There are Something i want to say, like: Another value to the string"

As you can see, you access the strings in the %() in order that they were write

There’s a lot of types of values you can acess in a string, like the table below.

Format Symbol Conversion
%c character
%s string conversion via str() prior to formatting
%i signed decimal integer
%d signed decimal integer
%u unsigned decimal integer
%o octal integer
%x hexadecimal integer (lowercase letters)
%X hexadecimal integer (UPPERcase letters)
%e exponential notation (with lowercase ‘e’)
%E exponential notation (with UPPERcase ‘E’)
%f floating point real number
%g the shorter of %f and %e
%G the shorter of %f and %E

And also there are some functions prefurbished to the strings listed in the table below:

Methods with Description
capitalize()
Capitalizes first letter of string
center(width, fillchar)

Returns a string padded with fillchar with the

Continue reading "Strings"

Tuples

--Originally published at Hector Martinez Alcantara

The tuples are almost the same as the lists, with the diference that tuples are immutable, is means that you can’t enlarge or shorten a tuple, but you can update it.

Also the syntax of the tuples is different,if you want to create a tuple you have to use parentheses unlike lists.

The syntax is:

Tuple=("elem",2,3,"elem 4")

If you want to access it you can do the same as you do with the lists, you also have to use brackets to access a value of the tuple.

print( Tuple[2] )

The Tuples operators and indexing are also the same, if you want to know more about them, visit my last post called Lists or Tutorialspoint, there is a lot of information about these topics.

Thanks for reading, and again thanks to  Tutorialspoint where you can find a lot of information.


Lists

--Originally published at Hector Martinez Alcantara

In this posst we’re going to explain some things about the lists in python.

Firstly, a list is like an array of diferent or equal type of elements which can be updated, enlarged and shortened.

The syntax of a list is the next:

List= ["element 1", 2,"element3",...,n]

To access a list you have to type brackets after the list name, and between them the number of the position you want to acess.

print(List[0]); #This shows'element 1' which is the first element of List
print(List[1:3]) #This prints the elements in position 1 to position 3

To update an element of  the list you only have to assign the new value to the List’s position.

List[0]="New element"

To delete an element you have to use the function del with the position of the list that you want to delete.

del(List[4])

Then there are some operations with operators that are basic in a list like: +, *, len, in, for.

Python Expression Results Description
len([1, 2, 3]) 3 Length
[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation
[‘Hi!’] * 4 [‘Hi!’, ‘Hi!’, ‘Hi!’, ‘Hi!’] Repetition
3 in [1, 2, 3] True Membership
for x in [1, 2, 3]: print x, 1 2 3 Iteration

 

Python Expression Results Description
L[2] ‘SPAM!’ Offsets start at zero
L[-2] ‘Spam’ Negative: count from the right
L[1:] [‘Spam’, ‘SPAM!’] Slicing fetches sections

Some Basic  methods

cmp(list1, list2)
Compares elements of both lists.

len(list)
Gives the total length of the list.

max(list)
Returns item from the list with max value.

min(list)
Returns item from the list with min value.

list(seq)
Converts a tuple into list.
Python also includes following list methods

list.append(obj)
Appends object obj to list

list.count(obj)
Returns count of how many

Continue reading "Lists"

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"