Copyright © 2017 IBM Cognitive Class. This notebook and its source code are released under the terms of the MIT License.

Why Python:

  • The most popular, high level, open source programming language
  • Powerful
  • Fast
  • Dynamic programming
  • Interactive
  • Object-oriented
  • Easy to learn
  • Complete library for fast all purpose (analytics, gamimg, web, robots etc)

Module 1 - Python Basics

-YOUR FIRST PROGRAM:

In [40]:
print("Hello Python 101")

#as comment
#print("Hello Python 101")
Hello Python 101

QUICK PRACTICE LAB

QUESTION 1

Using the Practice Lab find the result of executing print("Hello\nWorld!") statement

In [10]:
print("Hello\nWorld!")
Hello
World!

QUESTION 2

what is the output of executing the following statement: # print('Hello World!')

In [14]:
# print('Hello World!')

-TYPES:

1: Integer -> Int

2.34 : Real number -> Float

"cevi": Words -> Str

TRUE/FALSE: Boolean -> Bool

QUICK PRACTICE LAB

QUESTION 1

What is the type of the following int(1.0)?

In [21]:
int(1.0)
Out[21]:
1

QUESTION 2

Enter the code to convert the number 1 to a Boolean ?

In [25]:
bool(1)
Out[25]:
True
In [26]:
bool(0)
Out[26]:
False

-EXPRESSIONS AND VARIABLES:

Operators

In [28]:
40+40+100
Out[28]:
180
In [29]:
10-50
Out[29]:
-40
In [30]:
10*8
Out[30]:
80
In [31]:
20/5
Out[31]:
4.0

Variables

In [34]:
my_variable=100
In [35]:
print(my_variable)
100
In [36]:
total=1+2+19
In [37]:
print(total)
22
In [38]:
my_variable2=total/my_variable
In [39]:
print(my_variable2)
0.22

-Lab-Write your first Python code!

Python - Writing Your First Python Code!

Welcome!

By the end of this notebook, you will have learned the basics of Python, including writing some basic commands, understanding object types, and some simple operations!

Table of Contents


Your First Program in Python

A statement or expression is an instruction the computer will run or execute. Perhaps the simplest program you can write is to print a statement in Python.

**Tip**: To *execute* the Python code in the grey code cell below, **click on it and press Shift + Enter**.

Python 3

How do we know that Python 3 is running? Take a look in the top-right hand corner of this notebook. You should see "Python 3"!

Writing comments in Python

In addition to writing code, note that it is customary to comment your code to help describe what it does. Not only does this help other people understand your code, it can also serve as a reminder to you of what your code does. (This is especially true when you write some code and then come back to it weeks or months later.)

To write comments in your Python code, use the hash symbol (#) before writing your comment. When you run the code Python will ignore everything after the # in that line.

In [55]:
print('Hello Python 101') 

#this my comment
#print('Hi')
Hello Python 101

Great! After executing the cell above, you should notice that "this is my comment did not appeared in the output, because it was a comment (and thus ignored by Python). The second line was also not executed because print('Hi') was preceded by a hash symbol (#) as well!

Errors in Python

Before continuing, it's important to note when things go wrong in Python, and we cause errors.

There are many kinds of errors, and you do not need to memorize the various types of errors. Instead, what's most important is know what the error messages mean.

For example, if you spell print as frint, you will get an error message.

In [60]:
frint("Hello World!")
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-60-cbc42dbb0087> in <module>()
----> 1 frint("Hello World!")

NameError: name 'frint' is not defined

The error message tells you (1) where the error occurred, and (2) what kind of error it was. Here, Python attempted to run the function frint, but could not determine what frint -- since it is undefined.

Does Python know the error in the script before you run it?

No, Python is naive! Python will try to run the code line-by-line, and it will stop if it runs into an error.

In [64]:
print("This will be printed")
frint("This will cause an error")
print("This will NOT be printed")
This will be printed
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-64-aa3f0d14d353> in <module>()
      1 print("This will be printed")
----> 2 frint("This will cause an error")
      3 print("This will NOT be printed")

NameError: name 'frint' is not defined

More on errors later on in this course!

Exercise: Your First Program

Using the print() function, print out the phrase: "hello world"

In [69]:
print("hello world!")
hello world!
In [70]:
print("Hello World") #print Hello World
Hello World

Types of objects in Python

You can have many different object types in Python, let's start with strings, integers and floats. Anytime you write words (text) in Python, you're using character strings (strings for short). Numbers, on the other hand, depend: numbers can be integers (like -1, 0, 100) or floats, which are real numbers (like 3.14, -42.0).

<a,align = "center"><img src = "https://ibm.box.com/shared/static/8zp0t4oh7kuzleudrszhkqukcup1708f.png" width = 600></a>

The following chart summarizes three data types for the last examples, the first column indicates the expression the second column indicates the data type

In [75]:
11 #integer
Out[75]:
11
In [76]:
2.14 #float
Out[76]:
2.14
In [77]:
"Hello Python 101" #character string
Out[77]:
'Hello Python 101'

We can see the actual data type in python by using the type() command

In [79]:
type(12)
Out[79]:
int
In [80]:
type(2.14)
Out[80]:
float
In [81]:
type("Hello Python 101")
Out[81]:
str

Using the type() function, check the object type of 12.0?

In [83]:
type(12.0)
Out[83]:
float

Integers

Here are some integers, integers can be negative or positive:

<a align = "center"><img src = "https://ibm.box.com/shared/static/19iqm3q5pvxzuwa22d5ihxcr6eftjl48.png" width = 600></a>

We can verify some of the above examples using the type command:

In [88]:
type(-1)
Out[88]:
int
In [89]:
type(4)
Out[89]:
int
In [90]:
type(0)
Out[90]:
int

Floats

Floats are real numbers; they include the integers but also "numbers in-between the integers". Consider the numbers between 0 and one we can select numbers in-between them, these numbers are floats. Similarly, consider the numbers between 0.5 and 0.6. We can select numbers in-between them, these are floats as well. We can continue the process, zooming in for different numbers, of course, there is a limit, but it is quite small.

We can verify some of the above examples using the type command:

In [94]:
type(1.0)
Out[94]:
float
In [95]:
type(0.5)
Out[95]:
float
In [97]:
type(0.56)
Out[97]:
float

Converting from one object type to a different object type

You can change the type of the object in Python; this is called typecasting. For example, you can convert an integer into a float, as in 2 to 2.0.

In [101]:
type(2) #verify that this is an integer
Out[101]:
int

Converting to float:

In [104]:
float(2)
Out[104]:
2.0
In [105]:
type(float(2))
Out[105]:
float

Converting to integer:

Nothing really changes. If you cast a float to an integer, you must be careful. For example, if you cast the float 1.1 to 1 you will lose some information :

In [108]:
int(1.1)
Out[108]:
1

Converting from strings to integers/floats:

If a string contains an integer value, you can convert it to an integer:

In [111]:
int('1')
Out[111]:
1

You can also convert strings containing float values into float objects

In [113]:
float('1.2')
Out[113]:
1.2

However, if we attempt to convert a string that contains a non-numerical value, we get an error:

In [121]:
int("A")
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-121-51b62aeb0293> in <module>()
----> 1 int("A")

ValueError: invalid literal for int() with base 10: 'A'

Converting to strings:

You can convert an int to a string:

In [124]:
str(1)
Out[124]:
'1'

You can convert a float to a string

In [126]:
str(1.2)
Out[126]:
'1.2'

Boolean

Boolean is another important type in Python; a Boolean can take on two values. The first value is true, just remember we use an uppercase T:

In [129]:
True
Out[129]:
True

Boolean values can also be false, with an uppercase F:

In [131]:
False
Out[131]:
False

Using the type command on a Boolean value we obtain the term bool, this is short for Boolean

In [133]:
type(True)
Out[133]:
bool
In [134]:
type(False)
Out[134]:
bool

If we cast a Boolean true to an integer or float we will get a 1, if we cast a Boolean false to an integer or float. If we get a zero if you cast a 1 to a boolean, you get a true similarly, if you cast a 0 to a Boolean you get a false.

In [136]:
int(True)
Out[136]:
1
In [137]:
bool(1)
Out[137]:
True
In [138]:
bool(0)
Out[138]:
False
In [139]:
float(True)
Out[139]:
1.0

Quiz on types

What is the type of the result of: 6 / 2

In [143]:
type(6/2)
Out[143]:
float

What is the type of the result of: 6 // 2? (Note the double slash //)

In [145]:
type(6//2)
Out[145]:
int

Expression and Variables

Expressions

Expressions are operations that Python performs. For example, basic arithmetic operations like adding multiple numbers.

In [149]:
43 + 60 + 16 + 41
Out[149]:
160

We can perform operations such as subtraction using the subtraction sign. In this case the result is a negative number.

In [151]:
50 - 60
Out[151]:
-10

We can use multiplication using an asterisk:

In [153]:
5 * 5
Out[153]:
25

We can also perform division with the forward slash

In [155]:
25 / 5
Out[155]:
5.0
In [156]:
25 / 6
Out[156]:
4.166666666666667

We can use the double slash for integer division, where the result is rounded

In [158]:
25//5
Out[158]:
5
In [159]:
25//6
Out[159]:
4

What is 160 min in hours?

In [162]:
160.0/60.0
Out[162]:
2.6666666666666665

Python follows mathematical conventions when performing mathematical expressions. The following operations are in different order. In both cases Python performs multiplication, then addition to obtain the final result.

In [164]:
2 * 60 + 30
Out[164]:
150

The expressions in the parentheses are performed first. We then multiply the result by 60, the result is 1920.

In [167]:
(30 + 2) * 60
Out[167]:
1920

[Tip] Summary

You can do a variety of mathematical operations in Python including:
  • addition: **2 + 2**
  • subtraction: **5 - 2**
  • multiplication: **3 \* 2**
  • division: **4 / 2**
  • exponentiation: **4 \*\* 2**
  • Variables

    We can also store our output in variables, so we can use them later on. For example:

    In [171]:
    x = 43 + 60 + 16 + 41
    

    To return the value of x, we can simply run the variable as a command:

    In [172]:
    x
    
    Out[172]:
    160

    We can also perform operations on x and save the result to a new variable:

    In [175]:
    y = x / 60
    y
    
    Out[175]:
    2.6666666666666665

    If we save something to an existing variable, it will overwrite the previous value:

    In [177]:
    x = x / 60
    x
    
    Out[177]:
    2.6666666666666665

    It's good practice to use meaningful variable names, so you don't have to keep track of what variable is what:

    In [179]:
    total_min = (43 + 42 )
    total_min
    
    Out[179]:
    85
    In [180]:
    total_hr = total_min / 60  
    total_hr
    
    Out[180]:
    1.4166666666666667

    You can put this all into a single expression, but remember to use round brackets to add together the album lengths first, before dividing by 60.

    In [182]:
    total_hr = (43 + 42 + 57) / 60  # get total hours in a single expression
    total_hr
    
    Out[182]:
    2.3666666666666667

    [Tip] Variables in Python

    As you just learned, you can use **variables** to store values for repeated use. Here are some more **characteristics of variables in Python**:
  • variables store the output of a block of code
  • variables are typically assigned using **=** (as in **x = 1**)

  • Quiz on Expression and Variables in Python

    What is the value of x ?

    x = 3 + 2 * 2

    In [186]:
    x = 3 + 2 * 2
    
    In [187]:
    x
    
    Out[187]:
    7

    What is the value of y ?

    y = (3 + 2) * 2

    In [189]:
    y = (3 + 2) * 2
    
    In [190]:
    y
    
    Out[190]:
    10

    What is the value of z ?

    z = x + y

    In [193]:
    z = x + y
    
    In [194]:
    z
    
    Out[194]:
    17

    -String Operations

    String is a sequences of characters

    QUICK PRACTICE LAB

    QUESTION 1

    Consider the following string:

    Numbers="0123456"

    how would you obtain the even elements ?

    In [203]:
    #Number[::2]
    

    QUESTION 2 (1 point possible)

    What is the result of the following line of code:

    "0123456".find('1')

    In [205]:
    #1. Position
    

    -Lab - String Operations

    String Operations

    Table of Contents


    Strings

    A string is contained within 2 quotes:

    In [6]:
    "Michael Jackson"
    
    Out[6]:
    'Michael Jackson'

    You can also use single quotes:

    In [9]:
    'Michael Jackson'
    
    Out[9]:
    'Michael Jackson'

    A string can be spaces and digits:

    In [11]:
    '1 2 3 4 5 6 '
    
    Out[11]:
    '1 2 3 4 5 6 '

    A string can also be special characters :

    In [13]:
    '@#2_#]&*^%$'
    
    Out[13]:
    '@#2_#]&*^%$'

    We can print our string using the print statement:

    In [15]:
    print("hello!")
    
    hello!
    

    We can bind or assign a string to another variable:

    In [18]:
    Name= "Michael Jackson"
    Name
    
    Out[18]:
    'Michael Jackson'

    Indexing

    It is helpful to think of a string as an ordered sequence. Each element in the sequence can be accessed using an index represented by the array of numbers:

    <img src = "https://ibm.box.com/shared/static/esdu9w118rm1aldff7ff8c9b3kpjdazc.png" width = 600, align = "center"></a>

    The first index can be accessed as follows:

    In [23]:
    print(Name[13])
    
    o
    

    We can access index 6:

    In [25]:
    print(Name[6])
    
    l
    

    Moreover, we can access the 13th index:

    In [31]:
    print(Name[13])
    
    o
    

    We can also use negative indexing with strings:

    <img src = "https://ibm.box.com/shared/static/rmq8akevtt6uufox3xai7q2kqs4j9kan.png" width = 600, align = "center"></a>

    The last element is given by the index -1:

    In [33]:
    print(Name[-1])
    
    n
    

    The first element can be obtained by index -15:

    In [35]:
    print(Name[-15])
    
    M
    

    We can find the number of characters in a string by using 'len', short for length:

    In [38]:
    len("Michael Jackson")
    
    Out[38]:
    15

    We can obtain multiple characters from a string using slicing, we can obtain the 0 to 4th and 8th to the 12th element:

    </a>

    In [41]:
    Name[0:4]
    
    Out[41]:
    'Mich'
    In [42]:
    Name[8:12]
    
    Out[42]:
    'Jack'

    We can also input a stride value as follows, with the '2' indicating that we are selecting every second variable:

    </a>

    In [45]:
    Name[::2]
    
    Out[45]:
    'McalJcsn'

    We can also incorporate slicing with the stride. In this case, we select the first five elements and then use the stride:

    In [47]:
    Name[0:5:2]
    
    Out[47]:
    'Mca'

    We can concatenate or combine strings by using the addition symbols, and the result is a new string that is a combination of both:

    In [49]:
    Statement = Name + "is the best"
    Statement
    
    Out[49]:
    'Michael Jacksonis the best'

    To replicate values of a string we simply multiply the string by the number of times we would like to replicate it. In this case, the number is three. The result is a new string, and this new string consists of three copies of the original string:

    In [51]:
    3*"Michael Jackson "
    
    Out[51]:
    'Michael Jackson Michael Jackson Michael Jackson '

    You can create a new string by setting it to the original variable. Concatenated with a new string, the result is a new string that changes from Michael Jackson to “Michael Jackson is the best".

    In [53]:
    Name= "Michael Jackson"
    Name= Name+" is the best"
    Name
    
    Out[53]:
    'Michael Jackson is the best'

    Escape Sequences

    Back slashes represent the beginning of escape sequences. Escape sequences represent strings that may be difficult to input. For example, back slash "n" represents a new line. The output is given by a new line after the back slash "n” is encountered:

    In [57]:
    print(" Michael Jackson \n is the best" )
    
     Michael Jackson 
     is the best
    

    Similarly, back slash "t" represents a tab:

    In [59]:
    print(" Michael Jackson \t is the best" )
    
     Michael Jackson 	 is the best
    

    If you want to place a back slash in your string, use a double back slash:

    In [61]:
    print(" Michael Jackson \\ is the best" )
    
     Michael Jackson \ is the best
    

    We can also place an "r" before the string to display the backslash:

    In [63]:
    print(r" Michael Jackson \ is the best" )
    
     Michael Jackson \ is the best
    

    String Operations

    There are many string operation methods in Python that can be used to manipulate the data. We are going to use some basic string operations on the data.

    Let's try with the method "upper"; this method converts upper case characters to lower case characters:

    In [73]:
    A="Thriller is the sixth studio album"
    print("before upper:",A)
    B=A.upper()
    print("After upper:",B)
    
    before upper: Thriller is the sixth studio album
    After upper: THRILLER IS THE SIXTH STUDIO ALBUM
    

    The method replaces a segment of the string, i.e. a substring with a new string. We input the part of the string we would like to change. The second argument is what we would like to exchange the segment with, and the result is a new string with the segment changed:

    In [75]:
    A="Michael Jackson is the best"
    B=A.replace('Michael', 'Janet')
    B
    
    Out[75]:
    'Janet Jackson is the best'

    The method "find" finds a sub-string. The argument is the substring you would like to find, and the output is the first index of the sequence. We can find the sub-string "jack" or "el".

    </a>

    In [78]:
    Name="Michael Jackson"
    Name.find('el')
    
    Out[78]:
    5
    In [79]:
    Name.find('Jack')
    
    Out[79]:
    8

    If the sub-string is not in the string then the output is a negative one. For example, the string 'Jasdfasdasdf' is not a substring:

    In [81]:
    Name.find('Jasdfasdasdf')
    
    Out[81]:
    -1

    Quiz on Strings

    What is the value of the variable "A" after the following code is executed?

    A="1"

    In [85]:
    A="1"
    
    In [86]:
    A
    
    Out[86]:
    '1'

    What is the value of the variable "B" after the following code is executed?

    B="2"

    In [88]:
    B="2"
    
    In [89]:
    B
    
    Out[89]:
    '2'

    What is the value of the variable "C" after the following code is executed?

    C=A+B

    In [91]:
    C=A+B
    
    In [92]:
    C
    
    Out[92]:
    '12'

    Consider the variable "D": use slicing to print out the first three elements:

    In [95]:
    D="ABCDEFG"
    
    In [96]:
    print(D[:3])
    
    ABC
    

    Use a stride value of 2 to print out every second character of the string "E":

    In [98]:
    E='clocrkr1e1c1t'
    
    In [99]:
    print(E[::2])
    
    correct
    
    In [101]:
    print(" \\" )
    
     \
    

    Convert the variable "F" to uppercase:

    In [103]:
    F="You are wrong"
    
    In [104]:
    F.upper()
    
    Out[104]:
    'YOU ARE WRONG'

    Consider the variable "G", and find the first index of the sub-string 'snow':

    In [107]:
    G="Mary had a little lamb Little lamb, little lamb Mary had a little lamb \
    Its fleece was white as snow And everywhere that Mary went Mary went, Mary went \
    Everywhere that Mary went The lamb was sure to go"
    
    In [108]:
    G.find('snow')
    
    Out[108]:
    95

    In the variable "G", replace the sub-string Mary with "Bob":

    In [110]:
    G.replace("Mary","Bob")
    
    Out[110]:
    'Bob had a little lamb Little lamb, little lamb Bob had a little lamb Its fleece was white as snow And everywhere that Bob went Bob went, Bob went Everywhere that Bob went The lamb was sure to go'

    -Review Questions

    In [111]:
    3 + 2 * 2
    
    Out[111]:
    7
    In [113]:
    name = 'Lizz'
    
    In [114]:
    print(name[0:2])
    
    Li
    
    In [115]:
    var = '01234567'
    
    In [116]:
    print(var[::2])
    
    0246
    
    In [117]:
    '1'+'2'
    
    Out[117]:
    '12'
    In [118]:
    myvar = 'hello'
    
    In [119]:
    myvar.upper()
    
    Out[119]:
    'HELLO'

    Cheers!

    /itsmecevi