Challenge completed!

--Originally published at Hector Martinez Alcantara

Here’s my code of the second challenge from the class TC101.

It consist in sorting some numbers, an user type some numbers separated by coma in the terminal, and then the program do the bubble sort to re-order the numbers from smallest to largest.

First I read the numbers, then I compare two positions, to check if the number is higher than the previous number and if it’s the case, they change positions, doing this iteration length – 1 times.

That’s called bubble sort.

text=input("Type some numbers separated by coma\n")
numbers=text.split(',')
print("In disorder")
for number in numbers:
 print(number)
length=len(numbers)-1
for iteration in range(0,(length)):
 for position in range(0,(length)):
 if numbers[position] > numbers[position+1]:
 change=numbers[position]
 numbers[position]=numbers[position+1]
 numbers[position+1]=change
print("In order")
for number in numbers:
 print(number)

Thanks for reading.

 


Sum of vectors program

--Originally published at Hector Martinez Alcantara

Today I finished a program that can tell you the sum of three, or as many vectors as you want and the vector that balance the system.

There is a menu that shows two options.

In the case A you type 3 forces with their angles, and then the program shows the sum of components in X, components in Y, the resulting vector with its angle, and the vector with the angle that balances the system.

In the case B you type how many forces you want, then you type the forces with their angles, and then the program shows the sum of components in X, components in Y, the resulting vector with its angle, and the vector with the angle that balances the system.

import math
#------------------SHOWS THE VECTOR AND IT'S COMPONENTS-----------------
def Vector(compx,compy):
 magnr=math.hypot(float(compx), float(compy))
 print("\nSumatoria de componentes en X " + str(compx))
 print("Sumatoria de componentes en Y " + str(compy))
 print("\nVector Resultante:")
 if compx<0.0 and compy>0.0:
 print("Segundo sector")
 angr=math.degrees(math.atan(compy/compx)) + 180.0
 elif compx<0.0 and compy<0.0:
 print("Tercer sector")
 angr=math.degrees(math.atan(compy/compx))+ 180.0
 elif compx>0.0 and compy<0.0:
 print("Cuarto sector")
 angr=360+math.degrees(math.atan(compy/compx))
 else:
 print("Primer sector")
 angr=math.degrees(math.atan(compy/compx))
 print("La magnitud del vector resultante es "+ str(magnr) +"N")
 print("El angulo del vector resultante es "+ str(angr) +"° del eje +x")
 print("\nVector Complementario:")
 if compx<0.0 and compy>0.0:
 print("Cuarto sector")
 angr= angr + 180.0
 elif compx<0.0 and compy<0.0:
 print("Primer sector")
 angr= angr - 180
 elif compx>0.0 and compy<0.0:
 print("Segundo sector")
 angr= angr - 180.0
 else:
 print("Tercer sector")
 angr= angr + 180.0
 print("La magnitud del vector complementario es "+ str(magnr) +"N")
 print("El angulo del vector complementario es "+ str(angr) +"° del eje +x")
#--------------MAIN PROGRAM--------------------------------
y=0
while y!=1:
 print("\nCasos:")
 print("A) Tres fuerzas, encontrar la fuerza 
Continue reading "Sum of vectors program"

Nesting of conditional statements

--Originally published at Hector Martinez Alcantara

Firstly, what’s nesting?

Nesting in programming is to use a function inside the same function.

In the conditional statements is used to make a condition into another condition, but, what’s the diference between nesting a condition and using operators in the conditional statement?

The main advantage that I can notice  is that in every condition you can realize an action and use conditions into another condition, it makes something like a tree of conditional statements that can  be seen as a choice of multiple options, and like a path to reach a special case.

Well that’s how i see it but, it can be replaced with well planned conditions with operators, and remember the zen 0f python, flat is better than nested.

Also I’ve noticed that in python you don’t have a special function to switch an option, like in  C or Java language, or a select case from Visual Basic. So you have to use the conditionals as a switch option.

Lets see some examples of how nesting a conditional statement works.

Example:

x = input("type only one character \n")
if x.isdigit():
 print("Is a number")
 if int(x) > 5:
 print("the number is greater than five")
 elif int(x) < 5:
 print("the number is smaller than five")
 else:
 print("the number is five")
elif x.isalpha():
 print("you have typed letters")
 if len(x) < 2:
 print("you have typed " + str(x))
 else:
 print("you have typed more than one word")
else:
 print("I dont know what you have typed")

Result:

#if you type a 6 or greater
Is a number
the number is greater than five

#if you type a 4 or smaller
Is a number
the number is smaller than five

#if you type a 5
Is a number
the number is five

#if you type any letter
you have typed letters
you have 
Continue reading "Nesting of conditional statements"

Modules/Libraries in python

--Originally published at Hector Martinez Alcantara

If you want to use a  function in other program, you can script it, it’s easy to use it in other program just importing the module. But, what’s importing , and what’s a module?

If you wanto to do your own module, you have to do this:

def function(optionalvalue):
     #Here's what you want to do
     #return a value

Yes, is like doing a simple function, then save it with the extension .py and save it in the current directory.

A module is like a script where you define some functions, and importing is the action when you want to use it, and you take it from the other script to your script.

You can import a function typing this:

#To import all the package
import module
#Or
from package import *

It’s that easy, but if you have a module in a package and you dont want to import all the package, you can specify what module and/or function you want to import.

If you want to do it specific, you have to type something like this:

#To import specific function
import package.module.function
#Or
from package.module import funcion

There’s much libraries (modules) that python also provides, apart of the standard library. The standard library is the library that contents the most basic functions you use in the program.

modules-python

To import other modules is the same process like you do with your own modules, but, with other names, obviously.

There’s a index of some default python modules.

datetime    Basic date and time types.
math           Mathematical functions (sin() etc.).
decimal      Implementation of the General Decimal Arithmetic Specification.
difflib         Helpers for computing differences between objects.
enum          Implementation of an enumeration class.
errno          Standard

Continue reading "Modules/Libraries in python"

Functions in Python

--Originally published at Hector Martinez Alcantara

Hey there, i’m going to explain how to create and use functions in python 3. First, a function is a process that repeats several times and to reuse code, you use a function.

In the next example we can see a definition of a function:

def Litleman(Amaterial):
   print(' 0')
   print(' /T\\')
   print(' /\\')
   drawing= 'A man of '+ Amaterial
   return drawing

The word def inicates that we’re creating a function, then you put the name of the function, and in parenthesis a parameter of any type, which is a variable that will be used in the function, finally, you put the word return, to get back in the code, you can return a parameter.

Here is an example of how to cal a function:

Littleman('Steel')

It’s very simple, you call a function by it’s name with parenthesis at the end, and in the parenthesis you can introduce a parameter like the example above.

Here’s an example of the result of the function:

Littleman('Steel')
  0
 /T\
 /\
'Its a man of Steel'

It’s very simple right?

Now you know how to create and use functions!

Thanks for reading, have fun!

Special thanks to Barron stone on Programming fundamentals in real life from lynda.com

 


Basic data types

--Originally published at Hector Martinez Alcantara

In this post we’re going to see the basic types of variables we can have in python 3.

Number: These are created by assigning a value to a variable, there are diferent types that python support automatically they are:

  • int (signed integers)
  • long (long integers, they can also be represented in octal and hexadecimal)
  • float (floating point real values)
  • complex (complex numbers)

Example of Numbers:

var=5 #integer
var=5.5 #float
var=555555555L #The letter L is to long numbers
var=5.55e-34j #Complex numbers have a j that's the imaginary unit

String: They are arrays of characters that are usually words or sentences.

They’re variables that saves sentences, that are usually shown in the screen or will be transformed to be shown in the screen.

Example of Strings:

var='Hello, I love tacos'

List: The lists are like arrays of diferent or common types of variables, the lists can be updated whenever you want, and can be enlarged.

Lists are often used as lists (even the word say it).

Example of List:

var=['Hello',5,'another thing',5.5]

Tuple: They are arrays of diferent or common types of variables, but ulike lists, the tuples can’t be updated, and are only one length.

Tuples are often used as normal arrays.

Example of Tuple:

var=('Hello',5,'another thing',5.5)

Dictionary: They are arrays of diferent or common types of variables but unlike tuples and lists every space in the array can be named diferent.

They are often used as tables (like the tables in databases).

Example of Dictionary:

var = {'a string': 'Hello','an integer': 5, 'a float': 5.5}

Now you feel like…

Thanks for reading.

Special thanks to Tutorials point Python Variable Types


If, Elif and Else, the conditional sentences

--Originally published at Hector Martinez Alcantara

We’re going to see now how to make a conditional sentence.

A conditional sentence serves us to tell the program to do an action only if a condition is accomplished. to do it we need to put the word if and then the condition like you can see under this paragraph.

Example of if:

option=int(input('type a number one'))
if option==1:
   print('You have typed one! :)')
   print('Well done!')
print('And its done')

Above you can see that the value that’s assigned in the variable option have a prefix, that assigns the type of variable that the input function will return.

The statement of condition is if the variable option is exactly equal to the number one. If it’s true the program will do the next statements with tab and continue with the code.

If not, it will not do nothing with the lines with tab, but then continue the code.

Example of else:

option=int(input('type a number one'))
if option==1:
 print('You have typed one! :)')
else:
 print('You have not typed one... :(')

An else statement serves to do actions if the above condition is not accomplished.

In the example above, if you don’t type a number one, the sentences under the else statement will be executed.

Elif Example:

print('Lets play a game')
print('You only have three options')
print(' a)Save your wife, but loose a leg')
print(' b)Save your dog, but loose an arm')
print(' c)Save your son, but loose the eyes')
Option= input('Choose an option, if your option is not one of the above mentioned you will die\n')
if Option=='a':
 print('\nLoose your leg')
elif Option=='b':
 print('\nLoose your arm')
elif Option=='c':
 print('\nLoose your eyes')
else:
 print('\nYou have chosen to die, it is ok, you will die but all your loved ones will be ok')

Finally the reserved word elif serves to have diferent

Continue reading "If, Elif and Else, the conditional sentences"

Zen of python

--Originally published at Hector Martinez Alcantara

Zen of python
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

What’s this for me?

Its an ideal form of programming not only to python, for all the languages, but it’s very ideal, you often have to use other methods to do a code, usually because of the time.

The problem maybe it’s not very difficult to solve with the zen of python, but the time is running out and other solutions solve the problem easily and quickly, so you have to finish it.

Thats my opinion, tan tan.

Images from:

https://pbs.twimg.com/profile_images/556094082456383489/jfoAAmDG.png

https://upload.wikimedia.org/wikipedia/commons/thumb/c/c3/Python-logo-notext.svg/2000px-Python-logo-notext.svg.png


Inputs and Outputs

--Originally published at Hector Martinez Alcantara

Hey there, i’m going to explain how the basic inputs and outputs of text work.

Example of a basic input and output:

x=input('Type something\n')
print('You've typed '+x+'!')

Which result is:

Type something
>>>typing something
You've typed typing something!

The most basic form you can make an input for basic text is with the reserved word input, this function receives a string(an array of characters), assign it to a variable, and prints a message on the screen.

syntax of  an input:

variable=input('A message you want to show')

Then the most basic form you can show the value of a variable is with the reserved word print, the function print will convert every type of variable to a string and will show that string on the screen.

With the function print you can show text on screen, or a composed message of text and a variable.

here the syntax of an output:

print('The message you want to show') #Shows only the text between ''
print(variable) #Shows the value of 'variable'

Suposing that variable have a value of 10 integer the output will be:

>>>The message you want to show
>>>10

To show a message composed of text and a value of a variable you’ll type:

print ('First part '+ variable +' last part') #Shows a composed message of text

The text binds with the variable using the operator ‘+’ and makes only one string like the result below.

>>>First part 10 last part

Special thanks to Output and input in python


Comments in python

--Originally published at Hector Martinez Alcantara

#This is a comment in python 3
print('Program of a comment') #here can be a comment too
'''
this is a multi line comment
yes, here too
and another line of comment
final line of comment
'''

A comment is an annotation about everything you want it to be, this code won’t affect the program at all, its only to be seen in the code, not in the result of it.

The result of the code above will be the next

Program of a comment

Like you can see at the top, a comment can be a single line, a line after a code, and a multi-line comment. To do a single line or a line after a code you have to type a hash ‘#’, after the hash in the line, everything will be a comment. To do a multi-line comment you tipe three single or double quotes like ”’  or “”” and then everything will be a comment, until you type another time triple quotes.

Credits to  Comentarios en python – Linea de código

#Python3 #LearningANewLanguage #tc101