Rescuing the semestre

--Originally published at Programming Fundaments

Soooooo… This topic was one I thought I would never have to deal with at college (Somehow I thought this) . But here we are (sadly..) Trying to rescue the semester

And this might be might you be asking; Well…. is basically to pass that class that you have been strugguling from the first partial. And it is NOT pretty. So having to rescue this semestre might be a task that most people will have to deal with. Some more that other…

Sooo how can you save the semester?? Simple.. Study for the final. And H.A.R.D. I hope everyone will save at least this semestre (or at least me)


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/

When to use what type of repetition in a program

--Originally published at Programming Fundaments

This is a simple one: we are going to define when to use wichtype of loop, so we are going to make it a brief one.

If you are going to use a list of varios result you can use the “for” loop. While (no pun intended) you can use “while” loop to make a result reapeat until this one is false. There is it!


Use of recursion for repetitive algorithms

--Originally published at Programming Fundaments

In this topic we need to define “recursion” this means to “run back” or to retunr to itself. For this topic we are going with some factorials. and what we want to acomplish is to avoid infinite loops. to explain it better:  Recursion in computer science is a method where the solution to a problem is based on solving smaller instances of the same problem. Example:

def factorial(n):
    if n == 1:
        return 1
    else:
        return n * factorial(n-1)

Then we add a couple of prints to the previous funtion

def factorial(n):
    print("factorial has been called with n = " + str(n))
    if n == 1:
        return 1
    else:
        res = n * factorial(n-1)
        print("intermediate result for ", n, " * factorial(" ,n-1, "): ",res)
        return res	

print(factorial(5))

Giving the next result:

factorial has been called with n = 5
factorial has been called with n = 4
factorial has been called with n = 3
factorial has been called with n = 2
factorial has been called with n = 1
intermediate result for  2  * factorial( 1 ):  2
intermediate result for  3  * factorial( 2 ):  6
intermediate result for  4  * factorial( 3 ):  24
intermediate result for  5  * factorial( 4 ):  120
120

Examples and more at: http://www.python-course.eu/recursive_functions.php


For loops

--Originally published at Programming Fundaments

Usually for loops are used for range loops (list) , usually the syntax is this:

for iterating_var in sequence:
   statements(s)

The difference with the “with” loops is that you don’t have to have “true” or “false” variables because it is used for lists. Example:

for letter in 'Python':     
   print 'Current Letter :', letter

Resulting in:

Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n

 

Examples and more from: https://www.tutorialspoint.com/python/python_for_loop.htm