CLI (Command Line interface) - All programs have been tested using Python 3.4.2

Further learning

 

Tutorial 1: Print

# Single line comments are written by starting the line with hash symbol
"""
Multiline comment is written using triple Double quotes
The following program will show different ways to use 'print' command
"""
print ("Hello World") hwStr = 'Hello World' print (hwStr) print (hwStr[:5]*3) # up to fifth position from start and repeat three times print ("{0} {0}".format(hwStr[:5])) # up to fifth position from start, repeat twice with space print ("{0} {1}".format(hwStr[:5], hwStr[6:])) # from sixth position till the end print ( 'Can I print \"%s\"?' %hwStr) # used escape character """
You will have to import 'math' to use inbuilt mathematical functions.
'import' command can be used anywhere within the program and
it does not have be on the first line.
but it is a custom to write it in the beginning of the program which
makes it easier for other developers to understand the program.
""" import math print('%s, The value of PI is approximately %5.3f.' % (hwStr, math.pi)) # display in a space of 5
print('%s, The value of PI is approximately %10.3f.' % (hwStr, math.pi)) # display in a space of 10
bigNumber = 123456789.123456789
print('Big number in 3 decimal places is approximately %.3f.' % (bigNumber))

The output of this program is

Hello World
Hello World
HelloHelloHello
Hello Hello
Hello World
Can I print "Hello World"?
Hello World, The value of PI is approximately 3.142.
Hello World, The value of PI is approximately      3.142.
Big number in 3 decimal places is approximately 123456789.123.

 

Tutorial 2: Getting User Input

 

print ("Hello")
var1 = input("Enter a number:")
print ("you have entered " + var1)

 

The output of this program is

 

Hello
Enter a number:3
you have entered 3

 


 

Tutorial 3: How to print without quotes?

 

print ("Hello"),
print (" World")

var1 = ("World")
print ("Hello " + var1)

 

The output of this program is

 

Hello
 World
Hello World

Notice that the comma on the end of first line of code does not force the second line of code to be printed with the output of the first line of code. This was possible in Python 2.7 but not possible any more in Python 3

 


 

Tutorial 4: Type casting

varAge = input("Enter your age  please = ")
varAge = int(varAge) + 5
print ("Your age after five years will be " + str(varAge))

 

The output of this program is

 
Enter your age  please = 10
Your age after five years will be 15

 


 

Tutorial 5: Basic Maths operations

SOON

 

 

 

The output of this program is

 

 

 


 

Tutorial 6: Further Maths

SOON

 

 

 

The output of this program is

 

 

 


 

Tutorial 7: IF ELSE

SOON

 

 

 

The output of this program is

 

 

 


 

Tutorial 8: IF ELIF ELSE

SOON

 

 

 

The output of this program is

 

 

 


 

Tutorial 9: FOR Loop

SOON

 

 

 

The output of this program is

 

 

 


 

Tutorial 10: WHILE Loop

SOON

 

 

 

The output of this program is

 

 

 


 

Tutorial 11: Passing parameters across files

SOON

 

 

 

The output of this program is

 

 

 


 

Tutorial 12: Regular Expressions

Regular expressions are a small programming language built within Python and made available through the 're' module. Using this, you can find a substring within another string. You can also use REs to modify a string or to split it apart in different ways.

Some characters are special metacharacters. They signal that some out-of-the-ordinary thing should be matched, or they affect other portions of the RE by repeating them or changing their meaning. Here’s a complete list of the metacharacters

. ^ $ * + ? { } [ ] \ | ( )

[ and ] are used to specify a character class, which is a set of characters that will be matched. Characters can be listed individually, or as a range. For example, [abc] will match any of the characters a, b, or c; this is the same as [a-c]. If you wanted to match only lowercase letters, use [a-z].

Metacharacters are not active inside classes. For example, [akm$] will match any of the characters 'a', 'k', 'm', or '$'; '$' is usually a metacharacter, but inside a character class it is not special any more.

You can match the characters not listed within the class by complementing the set. This is indicated by including a '^' as the first character of the class; '^' outside a character class will simply match the '^' character. For example, [^5] will match any character except '5'.

The backslash, '\', can be followed by various characters to signal various special sequences. It is also used to escape all the metacharacters so you can still match them in patterns; for example, if you need to match a [ or \, you can precede them with a backslash to remove their special meaning: \[ or \\.

Some of the special sequences beginning with '\' represent predefined sets of characters that are often useful, such as the set of digits, the set of letters, or the set of anything that isn’t whitespace.

\d
Matches any decimal digit; this is equivalent to the class [0-9].
\D
Matches any non-digit character; this is equivalent to the class [^0-9].
\s
Matches any whitespace character; this is equivalent to the class [ \t\n\r\f\v].
\S
Matches any non-whitespace character; this is equivalent to the class [^ \t\n\r\f\v].
\w
Matches any alphanumeric character; this is equivalent to the class [a-zA-Z0-9_].
\W
Matches any non-alphanumeric character; this is equivalent to the class [^a-zA-Z0-9_].

These sequences can be included inside a character class. For example, [\s,.] is a character class that will match any whitespace character, or ',' or '.'.

The metacharacter for repeating things that we’ll look at is *. * doesn’t match the literal character *; instead, it specifies that the previous character can be matched zero or more times, instead of exactly once. For example bob*y will match boy (0 b characters), boby (1 b), bobby (2 b characters), and so on.


import re
hwStr = 'Hello World'
pattern = re.compile("ello")
print (pattern.match(hwStr)) # No match as "ello" is not at the start of "Hello World". print (pattern.match(hwStr, 1)) # Match as "ello" starts at 2nd character of "Hello World".
matchObject = pattern.match(hwStr, 1) print (matchObject) print (matchObject.group()) print (matchObject.start(), matchObject.end()) print (matchObject.span())
# search will look throughout the string
searchObject = pattern.search(hwStr) print (searchObject) print (searchObject.group()) print (searchObject.start(), searchObject.end()) print (searchObject.span()) if searchObject: print('Match of', searchObject.group(),' was found at position', searchObject.start()) else: print('No match')
p = re.compile('\d+') findAllList = p.findall('4 lollies, 2 chocolates, 3 cakes') print (findAllList) iterator = p.finditer('4 lollies, 2 chocolates, 3 cakes') for match in iterator: print(match.span()) print (findAllList)
m = re.match("(\w+\ )",hwStr) m2 = m.group(1) * 2 print (m2)

p = re.compile(r'\W+') p2 = re.compile(r'(\W+)') print (p.split('This... is a test.')) print (p2.split('This... is a test.'))

The output of this program is

 

None
<_sre.SRE_Match object; span=(1, 5), match='ello'>
<_sre.SRE_Match object; span=(1, 5), match='ello'> ello 1 5 (1, 5) <_sre.SRE_Match object; span=(1, 5), match='ello'> ello 1 5 (1, 5) Match of ello was found at position 1 ['4', '2', '3'] (0, 1) (11, 12) (25, 26) ['4', '2', '3'] Hello Hello ['This', 'is', 'a', 'test', ''] ['This', '... ', 'is', ' ', 'a', ' ', 'test', '.', '']

Further learning

 


 

Tutorial 13: Sorting

This is very useful in certain situations so let us try to figure out different ways of sorting.

aList = [5, 2, 3, 1, 4]
print (sorted(aList))
aList2 = sorted(aList)
print (aList) # the original list remains as it is
print (aList2) # the sorted list 
aList = [5, 2, 3, 1, 4]
aList.sort()
print (aList)

student_tuples = [
    ('john', 'A', 15),
    ('jane', 'B', 12),
    ('dave', 'B', 10),
]
print (sorted(student_tuples, key=lambda student: student[2]))   # sort by age

from operator import itemgetter
print (sorted(student_tuples, key=itemgetter(1,2))) # sorting on more than one field
print (sorted(student_tuples, key=itemgetter(2), reverse=True)) #descending order

# let us try another method; for that we need to make a class
class Student:
        def __init__(self, name, grade, age):
            self.name = name
            self.grade = grade
            self.age = age
        def __repr__(self):
            return repr((self.name, self.grade, self.age))
student_objects = [
    Student('john', 'A', 15),
    Student('jane', 'B', 12),
    Student('dave', 'B', 10),
]

print (sorted(student_objects, key=lambda student: student.age) )  # sort by age
from operator import attrgetter
print (sorted(student_objects, key=attrgetter('age'))) 

 

The output of this program is

 

[1, 2, 3, 4, 5]
[5, 2, 3, 1, 4]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
[('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]
[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
 

Future Learning


 

I think this is enough to get the students started and now they can start experimenting on their own. I will make more tutorial on further topics and keep adding to this space. If you would like a tutorial on a particular topic, feel free to send me an email.