Learning Python the Hard Way :)

After getting the RasPi, I was all the more excited to learn Python. I started it from this link
http://learnpythonthehardway.org/book/

I’m currently in Exercise 22 which asks us to rewind what we’ve learned so far. So I made these notes and will post here for my quick reference.

# Ex 22

Asks to go back and revist all the symbols and words and understand what they all do..

I’m’ gonna begin from ex1

———
Ex 1
———

print — This will print anything provided inside the brackets
ex: print(“This will come on the screen”)
ex1: a = 10;
print(“A is %d” %a);
or
print(“A is”, a);

——–
Ex 2
——–

In this excersise, we learn how to give single line and multi-line comments

Use the Pound symbol # to give single line comment as is now

Use three double quotes to start a multi line comment
“””
Use the same qutoes to end the multi line comment
“””

———-
Ex 3
———-
In this excersise, we learnt performing some basic arithmetic operations and also learnt to compare them

for example,
a = 5;
b = 4;
print(a==b); will print False

Also learnt were >, <, >=, <=, +, -, /, *, and %

Another derviation derieved was if any one of the operand is a float, the result will also be a float. (eg a = 10, b = 5.0, then a+b = 15.0)

———-
Ex 4
———-

In this exercise, we learnt how to print variables values

ex a = 10, b = 10, e = a+b;
print(“A + B = “, e);
or
print(“A + B = %d” %e);

%d = used for Digit
%f = used for float
%s = used for String
%r = used for any variable type irrespective of type

———
Ex 5
———

This example included more features on showing variables etc.

round(float_number) will give you the rounded value
eg: round(12.54) = 13 (which will be an int value πŸ™‚ )

Also, to show multi variables, club then in brackets

ex:
a = 10
b = 5
c = 6
print(“A = %d B = %d C = %d” %(a,b,c))
——–
Ex 6
——–

This exercise illustrates the many ways of printing variable values

For example:
X = “Python Rocks”
Z = 2
print(X, “And Number 2:”, Z);

We can even add two strings by using the + operator

A = “My Name is ”
B = “Anwaar”
print(A+B)
Will output: My Name is Anwaar

This is something I felt is real cool:

question = “Python is Awesome? %s” # Use %r if you wanna show as ‘True’
ans = “True”

print(question %ans);
Output: Python is Awesome? True

———
Ex 7
———

More printing stuff.

dot = “.” * 15
print(dot)
Output: ……………

You can add chars together to form meaningful words

a = “S”
b = “y”
c = “e”
d = “d”

print(a+b+c+d), # Buy placing a comma, the subsequent Print statement was printed on a new line
print(a+d)

———
Ex 8
———

formatter isn’t working in Python 3 which I’m currently on.

However, lets see what it has to offer:

formatter = “%r %r %r %r”
print formatter % (1, 2, 3, 4)

Output: ?
If you’re reading this and know it, please comment the outut.

———
Ex 9
———

This chapter introduced a multi line print statement that is controlled by “”” quotes (3 of them) “””

Example:
print(“”” You begin a statememt
like this and continue to the next line
and this won\’t end untill you close it with another three
quotes like “””)

Output:
You begin a statememt
like this and continue to the next line
and this won’t end untill you close it with another three
quotes like

This is very straight forward:

days = “Monday\nTuesday\nWednesday”;
print (days);

Output:
Monday
Tuesday
Wednesday

———
Ex 9
———

Here we learnt about the many available escape chars
Notable among which are:

\n – New Line
\t – Tab
\\ – Backslash
\’ – Single Quote
\” – Double Quote
\r – Return Line
\a – Audible Bell # This was something I enjoyed πŸ™‚

Another nice concept was introduced here: While loop

This was a small example

#Infinite Loop, remember, proper indentation is very important in Python
# Mind that w in while is lower case while T in true is uppercase
Also, there is a colon: after the while and the for condition which I missed out and had some nice errors

while True:
for i in [“A”, “B”, “C”]:
print(“%s”%i)

Output:
A
B
C
A
B
C
A
B
C
A
B
C
A
B
C
A
B
C
A
B
C
A
B
and that goes on infinitely. To stop it use, Ctrl + C

——–
Ex 11
——–

This one was a nice one as we were asking user inputs.
Inputs in Python gets very interesting and fun. Lets explore:

Note: All inputs in Python are treated as strings. If working on numbers, you need to convert it using the int(string)
or float(string) functions

input() is used to input in values from the keyboard.

Lets see an example:

print(“Enter your Name: “);
name = input();
print(“%s, you are human” %name);

Output:
Enter your Name:
Syed Anwaarullah
Syed Anwaarullah, you are human
If you noticed, the input on the next line places the input cursor on the next line.

This can be shortened by invoking the input() with an inbuilt message like:

age = input(“Your age please: “);

In order to convert the string age into a number for you ti use further, use int()

age = int(input(“Your Age Please: “));
if(age>19):
print(“Old Man”)
else:
print(“Kiddie”)

Output:
C:\py>python test.py
Your Age Please: 19
Kiddie

C:\py>python test.py
Your Age Please: 45
Old Man

——–
Ex 12
——–
This excersise introduced to the shortened version of input taking which we saw in Ex 11

——–
Ex 13
——–

This is gonna be a new topic: Accepting command line arguments πŸ™‚

I was fascinated working on this as I’ve used many scripts in BackTrack OS and have passed arguments. Though I worked on args in C, C++, Java and Linux, Python seemed so easy πŸ™‚

Here, you need to first import the argv (library) from the sys (package)

from sys import argv

Then Simply,

scriptName, arg1, arg2 = argv;
print(“Script Name: “, scriptName);
print(“Argument 1 = “, arg1);
print(“Argument 2 = “, arg2);

will Output:

C:\py>python test.py Argu1 Argu2
Script Name: test.py
Argument 1 = Argu1
Argument 2 = Argu2

As simple as that πŸ™‚

——–
Ex 14
——–

This exercise merged Prompting and Arg passing in a single example.
In the example shown, they first took the user name as an arg and kept prompting him (by printing his name) to enter some data

This looked cool, especially the ‘>’ prompt symbol, making it look awesome!

Let’s try a small one:

from sys import argv
scriptname, username = argv
prompt = ‘>’
print(“Please enter your age %s” %username)
age = int(input(prompt))
print(“Gosh, you\’re %d years old!!!” %age);

And here’s the Output:

C:\py>python test.py Syed
Please enter your age Syed
>45
Gosh, you’re 45 years old!!!

——–
Ex 15
——–
Here come’s another interesting topic: File Operations πŸ™‚

use the open() to open a file while also assigning it another var that would then be used to read the contents of the file.
Simple example follows

from sys import argv
script, file = argv
txt = open(file);
print(“File Contents:\n\n”)
print(txt.read());
txt.close();

And the output will be:

C:\py>python test.py sample.txt
File Contents:
Line 1
Line 2
Line 3
This is a new addition.
We hope that this will also be copied to the other section.
I’m not modifying the section and not trying to save to see if it still copies t
he file.
Ans: It still does πŸ™‚

Note: You can also give the full path name. The reason it worked here was because the sample.txt file was in the sample folder as the python file.

This also works:
C:\py>python test.py C:\py\sample.txt

# Here, we’re prompting the user to enter the file name and then again opening it’s content
print(“Type the File Name again: “);
file_again = input(“> “);
txt_again = open(file_again);
print(txt_again.read());
txt_again.close();

Note: If the file is not present, you’ll get this error:
C:\py>python ex15.py sample.tx
Traceback (most recent call last):
File “ex15.py”, line 6, in <module>
txt = open(filename)
FileNotFoundError: [Errno 2] No such file or directory: ‘sample.tx’

——-
Ex 16
——-
We’ll now introduce writing into files.

filename = input(“Enter File Name: “);
file = open(filename, ‘w’); # Open file in write mode
file.write(input(“Text that should go inside the file:”));
file.close();
and the output should look like:

C:\py>python test.py
Enter File Name: input.txt
Text that should go inside the file:This will be written to the file. Thanks

C:\py>type input.txt
This will be written to the file. Thanks

Note: In this simple example, the file will be overwritten everytime with our input data.
file.truncate() will truncate the file contents.

——–
Ex 17
——–

This exercise will introduce us in copying file’s data to each other

In this example, a new lib exists has been introduced that checks for the availability of file and is available in the os.path package.

Lets get started:

from os.path import exists
source = input(“Input File: “);
destination = input(“Destination File: “);

#Check if Output File exists
print(destination, “file exists: %s” %exists(destination))

#Now open the input file
in_file = open(source);

#Open the output file in write mode
out_file = open(destination, ‘w’);
out_file.write(in_file.read());
out_file.close();
in_file.close();

Note:
There was another thing that was introduced here about getting the length of the file
eg:
in_file = open(source);
indata = in_file.read();
print(“File Length in Bytes: %r” %len(indata)) # This will print the length of the file in bytes

———
Ex 18
———

This exercise introduces using functions in Python

Below example illustrates defining and calling a function:
def sample_function():
print(“This is a function”)
sample_function();

The above code will simply print the string on the screen

Lets now pass arguments in the function.

def two_chars(*args):
arg1, arg2 = args
print(“Arg1: “, arg1, “\nArg2: “, arg2);
two_chars(‘A’, ‘B’)

The output of the above would be:
C:\py>python test.py
Arg1: A
Arg2: B

We can directly use arg variables in the function instead of pointer as illustrated below:

def two_chars(arg1, arg2):
print(“Arg1: “, arg1, “\nArg2: “, arg2);
two_chars(‘A’, ‘B’)

The output will still be the same as earlier.

———
Ex 19
———

This introduces the concept of doing arithmetic operations and then passing in the arguments to the functions. This is illustrated below:

def add(a,b):
print(“A + B is: %d” %(a+b));
add(1,2);
add(3*3, 7-2);
add(int(input(“Enter first Number: “)), int(input(“Enter Second Number: “)));

The output of the above code is:
C:\py>python test.py
A + B is: 3
A + B is: 14
Enter first Number: 7
Enter Second Number: 7
A + B is: 14

——–
Ex 20
——–

This exercise deals with files and functions.
In this example we’re trying to show a particular line within a file:
Also introuced is file.rewind()
Essentially, by using the file.readline(), we’re just reading one line. Subsequent use of this will return the next line and so forth.

def print_one_line_at_a_time(filedata):
print(filedata.readline())

filedata = open(input(“Enter file name: “))

print_one_line_at_a_time(filedata);
print_one_line_at_a_time(filedata);

And the output of the above code will be:

C:\py>python test.py
Enter file name: test.py
# This is only to test any new things across Py

def print_one_line_at_a_time(filedata):

Notice the empty newline in between πŸ™‚

———-
Ex 21
———-

Returning values from functions. This is very straightforward and will be illustrated with the below example:

def add_num(a,b):
return(a+b);
print(“5 + 5 = “, add_num(5,5))

———————————————–

And that completes our revision. Another 30 exercises to go. Will post a summary of them once we’re done.

Cheers!!!

Advertisements

Author: Anwaarullah

Designer, Developer, Maker, Speaker, Educator and Dreamer. β™₯ Tinkering with Embedded, Android, Open Soft/Hard/Firm ware, Robotics and 3D Printer. Talk to me at syed {Shift+2} anwaarullah dash com

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s