Python Introduction - Jupyter Lab

profileJoJo2008
IntroPythonProgramming.pdf

5/21/2019 IntroPythonProgramming

localhost:8888/nbconvert/html/Google Drive/AAA_WestCliff/Python/IntroPythonProgramming.ipynb?download=false 1/19

Note: If you dont have Jupyter Notebook installed in your PC, go to the below link and access Jupyter through the below link.

https://labs.cognitiveclass.ai/ (https://labs.cognitiveclass.ai/)

Say "Hello" in Python

To execute the Python code in the code cell below, click on the cell to select it and press Shift + Enter .

In [2]: # Try your first Python output

print('Hello, Python!')

In [5]: print("Hello World")

Writing comments in Python

In [6]: # Practice on writing comments

print('Hello, Python!') # This line prints a string # print('Hi')

Integers Integers can be negative or positive numbers:

Hello, Python!

Hello World

Hello, Python!

5/21/2019 IntroPythonProgramming

localhost:8888/nbconvert/html/Google Drive/AAA_WestCliff/Python/IntroPythonProgramming.ipynb?download=false 2/19

In [8]: # Print the type of -2

type(-2.0)

In [ ]: # Print the type of -1

type(4)

Floats Floats represent real numbers; they are a superset of integer numbers but also include "numbers with decimals".

In [9]: # Print the type of 1.0

type(1.0) # Notice that 1 is an int, and 1.0 is a float

In [ ]: # Print the type of 0.56

type(0.56)

Converting integers to floats: Typecasting!

Let's cast integer 2 to float:

In [10]: # Convert 2 to a float

float(2)

In [11]: # Convert integer 2 to a float and check its type

type(float(2))

In [12]: # Casting 1.1 to integer will result in loss of information

int(1.1)

Out[8]: float

Out[9]: float

Out[10]: 2.0

Out[11]: float

Out[12]: 1

5/21/2019 IntroPythonProgramming

localhost:8888/nbconvert/html/Google Drive/AAA_WestCliff/Python/IntroPythonProgramming.ipynb?download=false 3/19

In [13]: # Convert an integer to a string

str(1)

In [14]: # Convert a float to a string

str(1.2)

Boolean data type Boolean is another important type in Python. An object of type Boolean can take on one of two values: True or False :

In [15]: # Value true

True

In [16]: # Value false

False

In [17]: # Type of True

type(True)

In [18]: 11//2

In [ ]: (72 - 32) / 9.0 * 5

Python Variables Unlike other programming languages, Python has no command for declaring a variable. A variable is created the moment you first assign a value to it.

Out[13]: '1'

Out[14]: '1.2'

Out[15]: True

Out[16]: False

Out[17]: bool

Out[18]: 5

5/21/2019 IntroPythonProgramming

localhost:8888/nbconvert/html/Google Drive/AAA_WestCliff/Python/IntroPythonProgramming.ipynb?download=false 4/19

In [19]: x = 5 y = "John" print(x) print(y)

Unlike other programming languages, Python has no command for declaring a variable. A variable is created the moment you first assign a value to it.

In [20]: x = 4 # x is of type int x = "Mark" # x is now of type str print(x)

String Operations In [21]: # Use quotation marks for defining string

"Michael Jackson"

In [ ]: # Use single quotation marks for defining string

'Michael Jackson'

In [25]: print('Chris' + " " + str(2))

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:

5 John

Mark

Out[21]: 'Michael Jackson'

Chris 2

5/21/2019 IntroPythonProgramming

localhost:8888/nbconvert/html/Google Drive/AAA_WestCliff/Python/IntroPythonProgramming.ipynb?download=false 5/19

The first index can be accessed as follows:

In [26]: # Print the first element in the string Name = "Michael Jackson" print(Name[0])

We can access index 6:

In [ ]: # Print the element on index 6 in the string print(Name[6])

In [ ]: # Print the element on the 13th index in the string

print(Name[13])

Negative Indexing

Using negative numbers for slicing is helpful for doing offsets relative to the end of a list.

M

5/21/2019 IntroPythonProgramming

localhost:8888/nbconvert/html/Google Drive/AAA_WestCliff/Python/IntroPythonProgramming.ipynb?download=false 6/19

In [27]: # Print the last element in the string

print(Name[-1])

In [28]: # Print the first element in the string

print(Name[-15])

Slicing The basic form of the slicing syntax is somelist[start:end]. We can obtain multiple characters from a string using slicing, we can obtain the 0 to 4th and 8th to the 12th element:

n

M

5/21/2019 IntroPythonProgramming

localhost:8888/nbconvert/html/Google Drive/AAA_WestCliff/Python/IntroPythonProgramming.ipynb?download=false 7/19

In [29]: # Take the slice on variable Name with only index 0 to index 3

Name[0:4]

In [30]: # Take the slice on variable Name with only index 8 to index 11

Name[8:12]

MORE ON SLICING

In [32]: a = ['a','b','c','d','e','f','g','h']

In [33]: print('First four:', a[:4])

In [34]: print('Last four:', a[-4:])

In [35]: print('Middle two:', a[3:-3])

In [ ]: #Try and observe below examples a[:] #['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h] a[:5] #['a', 'b', 'c', 'd', 'e'] a[:-1] #['a', 'b', 'c', 'd', 'e', 'f', 'g'] a[4:] # ['e', 'f', 'g', 'h'] a[-3:] # ['f', 'g', 'h'] a[2:5] # ['c', 'd', 'e'] a[2:-1]# ['c', 'd', 'e', 'f', 'g']

Out[29]: 'Mich'

Out[30]: 'Jack'

First four: ['a', 'b', 'c', 'd']

Last four: ['e', 'f', 'g', 'h']

Middle two: ['d', 'e']

5/21/2019 IntroPythonProgramming

localhost:8888/nbconvert/html/Google Drive/AAA_WestCliff/Python/IntroPythonProgramming.ipynb?download=false 8/19

In [36]: a[:]

Stride

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

In [38]: # Get every second element. The elments on index 1, 3, 5 ...

Name[::3]

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

In [ ]: # Get every second element in the range from index 0 to index 4

Name[0:5:2]

String Concatenation

In [ ]: 'ham'+'eggs'

In [ ]: 'ham'+2*'eggs'

Length

Out[36]: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

Out[38]: 'Mhlas'

5/21/2019 IntroPythonProgramming

localhost:8888/nbconvert/html/Google Drive/AAA_WestCliff/Python/IntroPythonProgramming.ipynb?download=false 9/19

In [39]: len('Hello you!')

In [40]: import math math.sqrt(3*3)

In [45]: for c in 'Hello You!': print(c, end ="")

String Methods!

In [46]: s ="august" s

In [47]: s.capitalize()

In [48]: s.upper()

In [49]: s.title()

In [50]: s.find('g') #Find the first position where sub occurs in s

In [51]: s.rfind('u')

In [52]: s.replace('u','j')

In [ ]:

Lists

Out[39]: 10

Out[40]: 3.0

Hello You!

Out[46]: 'august'

Out[47]: 'August'

Out[48]: 'AUGUST'

Out[49]: 'August'

Out[50]: 2

Out[51]: 3

Out[52]: 'ajgjst'

5/21/2019 IntroPythonProgramming

localhost:8888/nbconvert/html/Google Drive/AAA_WestCliff/Python/IntroPythonProgramming.ipynb?download=false 10/19

A list is a sequential collection of Python data values, where each value is identified by an index. The values that make up a list are called its elements. Lists are called compound data types and are one of the key types of data structures in Python. Strings are always sequences of characters. Lists are sequences of arbitrary values. Lists can have numbers, strings, or both!

In [ ]: myList =[1,"ham",4,"eggs"]

In [ ]: type(myList)

In [ ]: print(myList)

Indexing

In [ ]: list = [1, 2, 3, 4, 5, 6, 7 ];

In [ ]: print ("list[1:5]: ", list[1:5])

Traversing a list

In [ ]: myList =[1,"ham",4,"eggs"]

In [ ]: numElem=0 for item in myList: numElem = numElem+1 print(numElem)

Concatenation & Slicing

In [ ]: a =["This", "is", "fun"] b = [1,2]

In [ ]: a + b

In [ ]: (a+b)[1:3]

In [ ]: (a+b)[1:]

Appending

5/21/2019 IntroPythonProgramming

localhost:8888/nbconvert/html/Google Drive/AAA_WestCliff/Python/IntroPythonProgramming.ipynb?download=false 11/19

In [ ]: a.append([1,2,3]) a

In [ ]: a.extend([1,2,3]) a

Range Range object is an ordered list. to generate a sequence that contains three elements ordered from 0 to 2 we simply use the following command:

In [ ]: # Use the range

range(0,3)

In [ ]: for i in range(6): print(i, end=' ') # Appends a space instead of a newline in Python 3

List Comprehensions

In [ ]: a = range(0,11)

In [ ]: squares = [ x**2 for x in a] squares

Filter

In [ ]: even_squares = [ x**2 for x in a if x % 2 == 0] even_squares

In [ ]:

Dictionaries

What are Dictionaries? A dictionary consists of keys and values. It is helpful to compare a dictionary to a list. Instead of the numerical indexes such as a list, dictionaries have keys. These keys are the keys that are used to access values within a dictionary.

5/21/2019 IntroPythonProgramming

localhost:8888/nbconvert/html/Google Drive/AAA_WestCliff/Python/IntroPythonProgramming.ipynb?download=false 12/19

In [ ]: Dict={"A":1,"B":"2","C":[3,3,3],"D":(4,4,4),'E':5,'F':6} Dict["D"]

In [ ]: # Create the dictionary

Dict = {"key1": 1, "key2": "2", "key3": [3, 3, 3], "key4": (4, 4, 4), ('key5' ): 5, (0, 1): 6} Dict

In [ ]: # Access to the value by the key

Dict["key1"]

In [ ]: # Access to the value by the key

Dict[(0, 1)]

In [ ]: # Get all the keys in dictionary

Dict.keys()

In [ ]: Dict.values()

5/21/2019 IntroPythonProgramming

localhost:8888/nbconvert/html/Google Drive/AAA_WestCliff/Python/IntroPythonProgramming.ipynb?download=false 13/19

In [ ]: # Append value with key into dictionary

Dict['key6'] = '71'

In [ ]: Dict

In [ ]: # Delete entries by key

del(Dict['key2'])

In [ ]: Dict

In [ ]: # Verify the key is in the dictionary

'key6' in Dict

In [ ]:

Sometimes, you might want to repeat a given operation many times. Repeated executions like this are performed by loops. We will look at for loops.

Before we discuss loops lets discuss the range object. It is helpful to think of the range object as an ordered list. For now, let's look at the simplest case. If we would like to generate a sequence that contains three elements ordered from 0 to 2 we simply use the following command:

For Loop

Sometimes, you might want to repeat a given operation many times. Repeated executions like this are performed by loops. We will look at for loops.

Before we discuss loops lets discuss the range object. It is helpful to think of the range object as an ordered list. For now, let's look at the simplest case. If we would like to generate a sequence that contains three elements ordered from 0 to 2 we simply use the following command:

Range

In [5]: # Use the range

range(3)

Out[5]: range(0, 3)

5/21/2019 IntroPythonProgramming

localhost:8888/nbconvert/html/Google Drive/AAA_WestCliff/Python/IntroPythonProgramming.ipynb?download=false 14/19

What is for loop?

The for loop enables you to execute a code block multiple times. For example, you would use this if you would like to print out every element in a list. Let's try to use a for loop to print all the years presented in the list dates :

This can be done as follows:

In [6]: # For loop example

dates = [1982,1980,1973] N = len(dates)

for i in range(N): print(dates[i])

Functions An example of a function that adds on to the parameter a prints and returns the output as b :

1982 1980 1973

5/21/2019 IntroPythonProgramming

localhost:8888/nbconvert/html/Google Drive/AAA_WestCliff/Python/IntroPythonProgramming.ipynb?download=false 15/19

In [7]: # First function example: Add 1 to a and store as b

def add(a): b = a + 1 print(a, "if you add one", b) return(b)

In [8]: # Call the function add()

add(2)

In [9]: # Define a function for multiple two numbers

def Mult(a, b): c = a * b return(c)

In [10]: # Use mult() multiply two integers

Mult(2, 3)

In [11]: # Use mult() multiply two floats

Mult(10.0, 3.14)

In [12]: # Use mult() multiply two different type values together

Mult(2, "Michael Jackson ")

Comparison Operators

In [13]: # Condition Equal

a = 5 a == 6

2 if you add one 3

Out[8]: 3

Out[10]: 6

Out[11]: 31.400000000000002

Out[12]: 'Michael Jackson Michael Jackson '

Out[13]: False

5/21/2019 IntroPythonProgramming

localhost:8888/nbconvert/html/Google Drive/AAA_WestCliff/Python/IntroPythonProgramming.ipynb?download=false 16/19

In [14]: # Greater than Sign

i = 6 i > 5

In [15]: # Inequality Sign

i = 2 i != 6

In [16]: # Inequality Sign

i = 6 i != 6

In [17]: # Use Equality sign to compare the strings

"ACDC" == "Michael Jackson"

In [18]: # Compare characters

'B' > 'A'

In [19]: # Compare characters

'BA' > 'AB'

Branching Branching allows us to run different statements for different inputs. It is helpful to think of an if statement as a locked room, if the statement is True we can enter the room and your program will run some predefined tasks, but if the statement is False the program will ignore the task.

Out[14]: True

Out[15]: True

Out[16]: False

Out[17]: False

Out[18]: True

Out[19]: True

5/21/2019 IntroPythonProgramming

localhost:8888/nbconvert/html/Google Drive/AAA_WestCliff/Python/IntroPythonProgramming.ipynb?download=false 17/19

Use the condition statements learned before as the conditions need to be checked in the if statement. The syntax is as simple as if condition statement : , which contains a word if , any condition statement, and a colon at the end. Start your tasks which need to be executed under this condition in a new line with an indent. The lines of code after the colon and with an indent will only be executed when the if statement is True. The tasks will end when the line of code does not contain the indent.

In the case below, the tasks executed print(“you can enter”) only occurs if the variable age is greater than 18 is a True case because this line of code has the indent. However, the execution of print(“move on”) will not be influenced by the if statement.

In [20]: # If statement example

age = 19 #age = 18

#expression that can be true or false if age > 18: #within an indent, we have the expression that is run if the condition is true print("you can enter" )

#The statements after the if statement will run regardless if the condition is true or false print("move on")

The else statement runs a block of code if none of the conditions are True before this else statement. Let's use the ACDC concert analogy again. If the user is 17 they cannot go to the ACDC concert, but they can go to the Meatloaf concert. The syntax of the else statement is similar as the syntax of the if statement, as else : . Notice that, there is no condition statement for else . Try changing the values of age to see what happens:

In [21]: # Else statement example

age = 18 # age = 19

if age > 18: print("you can enter" )

else: print("go see Meat Loaf" ) print("move on")

you can enter move on

go see Meat Loaf move on

5/21/2019 IntroPythonProgramming

localhost:8888/nbconvert/html/Google Drive/AAA_WestCliff/Python/IntroPythonProgramming.ipynb?download=false 18/19

Exercises Due Sunday June 2nd 11:59PM

1. measureCircleArea(radius) [10 Points] The function should calculate and print the area of a circle. Radius is passed as input parameter. Area of circle is 𝜋𝑟^2, where r is radius and 𝜋 is a constant which has the value 3.14.

In [ ]:

2. computeAverage() [10 Points] This function should print the average of numbers ‘10’, ‘20’, ‘30’ and ‘40’.

In [ ]:

3. kilometersToMiles(km) [10 Points] The function should convert distances measured in kilometers to miles and print the distance in miles. Value of distance in kilometers is passed as input parameter to function. One kilometer is approximately 0.62 miles.

In [ ]:

4. firstFiveOddnumbers() [20 Points] The function should print the first five odd integers (1, 3, 5, 7, 9) using ‘for’ loop.

In [ ]:

5. firstFiveNumberSum() [20 Points] Write a function firstFive() which prints the first five integers (1, 2, 3, 4, 5) using ‘for’ loop.

In [ ]:

5/21/2019 IntroPythonProgramming

localhost:8888/nbconvert/html/Google Drive/AAA_WestCliff/Python/IntroPythonProgramming.ipynb?download=false 19/19

6. Write a function that takes two positive integers which define the values of a range. The function calculates and prints the ratio of the sum of even numbers to the sum of all the numbers in the range. [30 Points]

input: Positive integers ‘start’ and ‘end’

Output: Ratio of sum of even numbers to the sum of all the numbers in the range defined by the numbers ‘start’ and ‘end’

Explaination:

Let’s say we have the values of ‘start’ and ‘end’ as 2 and 10 respectively. So, numbers between 2 and 10 are 2 , 3, 4 , 5 , 6 , 7, 8, 9 , 10 The sum of even numbesr in the given range is : 2 + 4 + 6 + 8 + 10 = 30 Total sum of all the numbers is 54 Ratio of the sum of even numbers to the sum of all the numbers in this range is 30/54 = 0.555 Hint: An even number divided by 2 leaves a remainder 0.

In [ ]:

In [ ]: