Creation and use of Lists/Tuples (Python)

--Originally published at Quirino´s Projects

The Lists/Tuples are kind of the same, tuples are like lists but its contents cannot be modified.

A list contains a set of values, it can be almost anything, from int to floats,, from strings to even other lists.

Here are a few examples of list

myGrades = [10,10,10,10,10,10] #LOL

random = [1,”Juan”,[1,2,3],5.0,”Anita lava la tina”]

The way we access a list element is by its index

list[0] returns the first element, list[1] returns the second, and so on.

To check useful function for lists check https://www.tutorialspoint.com/python/python_lists.htm


Creating and using your own libraries

--Originally published at Quirino´s Projects

Sure you know how to import libraries, if you don’t , just check my post about that

Somewhat you want to do something many times in different programs, and of course you would like to use a function but taking a function from another program then copy/pasting it to your current can get tedious, thats why you should be creating your own libraries, its simple, you create a python program as normal that contains the functions that your are going to use, in my case i created a quirinoStuff.py that contained 3 functions useful for opening files, just doing open() is easy you might say but this one ensures that the file you are trying to open exists so there won’t be crashes because of the user not typing correctly, so we import as it was a built in one like:

from quirinoStuff import openFile

And know we can use openFile in our program without the need to write the function again

You can check an example in my GitHub https://github.com/QuirinoC/46Exercises
In the simpleIO37.py


Creation and use of strings

--Originally published at Quirino´s Projects

string is a data type which contains a set of concatenated characters, is one of the simplest data type in python

A string must be between “” or ”, there can be empty strings like the ones mentioned before, or strings that contain just a space like ” ” we can use strings to store names, addresses, colors, well everything that can be written, a word or a phrase, there is no limit.

name = “Juan”

address = “Milan  #### Col. Providencia ”

numbersFromOneToThree = “one\ntwo\nthree”

If we would print the three variables we would get

“Juan”

“Milan  #### Col. Providencia”

“one

two

three

As you can see \n prints a new line, this happens because \ is a special character that can make the string do different things with the char next to it, using \n makes a new line \” or \’ makes you able to print the ” ‘ without ending or starting a new string

String operations, you can also perform sums with strings too, adding a character to a string or a string to a string will concatenate the given string to the string we are operating with

We can also pass strings to a for, thus we can operate each char individually

newString = “”

for i in “Juan”:

newString += (i.upper() + “_”)

print (newString) #J_U_A_N

We can multiply strings to get a bigger one containing the string itself

print (“Yiii” * 3) # prints “YiiiYiiiYiii”

For more info (in spanish) check this great tutorial http://librosweb.es/libro/python/capitulo_6.html


Use of recursion for repetitive algorithms

--Originally published at Quirino´s Projects


Repetitive algorithms are useful when you want to do something with some values, then with the results of that, do the same until we reach to our desired result

#Ignore newList() its a function i created for creating a completely new list so the original won’t be affected

1 def chain(word,elements,wordChain):
2      elements = newList(elements)
3      wordChain.append(word)
4     elements.remove(word)
5     for nextWord in elements:
6          if word[-1] == nextWord[0]:
7               chain(nextWord,elements,wordChain)
8               return wordChain
9       newWordChain = newList(wordChain)
10       wordChain = []
11       return newWordChain

 

The function above at first its a bit hard to understand, so ill do my best, and explain step by step

The function creates the biggest chain possible with the following rule:

We have a word, the first character in the next word of the chain must be the same as the last one of the last of the word

In the first Function run the word is a word (doesn’t matter which one right now) in the elements list, elements is a list that contain a set of words, and wordChain will be the chain to be returned

(3) First, the word its appended, since it will be the first word

(4) We remove the word from the elements list so we can’t repeat words

(5-7)We search for every word in elements that meets our condition if it gets evaluated to true, then we call the function with the values we have right now

For the second run we do the same but now the function parameters are the ones from the first run, when the condition

Continue reading "Use of recursion for repetitive algorithms"

Reading and writing of text files

--Originally published at Quirino´s Projects

southpark

The most useful thing about doing console programs in python is the ability to read and write files, it gives us access to create and read files within our computer, without the need to copy/paste into our code and having a way to store the results of the program.

To get a file in our code first we have to open()

We define the name of the variable the file will be stored into and we open it

myFile = open(‘robots.txt’,’r+’)

The sintaxis is

open

(

Name of the file as a string

,

Parameter

)

To check more parameters about file I/O check this table from tutorialspoint.com

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.
Continue reading "Reading and writing of text files"

Creation and use of dictionaries in Python

--Originally published at Quirino´s Projects

dictionaryA very useful data type in python are dictionaries, these could be understand as a list, but each element its a key with its respective value e.g.

We can have a list that holds every word in the english alphabet, but if we wanted to create a program that holds the number of times a letter appears in a string, creating a variable for each letter would be that practical, so a dictionary would be useful

alphabet = {“A”:0,”B”:0,”C”:0,”D”:0…}

Now we have a dictionary that holds a numerical value for each letter, the sintaxis of the dictionary is the following

{} The curly braces contain the dictionary

: The colon separates the key from the value of the key

“A” This is the key, it holds the value next to it

0 Its the value of the key

If we would like to add elements to our dictionary, we simply assign a value to a key is if it was already there

alphabet[“E”] = 5

A useful function when you are working with dictionaries is dictionary.keys(),this function returns the keys in a dictionary as a list, so we could check if a key is in the list before doing something with it

To get more info about dictionaries check:

https://www.tutorialspoint.com/python/python_dictionary.htm

 

 


While and For Loops

--Originally published at Quirino´s Projects

When we want to repeat some code n times, depending on a variable, or until a condition is met, we can use While and For loops

For

A for loop takes a data type, could be a string, a list, a dictionary, and basically every type of data that can be access by its elements, and runs n times were n is the number of elements of the list, and creates a variable each loop with each element

And example, we have a list

myList = [0,1,2,3,4]

And we want to print each element individually, in this case we use the for loop like this

for i in myList:

print (i)

Here the i in the first loop takes the value of 0, then gets printed, then takes the value of 1, then gets printed, and so on the i becomes the value of the index of the list

Here is an example of a program that eliminates spaces from strings

myString = input(“Give me a string: “)

newString =””

for i in myString:

if i != ” “:

newString += i

print (newString)

This program checks each character in the string, if the string is different that a blank space, is not added to the new string

While

A while loop is a loop that runs the code within forever until the condition given is evaluated to False

while True:

print(“I will be printed for ever”)

This is a not correct way of using loop, but serves to explain for While

n = 10

while n <100:

print (“Value of number is {0}”.format(n))

n -= 2

 

 

 

 


Control flow with If, elif, else, and nested conditionals

--Originally published at Quirino´s Projects

When we want to do something based on an specific value, or do something if a value is equal to something or do something else if the value is different than that, we use control flow for example we want to create a program that reads user age and prints whether or not he can enter to the bar

In this case we can use the if conditional, the if sintaxis works like this

if (conditional):

(statements)

“If this is true then do this (statements)”

age = input(“Whats your age? “)

if age >= 18:

print(“You may come in”)

This program checks if the age is bigger or equal than 18 and if the age is, it prints the string, if the age is less than 18 the statements in if will be ignored.

If we wanted to do something

age = input(“Whats your age? “)

if age >= 18:

print(“You may come in”)

else:

print(“Weenie hut is next door kid”)

Now we have something to handle when the condition is set to false.

Simple if this is something, do this, if not do that instead

But what if we want to check for another condition if the first one is met? Well in many programming language we would be required to put an if inside the else, but python is helpful including the elif statement, this one works like this

if (condition): #If the first is true

    #Do This

elif (anotherCondition): #If the one above this False

    #Do this

elif (someOtherCondition): #Do this if the one above false

    #Do this

else: #This one is run if non of the conditions is met 

   #Do this 

#Here we continue the program

This way we can do specific things depending on the value of our variables

2000px-If-Then-Else-diagram.svg.png
Continue reading "Control flow with If, elif, else, and nested conditionals"

Importing and Using Modules/Libraries in python

--Originally published at Quirino´s Projects

Python is a really powerful programing language, we can do a lot of things with it, but sometimes the stock python is not enough when we want to do other things easily without having to do our own functions. For example if we wanted to get the Squared root of a number, we couldn’t do it with the basic mathematical operations python gives us in this case we need to import the sqrt function in the math library

The way this works is like this:

from math import sqrt

from 

from the following module

import

Import this

The way this is used is that import checks the math module, then inside it, it takes the sqrt function

This way we only import sqrt function inside math, but if we wanted to import the whole module we could also do

import math

This would let us use everything contained in math, but now to access a method in math we would need to do

print (math.sqrt(6))

Because Python wouldn’t know if we have a sqrt function in our program, so we need to specify from were we are taking this function

Also, we could import some function or a variable from a module, and rename it as we want then use it

from math import sqrt as squaredRoot

print (SquaredRoot(5))

>> 2.23606797749979

131126191411-strahov-abbey-library-horizontal-large-gallery


Creating functions

--Originally published at Quirino´s Projects

This a little bit hard to catch for early beginners, but trust me these are really easy once you understand how the functions are made.

Sometimes we want to do something many or several times in our code changing only a number or a string, and repeating ourselves makes our program harder to read

keep-calm-and-don-t-repeat-yourself

This is were functions become our ally

If we wanted to get the factorial of 3 numbers, without functions we would need to do this:

num1 = int(input(“N: “))
result1 = 1
for i in range(1,num + 1):
result1 *= i
num2 = int(input(“N: “))
result2 = 1
for i in range(1,num2 + 1):
result2 *= i

num3 = int(input(“N: “))
result3 = 1
for i in range(1,num3 + 1):
result3 *= i

print (num1)

print(num2)

print (num3)

Using the for loop each time makes a bulky code, so instead we could use a function

def factorial(num):
result = 1
for i in range(1,num+1):
result *= i
return result

To explain how a function in python works we need to see each part

def

Stands for define is the keyword needed to tell python that the next thing will be a function

factorial

This is the name our function has and the name it will be called with it can be any name but there are a few conventions about naming things in python

Please Check https://www.python.org/dev/peps/pep-0008/

(num)

These are why functions are a bit hard at first, num is the argument that is passed to the function we defined just one, called num but a function can have as many arguments as we want, this argument is used locally inside the function and we cannot edit it outside the function block for easier understanding lets look at this code

def numberTimesThree(num):

    return

Continue reading "Creating functions"