Monday 14 August 2017

Python Basics -1

The Origin of Python:
·      Python was created by Guido van Rossum in the late 1980’s.
·      Guido created Python after his experience (and some frustrations) with the ABC programming language.
·      The name “Python” comes from a British comedy group named Monty Python.

The Python REPL:
·      Python’s interpreter can be used interactively: when started from the Command line without specifying a script to run, the interpreter runs in interactive mode.
·      In the interactive mode, the interpreter waits for the user to type in expressions and statements, which it then evaluates and prints the resulting values. Then it goes right back to waiting for the next input from the user.
·      This mode of operation is called a REPL: read-eval-print-loop. It is a very useful property of the interpreter, as it facilitates and encour-ages quick experimentation, which speeds up both the learning and the development processes.

Numbers in Python:
Python supports three kinds of numbers: integers, floating point numbers, and complex numbers, with the usual arithmetic operators to manipulate them:

>>>           2 + 2   # +, -, * and / have usual meanings

             4

>>>           2 ** 3  # ** is the power/exponent operator

             8

>>>           _ + 2   # underscore => last computed result

            10

>>>           8 % 5   # % is the mod/remainder operator

             3

>>>           8 / 5   # integer division

            1

>>>           8.0 / 5 # force floating point division

            1.6



Strings in Python:
=============
A string is a series of characters, they are mostly used to display text.
To define a string simply type text between quotes.
Python accepts single, double and triple quotes.


String input and output:
To output text (string) to the screen:
s = "hello world"
print(s)

To get text from keyboard:
[Python 3.x]
name = input("Enter name: ")
print(name)

[Python 2.x]
name = raw_input("Enter name: ")
print(name)

String Comparison:
To test if two strings are equal use the equality operator (==).

#!/usr/bin/python
sentence = "The cat is brown"
q = "cat"
if q == sentence:
    print('strings equal')

To test if two strings are not equal use the inequality operator (!=)
#!/usr/bin/python
sentence = "The cat is brown"
q = "cat"
if q != sentence:
    print('strings equal')


String Slices:
A string is a series of characters, they are mostly used to display text.
To define a string simply type text between quotes.
Python accepts single, double and triple quotes.

String Index
Python indexes the characters of a string, every index is associated with a unique character. For instance, the characters in the string ‘python’ have indices:
String
String numbering
Characters in string

The 0th index is used for the first character of a string. Try the following:

#!/usr/bin/python
s = "Hello Python"
print(s)      # prints whole string
print(s[0])   # prints "H"
print(s[1]) # prints "e"

String Slicing
Given a string s, the syntax for a slice is:
s[ startIndex : pastIndex ]
The startIndex is the start index of the string. pastIndex is one past the end of the slice.
NOTE:
If you omit the first index, the slice will start from the beginning. If you omit the last index, the slice will go to the end of the string. For instance:

#!/usr/bin/python
s = "Hello Python"
print(s[0:2]) # prints "He"
print(s[2:4]) # prints "ll"
print(s[6:])  # prints "Python"

Example:
=======
foo = "Monty Python's Flying Circus"

#Print the middle of foo- slice from the 7th-1 character end at the 15th-1 character
print foo[6:14]

#Use a slice to get the first six characters
print foo[:6]
#>>> Monty

#Slice after the first six characters of foo
print foo[6:]
#>>> Python's Flying Circus

#Print everthing in foo
print foo[:]
#>>> Monty Python's Flying Circus

#Every second character
print foo[0:27:2]
#>>> MnyPto' ligCru

#The last character of foo
print foo[-1]
#>>> s

#The last two characters of foo
print foo[-2:]
#>>> us

#Everything but the last seven charachers of foo
print foo[:-7]
#>>> Monty Python's Flying


Python variables
Variables in Python (x,y,z). They can be used later in the program
Variables can hold numbers that you can use one or more times.

You can create variables in Python by just assigning some value to them. There is no need to “declare” variables:

>>>      a = 42  # This creates the variable ‘a’.

>>>      # NOTE: REPL does *not* print assignment results.

>>>      a + 18

     60


Numbers can be of one of these datatypes:
    integer (1,2,3,4)
    float (numbers behind the dot)
    boolean (True or False)

Numeric variables example:
x = 1
y = 1.234
z = True


You can output them to the screen using the print() function.
x = 1
y = 1.234
z = True

print(x)
print(y)
print(z)

Python supports arithmetic operations like addition (+), multiplication (*), division (/) and subtractions (-).

#!/usr/bin/env python
x = 3
y = 8
sum = x + y
print(sum)

More mathematical operations
User input

Python 3
Use the input() function to get text input, convert to a number using int() or float().
#!/usr/bin/env python
x = int(input("Enter x:"))
y = int(input("Enter y:"))
sum = x + y
print(sum)

Python 2 (old version)
You can also ask the user for input using the raw_input function:

#!/usr/bin/env python
x = int(raw_input("Enter x:"))
y = int(raw_input("Enter y:"))
sum = x + y
print(sum)


Python lists
List is a sequence and a basic data structure.   A list may contain strings (text) and numbers.  A list is similar to an array in other programming languages, but has additional functionality.

We define lists with brackets []. To access the data, these same brackets are used.
Example list usage:

#!/usr/bin/python
l = [ "Drake", "Derp", "Derek", "Dominique" ]
print(l)     # prints all elements
print(l[0])  # print first element
print(l[1])  # prints second element

Add/remove:
We can use the functions append() and remove() to manipulate the list.


#!/usr/bin/python
l = [ "Drake", "Derp", "Derek", "Dominique" ]
print(l)                        # prints all elements
l.append("Victoria")   # add element.
print(l)                        # print all elements
l.remove("Derp")       # remove element.
l.remove("Drake")     # remove element.
print(l)                       # print all elements.

Sort list:
We can sort the list using the sort() function.
#!/usr/bin/python
l = [ "Drake", "Derp", "Derek", "Dominique" ]
print(l)     # prints all elements
l.sort()     # sorts the list in alphabetical order
print(l)     # prints all elements

List in descending order, simply use the reverse() function.
#!/usr/bin/python
l = [ "Drake", "Derp", "Derek", "Dominique" ]
print(l)     # prints all elements
l.sort()    # sorts the list in alphabetical order
l.reverse() # reverse order.
print(l)     # prints all elements

If statements:
In Python we can define conditional statements, known as if-statements.
A block of code is executed if certain conditions are met.

Consider this application, it executes either the first or second code depending on the value of x.

#!/usr/bin/python
x = 3
if x < 10:
   print("x smaller than 10")
else:
   print("x is bigger than 10 or equal")

If you set x to be larger than 10, it will execute the second code block.   We use indentation (4 spaces) to define the blocks.

A little game:
A variable may not always be defined by the user, consider this little game:

age = 24

print "Guess my age, you have 1 chances!"
guess = int(raw_input("Guess: "))

if guess != age:
    print("Wrong!")
else:
    print("Correct")

Conditional operators
A word on conditional operators
Operator  Description
!=  not equal
==  equals
>  greater than
<  smaller than

Do not confuse the assignment operator (=) with the equals operator (==).
Nesting

The most straightforward way to do multiple conditions is nesting:

a = 12
b = 33

if a > 10:
    if b > 20:
        print("Good")

This can quickly become difficult to read, consider combining 4 or 6 conditions.  Luckily Python has a solution for this, we can combine conditions using the and keyword.

guess = 24
if guess > 10 and guess < 20:
    print("In range")
else:
    print("Out of range")

Sometimes you may want to use the or operator.

Functions:
A function is re-usable code that can be called anywhere in your program. Functions improve readability of your code: it’s easier for someone to understand code using functions instead of long lists of instructions.

On top of that, functions can be reused or modified which also improve testability and extensibility.

We use this syntax to define as function:

def function(parameters):
    instructions
    return value

The def keyword tells Python we have a piece of reusable code (A function). A program can have many functions.
Practical Example

We can call the function using function(parameters).

#!/usr/bin/python

def f(x):
    return(x*x)

print(f(3))

Output:
9

The function has one parameter, x. The return value is the value the function returns. Not all functions have to return something.
Parameters

 We can pass multiple variables:

#!/usr/bin/python

def f(x,y):
    print('You called f(x,y) with the value x = ' + str(x) + ' and y = ' + str(y))
    print('x * y = ' + str(x*y))

f(3,2)

Output:
You called f(x,y) with the value x = 3 and y = 2
x * y = 6

Global and Local variables
There are two types of variables: global variables and local variables.
A global variable can be reached anywhere in the code, a local only in the scope.

global-local-variable
A global variable (x) can be reached and modified anywhere in the code, local variable (z) exists only in block 3.

Local variables can only be reached in their scope.
The example below has two local variables: x and y.

def sum(x,y):
    sum = x + y
    return sum

print(sum(8,6))

The variables x and y can only be used inside the function sum, they don’t exist outside of the function.
Local variables cannot be used outside of their scope, this line will not work:

print(x)

Global variables
A global variable can be used anywhere in the code.
In the example below we define a global variable z
z = 10
def afunction():
    global z
    print(z)

afunction()
print(z)

The global variable z can be used all throughout the program, inside functions or outside.
A global variable can modified inside a function and change for the entire program:

z = 10

def afunction():
    global z
    z = 9

afunction()
print(z)

After calling afunction(), the global variable is changed for the entire program.
Exercise

Local and global variables can be used together in the same program.
Try to determine the output of this program:

z = 10

def func1():
    global z
    z = 3

def func2(x,y):
    global z
    return x+y+z

func1()
total = func2(4,5)
print(total)

Scope
Scope variables can only reach the area in which they are defined, which is called scope. Think of it as the area of code where variables can be used. Python supports global variables (usable in the entire program) and local variables.

By default, all variables declared in a function are local variables. To access a global variable inside a function, it’s required to explicitly define ‘global variable’.

Example
Below we’ll examine the use of local variables and scope. This will not work:

#!/usr/bin/python
def f(x,y):
    print('You called f(x,y) with the value x = ' + str(x) + ' and y = ' + str(y))
    print('x * y = ' + str(x*y))
    z = 4 # cannot reach z, so THIS WON'T WORK

z = 3
f(3,2)

but this will:

#!/usr/bin/python

def f(x,y):
    z = 3
    print('You called f(x,y) with the value x = ' + str(x) + ' and y = ' + str(y))
    print('x * y = ' + str(x*y))
    print(z) # can reach because variable z is defined in the function

f(3,2)

Let’s examine this further:

#!/usr/bin/python
def f(x,y,z):
    return x+y+z # this will return the sum because all variables are passed as parameters
sum = f(3,2,1)
print(sum)

Calling functions in functions
We can also get the contents of a variable from another function:

#!/usr/bin/python

def highFive():
    return 5

def f(x,y):
    z = highFive() # we get the variable contents from highFive()
    return x+y+z # returns x+y+z. z is reachable becaue it is defined above

result = f(3,2)
print(result)

If a variable can be reached anywhere in the code is called a global variable. If a variable is known only inside the scope, we call it a local variable.

Loops: For loop, while loop
Code can be repeated using a loop. Lines of code can be repeated N times, where N is manually configurable. In practice, it means code will be repeated until a condition is met. This condition is usually (x >=N) but it’s not the only possible condition.

Python has 3 types of loops: for loops, while loops and nested loops.

For loop
We can iterate a list using a for loop
#!/usr/bin/python
items = [ "Abby","Brenda","Cindy","Diddy" ]
for item in items:
    print(item)

The for loop can be used to repeat N times too:

#!/usr/bin/python
for i in range(1,10):
    print(i)

While loop

If you are unsure how many times a code should be repeated, use a while loop.
For example,

correctNumber = 5
guess = 0

while guess != correctNumber:
    guess = input("Guess the number: ")

    if guess != correctNumber:
        print('False guess')

print('You guessed the correct number')

Nested loops

We can combine for loops using nesting. If we want to iterate over an (x,y) field we could use:

#!/usr/bin/python

for x in range(1,10):
    for y in range(1,10):
        print("(" + str(x) + "," + str(y) + ")")

Nesting is very useful, but it increases complexity the deeper you nest.


Python range
The range() function returns of generates a sequence of numbers, starting from the lower bound to the upper bound.
range(lower_bound, upper_bound, step_size)
    lower_bound: The starting value of the list.
    upper_bound: The max value of the list, excluding this number.
    step_bound: The step size, the difference between each number in the list.

The lower_bound and step_size parameters are optional. By default the lower bound is set to zero, the incremental step is set to one. The parameters must be of the type integers, but may be negative.
python range

range implementation difference
This distinction won’t usually be an issue. The range() is implemented slightly different in the Python versions:

    Python 2.x: The range() function returns a list.
    Python 3.x: The range() function generates a sequence.

range in python 2.7
A call to range(5) will return: 0,1,2,3,4.

>>> range(5)

A call to range(1,10) returns: 1,2,3,4,5,6,7,8,9

>>> range(1,10)

Calling range(0,10,2) returns: 0,2,4,6,8

>>> range(0,10,2)

range in python 3
To generate a list using range, add the list function

>>> list(range(5))

We can use all parameters (lower bound, upper bound, step)

>>> list(range(0,10,2))
[0, 2, 4, 6, 8]

python 2 implementation
This version of range() allocates computer memory and also populates the computer memory behind the scenes. For large ranges, this is implementation is not very efficient.

Usually you won’t have any issues with the Python2 implementation of range() but if you use large numbers (millions of items) you could run into issues.

Python tuple:
The tuple data structure is used to store a group of data.  The elements in this group are separated by a comma. Once created, the values of a tuple cannot change.
An empty tuple in Python would be defined as:
tuple = ()
A comma is required for a tuple with one item:
tuple = (3,)

The comma for one item may be counter intuitive,  but without the comma for a single item, you cannot access the element.  For multiple items, you do not have to put a comma at the end.  This set is an example:

personInfo = ("Diana", 32, "New York")

The data inside a tuple can be of one or more data types such as text and numbers.
Data access

To access the data we can simply use an index. As usual, an index is a number between brackets:

#!/usr/bin/env python
personInfo = ("Diana", 32, "New York")
print(personInfo[0])
print(personInfo[1])

If you want to assign multiple variables at once, you can use tuples:
#!/usr/bin/env python
name,age,country,career = ('Diana',32,'Canada','CompSci')
print(country)

On the right side the tuple is written. Left of the operator  equality operator are the corresponding output variables.
Append to a tuple in Python

If you have an existing tuple, you can append to it with the + operator.  You can only append a tuple to an existing tuple.

#!/usr/bin/env python

x = (3,4,5,6)
x = x + (1,2,3)
print(x)
 

Python dictionaries:
A dictionary can be thought of as an unordered set of key: value pairs.
A pair of braces creates an empty dictionary: {}.  Each element can maps to a certain value.  An integer or string can be used for the index. Dictonaries do not have an order.

Dictionary example
Let us make a simple dictionary:

#!/usr/bin/python

words = {}
words["Hello"] = "Bonjour"
words["Yes"] = "Oui"
words["No"] = "Non"
words["Bye"] = "Au Revoir"

print(words["Hello"])
print(words["No"])

Output:

Bonjour
Non

We are by no means limited to single word definitions in the value part. A demonstration:

#!/usr/bin/python
dict = {}
dict['Ford'] = "Car"
dict['Python'] = "The Python Programming Language"
dict[2] = "This sentence is stored here."

print(dict['Ford'])
print(dict['Python'])
print(dict[2])

Output:

Car
The Python Programming Language
This sentence is stored here.

Manipulating the dictionary

We can manipulate the data stored in a dictionairy after declaration.  This is shown in the example below:

#!/usr/bin/python
words = {}
words["Hello"] = "Bonjour"
words["Yes"] = "Oui"
words["No"] = "Non"
words["Bye"] = "Au Revoir"

print(words)           # print key-pairs.
del words["Yes"]       # delete a key-pair.
print(words)           # print key-pairs.
words["Yes"] = "Oui!"  # add new key-pair.
print(words)           # print key-pairs.

Output:

{'Yes': 'Oui', 'Bye': 'Au Revoir', 'Hello': 'Bonjour', 'No': 'Non'}
{'Bye': 'Au Revoir', 'Hello': 'Bonjour', 'No': 'Non'}
{'Yes': 'Oui!', 'Bye': 'Au Revoir', 'Hello': 'Bonjour', 'No': 'Non'}


Datatype casting
Python determines the datatype automatically, to illustrate:
x = 3
y = "text"
It finds x is of type integer and y of type string.
Functions accept a certain datatype. For example, print only accepts the string datatype.
If you want to print numbers you will often need casting.
In this example below we want to print two numbers, one whole number (integer) and one floating point number.

x = 3
y = 2.15315315313532

print("We have defined two numbers,")
print("x = " + str(x))
print("y = " + str(y))

We cast the variable x (integer) and the variable y (float) to a string using the str() function.

What if we have text that we want to store as number? We will have to cast again.

a = "135.31421"
b = "133.1112223"

c = float(a) + float(b)
print(c)

In the example above we cast two variables with the datatype string to the datatype float.
Conversion functions

To convert between datatypes you can use:
Function  Description
int(x)  Converts x to an integer
long(x)  Converts x to a long integer
float(x)  Converts x to a floating point number
str(x)  Converts x to an string. x can be of the type float. integer or long.
hex(x)  Converts x integer to a hexadecimal string
chr(x)  Converts x integer to a character
ord(x)  Converts character x to an integer


Random numbers
Using the random module, we can generate pseudo-random numbers. The function random() generates a random number between zero and one [0, 0.1 .. 1].  Numbers generated with this module are not truly random but they are enough random for most purposes.

Random number between 0 and 1.
We can generate a (pseudo) random floating point number with this small code:

from random import *
print random()     # Generate a pseudo-random number between 0 and 1.

Generate a random number between 1 and 100
To generate a whole number (integer) between one and one hundred use:

from random import *

print randint(1, 100)    # Pick a random number between 1 and 100.

This will print a random integer. If you want to store it in a variable you can use:

from random import *

x = randint(1, 100)    # Pick a random number between 1 and 100.
print x

Random number between 1 and 10
To generate a random floating point number between 1 and 10 you can use the uniform() function

from random import *

print uniform(1, 10)

Picking a random item from a list

Fun with lists
We can shuffle a list with this code:

from random import *

items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
shuffle(items)
print items

To pick a random number from a list:

from random import *

items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

x = sample(items,  1)   # Pick a random item from the list
print x[0]

y = sample(items, 4)    # Pick 4 random items from the list
print y

We can do the same thing with a list of strings:

from random import *

items = ['Alissa','Alice','Marco','Melissa','Sandra','Steve']

x = sample(items,  1)   # Pick a random item from the list
print x[0]

y = sample(items, 4)    # Pick 4 random items from the list
print y




No comments:

Post a Comment

Note: only a member of this blog may post a comment.