Learn Python in 3 days



Charles Severance AKA Dr. Chuck
This blog is based in his course online

Who may benfit from this blog

Learn Python in three days is primarily aimed to people who already know a programming language and want to know the basics of Python quickly and easily. It is based on the excellent online course Python for Informatics by Dr. Charles Severance. That course is designed to learn from scratch, but in this blog I will assume you already have some experience on what computer, program, variables, etc.. are, so I do not make any reference to these issues.

May this blog be useful for someone who does not know anything about programming? probably yes, but but he/she will have to make an extra effort to look for many things that I have omitted here for granted. I think that is a good way to learn to code from scratch, because the sequence of exercises is very well designed and covers the fundamental problems of programming. With these tools, plus Internet search, I think anyone is in a position to start producing useful code.

The method

The method is opposite as traditionally taught. Here there are no problems for the student's solve, it shows the code already written, the problem solved and explained briefly how it works. As Python has a very clear syntax and self explanatory, I think is the easiest and quickest method. Just like a baby learns to talk, not memorizing words and then learn rules of grammar, but mimic whole sentences spelled by older people, the method used here is similar: to avoid the cumbersome process of try to figure the "solution" to an artificial problem, I prefer show you the problems solved, explaining how they work and encouraging to explore alternative solutions.

How to install

Instructions for installing Python into our computer link found at Dr. Chuck´s website,

How to Start

Once you have installed everything in c: \ Python27 will be able to start programming. There are several ways to run a program in Python, for example using "Idle" an aplication that allows you to write the code and run it. I recommend to download also Notepad ++ and use it to write the code. To run it from the console, for Windows 7 go to Start and write in the command window cmd, an MS/DOS style console will appear as shown the image bellow. Then move using cd (folder) where you wrote your program. Then run it by placing the full name, for example prueba1.py. As in all interpreted languages, Python programs are simple text files, because programs are recognized as such by the extension his name must have the extension py, for example prueba1.py. So if you have saved a file with that name and have the Python interpreter installed, it automatically recognizes and runs

Option: You may check Dr. Chuck´s introductory lectute (Youtube)


DAY ONE


1.-Hello World

 Every student of a new language must write this tribute to the Gods of Codes, Teach to write a message in the console. Write in Notepad ++ and store as test1.py
Test: type test1.py and in the console must appear Hello World


2.-Input a name, stores into a variable and print in the console, a variant of Hello World, using raw_input to enter data
Test: type test2.py in console and "Enter Name"  may appear, if we enter Joe it may appear a line Hola Joe

Variables entered with raw_input are strings (literals) by default, you may turn into floating point using  floar-var=float(string-var). For other Python variables ask in the web. Python is case-sensitive for everything, capitals matter, Date and date are different variable names, if you type PRINT or Print instead print an error will occur..


3.-Ask for variables, change some to floating point numbers, do aritmetic operations and show results
Prueba: al entrar 45 horas a un rate de 2.75 debe aparecer el resultado de 123.75
Option: You may check Dr. Chuck´s lecture on expressions(Youtube)

4.-Ask for variable data, turn into floating point numbers, make operations, print result.

Test: entering score of 0.95 may appear A

The instruction used is if (condition) : The colon are equivalent to "then " in other languages, that is "if condition is accomplished do the following indented instruction(s)"
elif corresponds to else or else if from other languajes, that is "if the former condition was not accomplished then try with this"
Indenting (tabs or 4 blank spaces) is very important in Python because indicates where the loops closes, it is used in if and other instructions such as for, while etc.
Option: You may check Dr. Chuck´s lecture on Conditional Expressions(Youtube)

5.-Code a function, a function is a piece of code that is frequently used in diferent sections of a program, funtionns are not executed until they are called and return a value calculated from the values (parameters) which was feeded. Funtions are also indented

Functions start with def y end with return. In this example the function computerpay calculate if hours worked exceed 40 and the excess is paid with a bonus of 1.5 times. In Python the character # is used to inser comments, anything following # in the line is not executed
Test: enter 45 hours at rate 3 result is 120+22.5 so may appear Pay: 142.5
Option:You may check Dr. Chuck´s lecture on funtions(Youtube)


DAY TWO

6.-To read a list and print the biggest number

Python lists are very powerful. Are denoted by square brackets and the values ​​are separated by commas, a list can contain another list as an element. lists have many useful features and one of the best is slice, that converts a delimited string to a list. For example we have the string stringdenombres = "Perdo Juan Diego" using slice can create a list stringdenombres.split list = () that would [Pedro, Juan, Diego]. We will use this feature later. delimiters by default are spaces, but it could be any other character as comma, colon, etc. Simply put in the parentheses of split, for example textostrings.split list2 = (",") for comma delimited The strings (character string like "THIS IS A STRING") and lists are treated similarly in Python, both are "sequences", you can go from string to list using split easily
Options:Dr. Chuck on Lists(Youtube) Dr. Chuck on files(Youtube) Dr Chuck on iterations/a>

7.-Enter data within a loop, choose the bigger and the lesser in a serie of numbers entered between 1 y 10000

Test: enter values 8,4,9,2,0,6,5​​, done. It should appear 8 Minimum Maximum is 0

This example uses a cycle who repeat some instructions indefinitely (while True:) remember that the colon denotes the opening of a cycle. Explained in words is "repeat everything comes next indefinitely, when get to the last statement, returning the beginning. In lines 1 and 2 the two variables are initialized: max with a very small value -1 and min with a very large value 10000, the purpose of such initial values is to ensure that will store larger and smaller values respectively in the first round (never less than -1 or greater than 10000). Then ask the user to enter any number using raw_input. If instead of entering a number you enter the word done the cycle ends and jumps to the last two instructions (remember that the indentation mark where the cycle is repeated, break is the instruction to exit a cycle towards the end. The instructions try and except are a trap that check error if the input is not floating point number (decimal) neither the string "done" if data entered is error continues the cycle without executing the instructions below, using the continue statement. The folowing instructions store the maximum and minimum value, comparing the previous value they had with the new value, if its previous value of max is less than the new max then saved it, if the old value of min is greater than the new then store it in min.
Options: You may check Dr. Chuck on Iterations

8.-Retrieve a specific string from a text file For this exercise you have to download the text file mbox-short.txt and store it in the same folder where program is saved, this file contains a series of raw emails where you have to identify the lines starting with the string "X-DSPAM-Confidence:", then to identify the position of colon and extracted the 40 characters who follow to the right of this position, the string is turned into floating point, and add up, count how many lines were selected and average (sum of the numbers divided by number of lines)


DAY THREE

9.-To Identify and retrieve selected slices from a textfile, to store into a dictionary and count them by cathegory, The same file mbox-short.txt with raw mails is used here, the code is as follow:
In this case the problem uses a dictionary (COU) and a list (e), which are initialized empty in lines 3 and 4. The solution into three parts: Between lines 7 and 10 is filled with the list e-mail addresses that are extracted from mbox-short.txt, for this is reviewed every line of the file and if it begins with "from: "then what comes is an email address, but no other information line in addition to the e-mail and is used to transform the line split (string) into a list called words, the line is added post to the list the second word element (in Python the first element is 0 and the second one), in this case is only the mailing address. With that form the extracted list all mail file.

Between lines 11 and 17 we generate a dictionary called cou. a dictionary is also a sequence, but unlike a list has two elements: a key and a value. In our case the key is the e-mail and the value store the times who the element repeats. Lines 13 to 17 acumulate the repeated values ​​for each email (key) in a dictionary, which is a list such as cou = {"pedro@cti.com": 4, "juan@cbs.cl": 3 , "diego@aol.com", 45} Note that dictionaries are annotated with curly parentheses, list with square brackets, the lists store one items at each position, separated by commas, while dictionaries have sets of two elements comma separated. One is the key and the other value. One can understand a list as a line or a column of values ​​in Excel, while a collection has a name and a value associated with that name. The name or key does not change but the value can change.

Between lines 20 and 27 the biggest value (times of appereance) and the email address to which it is associated.
Option: Dr. Chuck on Dictionaries(Youtube) Dr. Chuck on Tuples(Youtube)

10.-Create a dictionary and sort it by value instead of key . Using the same file mbox-short.txt to retrieve and count addresses of email, accumulating those who repeat and how many times they appear in a dictionary, similarly to the previous drill. Then you create a tuple, which is similar to a list but their values ​​do not change (as a sort of a list of constants), the advantage of tuples is they can be used as temporary storage to change the order of a key-value pair in the dictionary (keys become values ​​and vice versa). this allows sort content by values, the code is as follow:
The lines of code are commented, line 10 accumulate values ​​in a dictionary using get in a useful and compact method to build the pair mails times of repitence pairs, in the previous drill a longer but simpler method was used.

And that´s all my friends, I think if someone do these 10 drills by copying and pasting the code, running, adding print in strategic places to see that value are taking the variable values​​, and if after that comes to understand how each of the 10 codes work, he/she will be qualified to start coding with Python, and when some specific problem/error appear will have no alternative but to refer the  guide online or wherever. But these 10 drills are -I think- the essentials to begin.

And finally a disclaimer: Although I did all the problems of the current Dr. Chuck´s course correctly, I´m not sure if the included codes are perfect (it may be a preliminary attempt). If anyone finds an error, please tell me to congratulate him/her and correct it ¡Suerte!.

1 comentario:

  1. Very good tutorial to understand basics of Python.. It covers Helloworld, input name, variables etc.,

    You also can visit to know the important features of Python

    Python Training in Chennai

    ResponderEliminar