Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 103

Prepared by: NG HUI QUN &MUKRIMAH NAWIR

School of Computer and Communication Engineering

Organized by School of Computer and Communication Engineering

09/12/201 PYTHON CRASH 1


8 COURSE
Dr AmizaAmir|Dr NaimahYaakob|Dr Nik Adilah Hanin|Mdm SalinaAsi|Ng Hui Qun|Mukrimah Nawir
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

PYTHON CRASH COURSE


9.00am Variables and Simple Data Types 10.00am

10.00am Introduction and Working withLISTS 12.00pm

12.00pm IF Statements 1.00pm

1.00pm
BREAK TIME 2.00pm

2.00pm User Input and While loops 3.00pm

3.00pm Functions 4.00pm

4.00pm Dictionaries and Data Visualization 5.15pm


09/12/201 PYTHON CRASH 2
8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

PYTHON CRASH COURSE

VARIABLES
&
SIMPLE DATATYPES
09/12/201 PYTHON CRASH 3
8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

VARIABLES
word print, it prints to the screen whatever is inside the parentheses.

 print (“Hello Python World!”)


Hello Python World!
 message = “Hello Python World!”
print (message) message is a variable
Hello Python World!
 message = “Hello Python World!”
print (message)

message = “Hello Python Crash Course World!”


print (message)
Hello Python World!
Hello Python Crash Course World!
09/12/201 PYTHON CRASH 4
8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

RULES &GUIDELINES - VARIABLES

 Contain only letters, numbers, and underscores



Can start with a letter or an underscore, but not with a
number.
 Spaces are not allowed, but underscores can be used
 Avoid using Python keywords and function names

09/12/201 PYTHON CRASH 5


8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

STRINGS
A series of characters. Anything inside quotes is considered a
string in Python and you can use single or double quotes

String with Methods


Name = “ mukrimah nawir” Output:
print(Name.title()) Mukrimah Nawir
print(Name.upper()) MUKRIMAH NAWIR

print(Name.lower()) mukrimah nawir


Combining and Concatenating Strings
first_name=”mukrimah”
last_name=”nawir” mukrimah nawir
full_name= first_name + “ “ + last_name
print(full_name)
print(“Hello, “ + full_name.title() + “!”) Hello, Mukrimah Nawir!
09/12/201 PYTHON CRASH 6
8 COURSE
Prepared by: NG HUI QUN

STRINGS
String with Tabs Output:
print(“Python”) Python
print(“\tPython”) Python
String with Newlines Languages:
print(“Languages:\nPython\nC\nJavaScript”) Python
C
JavaScript
String with Apostrophe
message=”One of Python's strengths is its diverse community.”
print(message) One of the Python's strengths is its diverse community

message='One of Python's strengths is its diverse community.'


print(message) SyntaxError: invalid syntax

 rstrip() : right strip  lstrip() : left strip  strip() : both side strip
09/12/201 PYTHON CRASH 7
8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

NUMBERS
Integers
 Add(+), Substract(-), Multiply (*), and Divide (/), Exponents (**)
Floats

Number with a decimal point
print(16.0/7)
2.2857142857142856

Rounding Floats
 X=(16.0/7)
output=round(X,3)
print(output)
2.286

09/12/201 PYTHON CRASH 8


8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR
AVOIDING TYPE ERRORS WITH STR()
FUNCTION

 age=23
message=”Happy” + age + “rd Birthday!”
print(message)
TypeError: Can't convert 'int' object to str implicitly
 age=23
message=”Happy ” + str(age) + “rd Birthday!”
print(message)
Happy 23rd Birthday!

# indicates a comment
09/12/2”
01”
8 ” indicates a c
PYo
THm m
ON CRASe
HnCOt
URw
SE ith few 9

lines
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

EXERCISES

Name cases: Store your name in a variable, then print that
person's name in lowercase, uppercase, and titlecase.

Famous quote: Find a quote from a famous person you admire.
Print the quote and the name of its author. Your output should
look like this
Albert Einstein once said, “A person who never made a
mistake never tried anything new.

 Number Eight: Write addition, subtraction, multiplication and


division operations that each result in the number 8. Be
sure to enclose your operations in print statements to see
the results. You should create four lines that look like this:
print(5+3)
09/12/201 PYTHON CRASH 10
8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

PYTHON CRASH COURSE

INTRODUCTION&
WORKINGWITH
LISTS
09/12/201 PYTHON CRASH 11
8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

INTRODUCTION TO LISTS
 A list is a collection of items in a particular order

[ ] indicates a list and individual elements in the list are separated
by commas
bicycles = ['trek','cannondale', 'redline', 'specialized']
print(bicycles) ['trek','cannondale', 'redline', 'specialized']

Accessing Elements in a List



List are ordered collections, access any element in a list by telling
Python the position/index of the item desired.

bicycles = ['trek','cannondale', 'redline', 'specialized']


print(bicycles[0])
print(bicycles[0].title()) trek
Trek
09/12/201 PYTHON CRASH 12
8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

INTRODUCTION TO LISTS (CONT.)


Index Positions Start at 0, Not 1
 Python considers the first item in a list to be at position 0, not position 1

Special syntax for accessing the last element in a list by asking for the
item at index -1
bicycles = ['trek','cannondale', 'redline', 'specialized']
print(bicycles[1]) cannondale
print(bicycles[3])
specialized
print(bicycles[-1])
print(bicycles[-2])
specialized
redline
Using Individual Values from a List
 Use concatenation to create a message based on a value from a list
bicycles = ['trek','cannondale', 'redline', 'specialized']
message= “My first bicycle was a” + bicycles[0].title()+”.”
print(message)
My first bicycle was a Trek.
09/12/201 PYTHON CRASH 13
8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR
CHANGING, ADDING, &REMOVING
ELEMENTS
Modifying elements in a list
cars = ['peugeot','merc', 'mazda']
print(cars) ['peugeot','merc', 'mazda']
cars[0]='myvi' ['myvi','merc', 'mazda']
print(cars)
Adding elements in a list – .append() or .insert()
cars.append = ('volvo')
print(cars) ['myvi','merc', 'mazda','volvo']
cars.insert(2,'kancil') ['myvi','merc', 'kancil', 'mazda','volvo']
print(cars)
Removing elements in a list – del
cars = ['peugeot','merc', 'mazda']
['peugeot','merc', 'mazda']
print(cars) ['merc', 'mazda']
del cars[0]
print(cars)

09/12/201 PYTHON CRASH 14


8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR
CHANGING, ADDING, &REMOVING ELEMENTS
(CONT.)
Removing elements in a list - .pop()
motorcycles = ['honda','yamaha', 'suzuki']
print(motorcycles) ['honda','yamaha', 'suzuki']
popped_motorcycle=motorcycles.pop() ['honda','yamaha']
print(motorcycles) suzuki
print(popped_motorcycles)
Popping items from any Position in a List .
motorcycles = ['honda','yamaha', 'suzuki']
first_owned=motorcycles.pop(0)
print('The first motorcycle I owned was a '+first_owned.title()+'.')
The first motorcycle I owned was a Honda.
Removing an item by Value .
motorcycles = ['honda','yamaha', 'suzuki','ducati']
print(motorcycles)
motorcycles.remove('ducati') ['honda','yamaha', 'suzuki','ducati']
print(motorcycles) ['honda','yamaha', 'suzuki']
09/12/201 PYTHON CRASH 15
8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

ORGANIZING A LIST
Sorting a List Permanently – .sort()
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort() ['audi','bmw', subaru', 'toyota', ]
print(cars)
Sorting a List Temporarily – sorted() Here is the original list:
cars = ['bmw', 'audi', 'toyota', 'subaru'] ['bmw', 'audi', 'toyota', 'subaru']
print(“Here is the original list:”)
print(“\nHere is the sorted list:”) Here is the sorted list:
print(sorted(cars)) ['audi','bmw', subaru', 'toyota', ]
Printing a List in Reverse Order - .reverse()
cars = ['bmw', 'audi', 'toyota', 'subaru']
print(cars) ['bmw', 'audi', 'toyota', 'subaru']
cars.reverse ['subaru', 'toyota','audi', 'bmw' ]
print(cars)
Finding the length of a list - len() output
cars = ['bmw', 'audi', 'toyota', 'subaru'] 4
len(cars)
09/12/201 PYTHON CRASH 16
8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

WORKING WITH LISTS


Looping Through Entire List
 When doing the same action with every item in a list, use a for looping
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician)
Indentation in Looping
 Indentation is used to determine when one line of code is connected to the
line above it.

In the example, lines 3 and 4 were part of the for loop because they were
indented.

Indentation makes code very easy to read.

Four spaces per indentation level
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician.title()+”, thata was a great trick!”)
print(“I can't wait to see your next, “ + magician.title() + “.\n”
09/12/201 PYTHON CRASH 17
8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

ORGANIZING A LIST
Sorting a List Permanently – .sort()
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort() ['audi','bmw', subaru', 'toyota', ]
print(cars)
Sorting a List Temporarily – sorted() Here is the original list:
cars = ['bmw', 'audi', 'toyota', 'subaru'] ['bmw', 'audi', 'toyota', 'subaru']
print(“Here is the original list:”)
print(“\nHere is the sorted list:”) Here is the sorted list:
print(sorted(cars)) ['audi','bmw', subaru', 'toyota', ]
Printing a List in Reverse Order - .reverse()
cars = ['bmw', 'audi', 'toyota', 'subaru']
print(cars) ['bmw', 'audi', 'toyota', 'subaru']
cars.reverse ['subaru', 'toyota','audi', 'bmw' ]
print(cars)
Finding the length of a list - len() output
cars = ['bmw', 'audi', 'toyota', 'subaru'] 4
len(cars)
09/12/201 PYTHON CRASH 18
8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

INDENTATION ERRORS
 Forgetting to Indent
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician.title()+”, that was a great trick!”)
 Forgetting to Indent Additional Lines
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician.title()+”, that was a great trick!”)
print(“I can't wait to see your next trick, “+magician.title()+”.\n”)
 Indenting Unnecessarily
message = “hello world”
print(message)
 Forgetting the colon
magicians = ['alice', 'david', 'carolina']
for magician in magicians
print(magician)
09/12/201 PYTHON CRASH 19
8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

MAKING NUMERICAL LIST


 Using the range() Function
1 Range() function starts counting at the
For value in range(1,5) 2 first value you give and stops when it
print(value) 3
reaches the second value. Therefore, the
4
c output never contains the end value.
 Using the range() to Make a List of Numbers
numbers = list(range(1,6)) [1, 2, 3, 4, 5]
print(numbers)
even_numbers = list(range(2,11,2)) Starting number is 2
print(even_numbers) Adds 2 repeatedly until it
[2, 4, 6, 8, 10] reaches or passes the end
value
squares = []
for value in range(1,11):
square = value**2 [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
09/12/20s18quares.append(squareP)YTHON CRASH 2
COURSE 0
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

MAKING NUMERICA LISTS (CONT.)


Simple Statistics with a List of Numbers
You can easily find the minimum, maximum and sum of a list of numbers.
digits = [1,2,3,4,5,6,7,8,9,0] 0
print(min(digits) 9
print(max(digits) 45
print(sum(digits)

List Comprehensions
 Allows you to generate the list in just one line of code.
 Combine for loop and the creation of new elements into one line, and
automatically appends each new element.
squares = []
for value in range (1,11): squares = [value**2 in range (1,11)]
squares.append(value**2) print (squares)
print (squares)

09/12/201 PYTHON CRASH 21


8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

WORKING WITH PART OF A LIST


Slicing a List
 To make a slice, you specify the index of the first and last elements you
want to work with.
 To output the first three elements in a list, you would request indices 0
through 3, which would return 0,1,and 2.
players =[‘charles’,’martina’,’micheal’, ‘florence’,’eli’]
print(players[0:3])
[‘charles’,’martina’,’micheal’]

 To output 2nd,3rd and 4th items, you would request indices 1 through 4.
players =[‘charles’,’martina’,’micheal’, ‘florence’,’eli’]
print(players[1:4])
[martina’,’micheal',‘florence’ ]

09/12/201 PYTHON CRASH 22


8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

WORKING WITH PART OF A LIST (CONT.)


 If you omit the first index in a slice, Python automatically starts your slice at
the beginning of the lists:
players =[‘charles’,’martina’,’micheal’, ‘florence’,’eli’]
print(players[:4])

[‘charles’,’martina’,’micheal’, ‘florence’]

 If you want all items from the third item through the last item.
players =[‘charles’,’martina’,’micheal’, ‘florence’,’eli’]
print(players[2:])

[’micheal',‘florence’,’eli’ ]

 The last three players on the list.


players =[‘charles’,’martina’,’micheal’, ‘florence’,’eli’]
print(players[-3:])
[’micheal',‘florence’,’eli’ ]
09/12/201 PYTHON CRASH 23
8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

WORKING WITH PART OF A LIST (CONT.)


Looping Through a Slice
 Use a slice in a for loop if you want to loop through a subset of the
elements in a list.
players =[‘charles’,’martina’,’micheal’, ‘florence’,’eli’]
print(“The first three players”)
for player in players[:3]:
print(players.title())

Output: The first three players:


Charles
Martina
Michael

09/12/201 PYTHON CRASH 24


8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

WORKING WITH PART OF A LIST (CONT.)


Copying a List

my_foods =[‘pizza’,`falafel’,`carrot cake’]


friend_foods = my_food[:]

my_foods.append(‘cannoli’)
friend_foods.append(‘ice cream’)

print(“My favorite foods are:”)


print(my_food)

print(“\n My friend’s favorite foods are:”)


print(friend_foods)
My favorite foods are:
[‘pizza’,`falafel’,`carrot cake’,’cannoli’]

My friend’s favorite foods are:


09/12/201
[‘pizza’,`falafel’,`carrot cake’,’ice cream’]
PYTHON CRASH 2
8 COURSE 5
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

TUPLES
Defining a Tuple
 Lists are used for storing items that can change throughout the life of a
program.
 Tuple is a list of items that cannot change (immutable).
dimensions=(200, 50)
200
print(dimensions[0]); 50
print(dimensions[1]);

 What if we try to change one of the items?


dimensions=(200, 50)
dimensions[0]=250
Traceback (most recent call last):
File “dimensions.py”,line 3, in <module>
dimensions[0]= 250
TypeError: ‘tuple’ object does not support item assignment

09/12/2018 PYTHON CRASH COURSE


26
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

TUPLES (CONT.)
Looping Through All Values in a Tupple
 You can loop over all the values in a tuple using a for loop.
dimensions=(200, 50)
for dimension in dimensions: 200
print(dimension) 50

Writing over a Tuple


 Although you can’t modify a tuple, you can assign a new value to a variable that
holds a tuple.

dimensions=(200, 50)
print(“Original dimensions:”)
for dimension in dimensions: Original dimensions:
200
print(dimension) 50
dimensions=(400, 100) Modified dimensions:
print(“\n Modified dimensions:”) 400
for dimension in dimensions: 100
09/12/201 PYTHON CRASH URS 2
8
print(dimension) CO E 7
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

STYLING YOUR CODE


The Style Guide
 Python Enhancement Proposal (PEP) 8

 Instruct programmers on how to style your code.

 Write clear code from the start.

Indentation
 PEP 8 recommends four spaces per indentation level.

 However, people often use tabs rather than spaces to indent.

09/12/201 PYTHON CRASH 28


8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

EXERCISE
Slices: players = ['charles', 'martina', 'micheal', 'florence', 'eli']
 Print the first four items in the list
 Print three items from the middle of the list
 Print the last three items in the list

Buffet: A buffet-style restaurant offers only five basic foods. Think


of five simple foods, and store them in a tuple.
 Use a for loop to print each food the restaurant offers.

 Try to modify one of the items, and make sure that Python rejects the change.

 The restaurant changes its menu, replacing two of the items with different foods.
Add a block of code that rewrites the tuple, and then use a for loop to print each
of the items on the revised menu.

09/12/201 PYTHON CRASH 29


8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

EXERCISE
My Pizza, Your Pizza
 Think of at least 3 kinds of your favourite pizza. Store these pizza names in a list,
and then use a for loop to print the name of each pizza.
 Modify your for loop to print a sentence using the name of the pizza instead of
printing just the name of the pizza. For each pizza, you should have one line of
output containing a simple statement like “ I like pepperoni pizza”
 Add a line at the end of your program, outside the for loop, that states how much
you like pizza. The output should consist of three or more lines about the kinds of
pizza you like and then an additional sentence, such as ’I really love pizza!”
 Make a copy of the list of pizza, and call it friend_pizzas.
 Add a new pizza to the original list.
 Add a different pizza to the friend_pizzas
 Prove that you have two separate list. Print the message list, “My favorite pizzas
are” and the then use a for loop to print the first list. . Print the message list, “My
friend’s favorite pizzas are” and the then use a for loop to print the second list.
09/12/201 PYTHON CRASH 30
8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

PYTHON CRASH COURSE

IFSTATEMENTS

09/12/201 PYTHON CRASH 31


8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

A SIMPLE EXAMPLE
cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars: Output:
if car == 'bmw': Audi
print(car.upper()) BMW
else: Subaru
print(car.title()) Toyoto

CONDITIONAL TESTS
Checking for Equality
>>> car = 'bmw' >>> car = 'audi' False
True
>>> car == 'bmw' >>> car == 'bmw'
''' Set the value of car to 'bmw'(single equal sign)
''' Equality operator returns True if the values on the left and right side of the
operator match

09/12/201 PYTHON CRASH 32


8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

CONDITIONAL TESTS (CONT.)


Checking for Inequality

requested_topping = 'mushrooms' Output:


if requested_topping != 'anchovies': Hold the anchovies!
print(“Hold the anchovies!”)
Numerical Comparisons

>>> age = 19 >>> age = 19 >>> age = 19 >>> age = 19


>>> age < 21 >>> age <= 21 >>> age > 21 >>> age >= 21
True True False False

09/12/201 PYTHON CRASH 33


8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

if Statements
Simple if Statements
age = 19
if age >= 18:
print("You are old enough to vote!")
You are old enough to vote!

if-else Statements
age = 17
if age >= 18:
print("You are old enough to vote!")
print(“Have you registered to vote yet?”)
else:
print(“Sorry, you are too young to vote.”)
print(“Please register to vote as soon as you turn 18!”)
Sorry, you are too young to vote.
Please register to vote as soon as you turn 18!
09/12/201 PYTHON CRASH 34
8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

if Statements (CONT.)
The if-elif-else Chain
age = 12
if age < 4:
print("Your admission cost is $0.")
elif age < 18: Your admission cost is $5
print("Your admission cost is $5.")
else:
print("Your admission cost is $10.")
age = 12
if age < 4:
price = 0
elif age < 18:
price = 5
else:
price = 10
print("Your admission cost is $" + str(price) + ".")

09/12/201 PYTHON CRASH 35


8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

if Statements (CONT.)
Using Multiple elif Blocks
age = 12
if age < 4:
price=0
elif age < 18:
price=5
elif age <65:
price=10
else:
price=5
print("Your admission cost is $" + str(price) + ".")

09/12/201 PYTHON CRASH 36


8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

if Statements (CONT.)
Omitting the else Block
age = 12
if age < 4:
price=0
elif age < 18:
price=5
elif age <65:
price=10
elif age >=65:
price=5
print("Your admission cost is $" + str(price) + ".")

09/12/201 PYTHON CRASH 37


8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

if Statements (CONT.)
Testing Multiple Conditions
requested_toppings = ['mushrooms', 'extra cheese']

if 'mushrooms' in requested_toppings:
print("Adding mushrooms.")
if 'pepperoni' in requested_toppings:
print("Adding pepperoni.")
if 'extra cheese' in requested_toppings:
print("Adding extra cheese.")
print("\nFinished making your pizza!")

Adding mushrooms.
Adding extra cheese.
Finished making your pizza!

09/12/201 PYTHON CRASH 38


8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

if Statements (CONT.)
Testing Multiple Conditions (CONT.)
requested_toppings = ['mushrooms', 'extra cheese']

if 'mushrooms' in requested_toppings:
print("Adding mushrooms.")
elif 'pepperoni' in requested_toppings:
print("Adding pepperoni.")
elif 'extra cheese' in requested_toppings:
print("Adding extra cheese.")
print("\nFinished making your pizza!")

Adding mushrooms.

Finished making your pizza!

09/12/201 PYTHON CRASH 39


8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

USING if Statement WITH LISTS


Checking for Special Items
requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']
for requested_topping in requested_toppings:
print("Adding " + requested_topping + ".")
print("\nFinished making your pizza!") Adding mushrooms
Adding green peppers.
Adding extra cheese.

Finished making your pizza!


requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']

for requested_topping in requested_toppings:


if requested_topping == 'green peppers':
print("Sorry, we are out of green peppers right now.")
else:
print("Adding " + requested_topping + ".")
print("\nFinished making your pizza!") Adding mushrooms.
Sorry, we are out of green peppers right now.
09/12/201 Adding
PYTHON CRASH extra cheese.
COURSE
8 4
0
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

USING if Statement WITH LISTS (CONT.)


Checking That a List Is Not Empty
requested_toppings = []
if requested_toppings:
for requested_topping in requested_toppings:
print("Adding " + requested_topping + ".")
print("\nFinished making your pizza!")
else:
print("Are you sure you want a plain pizza?") Are you sure you want a plain pizza?
Using Multiple Lists
available_toppings = ['mushrooms', 'olives', 'green peppers', 'pepperoni', 'pineapple',
'extra cheese']
requested_toppings = ['mushrooms', 'french fries', 'extra cheese']

for requested_topping in requested_toppings:


if requested_topping in available_toppings:
print("Adding " + requested_topping + ".")
else:
print("Sorry, we don't have " + requested_topping + ".")
print("\nFinished making your pizza!") Adding mushrooms.
Sorry, we don't have french fries.
09/12/201
Adding extra cheese.
PYTHON CRASH COURSE
8 4
1
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

PYTHON CRASH COURSE

USERINPUT
&
WHILELOOPS
09/12/201 PYTHON CRASH 42
8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

INTRODUCTION
 Python input() function
 Syntax:: input(prompt)
 prompt = A String, representing a default message before the input.
 Example:
print('Enter your name:')
x = input()
print('Hello, ' + x.title())


Output:

Enter your name:


Sarah
Hello, Sarah
09/12/201 PYTHON CRASH 43
8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

INTRODUCTION (CONT.)

Another method:
x = input('Enter your name:')
print('Hello, ' + x)


Output:

Enter your name: Sarah


Hello, Sarah

09/12/201 PYTHON CRASH 44


8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

INPUT MULTIPLE VALUES FROM USER IN ONE LINE IN


PYTHON

 For instance, in C we can do something like this:


//Reads two values in one line
scanf(“%d %d”, &x, &y)

 One solution is to use input() two times:


x,y = input(),input()

 Another solution is to use split()


x,y = input().split()

09/12/201 PYTHON CRASH 45


8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

INPUT MULTIPLE VALUES (CONT.)


Both x and y would be of string.
 We can convert them to int using another line
x,y = input(‘Enter values of x and y: ’).split()
iNewX = int(x)
iNewY = int(y)
print(iNewX + iNewY)
 Output
Enter values of x and y: 5 3
8
09/12/201 PYTHON CRASH 46
8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

WHILE LOOPS
 while loop runs as long as a certain condition is true.
 Example:

current_number = 1
while current_number <= 3:
print(current_number)
current_number += 1
 Output
1
2
3
09/12/201 PYTHON CRASH 4
8 COURSE 7
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

WHILE LOOPS (USING A FLAG)


prompt = "Enter 'quit' to end the program.”
repeat = True
while repeat:
message = input(prompt)
if message == 'quit':
repeat = False
else:
print(message)

Output
Enter 'quit' to end the program. Hello everyone!
Hello everyone!
Enter 'quit' to end the program. Hello again.
Hello again.
Enter 'quit' to end the program. quit
09/12/201 quit PYTHON CRASH 4
8 COURSE 8
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

EXERCISE

Write a Python program that creates a table of
degrees Celcius with the corresponding degrees
Fahrenheit. Begin at 0˚C and proceed to 100˚C in
20˚C increments using a suitable repetition structure.

Given, F = C * (9/5) + 32

where F is Fahrenheit, in degrees, and C is Celcius,
in degrees.
Save as
CelsiusToFahrenheit.py

09/12/201 PYTHON CRASH 4


8 COURSE 9
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

EXERCISE (CONT.)

Sample output:

Table of Celsius and Fahrenheit degrees


Degrees Degrees
Celsius Celsius

0.00 32.00
20.00 68.00
40.00 104.00
60.00 140.00
80.00 176.00
09/12/201 PYTHON CRASH 5
8 100.00 212.00
COURSE 0
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

EXERCISE
 Write a Python program that determines whether a
number is odd or even and total of each category.
 The program continues repetition when user enter ‘Y’
or ‘y’; otherwise it stops.
 An even number resulted a remainder of zero when it
is divided by 2.
Save as OddEven.py

09/12/201 PYTHON CRASH 51


8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

EXERCISE (CONT.)
 Sample output:
Enter a number to decide even or odd number: 6
6 is an even number
Do you want to continue? y-yes other characters-no y
Enter a number to decide even or odd number: 76
76 is an even number
Do you want to continue? y-yes other characters-no y
Enter a number to decide even or odd number: 991
991 is an odd number
Do you want to continue? y-yes other characters-no n
Number of even numbers: 2
Number of odd numbers: 1
09/12/201 PYTHON CRASH 52
8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

PYTHON CRASH COURSE

FUNCTIONS

09/12/201 PYTHON CRASH 53


8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

INTRODUCTION
 Use keyword def to inform Python that you’re defining a
function:

def greet_user():
#Display a simple greeting. Function definition
print("Hello!")

greet_user() Function call

 Output

Hello!
09/12/201 PYTHON CRASH 54
8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

PASSING INFORMATION TO FUNCTION

def greet_user(username):
#Display a simple greeting.
print("Hello, " + username.title() + "!")

greet_user('jesse')

 Output

Hello, Jesse!

09/12/201 PYTHON CRASH 55


8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

POSITIONAL ARGUMENTS
 Positional arguments - values passed by a function match up with
the order of arguments.
 Example:
def describe_pet(animal_type, pet_name):
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "'s name is " + pet_name.title() + ".")

describe_pet('hamster', 'harry')
 Output

I have a hamster.
My hamster's name is Harry.

09/12/201 PYTHON CRASH 56


8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

KEYWORD ARGUMENTS
 Keyword argument is a name-value pair that you pass to a function.
 Example:
def describe_pet(animal_type, pet_name):
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "'s name is " + pet_name.title() + ".")

describe_pet(animal_type='hamster', pet_name='harry')
describe_pet(pet_name='harry', animal_type='hamster')

These 2 function calls


09/12/201 PYTHON CRASH are equivalent 5
8 COURSE 9
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

DEFAULT VALUES

When writing a function, you can define a default value for each parameter.

If an argument for a parameter is provided in the function call, Python uses
the argument value.
 If not, it uses the parameter’s default value. Example:
def describe_pet(pet_name, animal_type='dog'):

print("\nI have a " + animal_type + ".")


print("My " + animal_type + "'s name is " + pet_name.title() + ".")

describe_pet(pet_name='willie')
 Output
I have a dog.
My dog's name is Willie.
09/12/201 PYTHON CRASH 58
8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

DEFAULT VALUES (CONT.)


def describe_pet(pet_name, animal_type='dog'):
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "'s name is " +
pet_name.title() + ".")

describe_pet(pet_name='willie', animal_type= "cat")

 Output
I have a cat.
My cat's name is Willie.

09/12/201 PYTHON CRASH 59


8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

USING A FUNCTION WITH A WHILE LOOP


def get_formatted_name(first_name, last_name):
#Return a full name, neatly formatted.
full_name = first_name + ' ' + last_name
return full_name.title()

# This is an infinite loop!


while True:
print("\nPlease tell me your name:")
f_name = input("First name: ")
l_name = input("Last name: ")
formatted_name = get_formatted_name(f_name, l_name)
print("\nHello, " + formatted_name + "!")
09/12/201 PYTHON CRASH 60
8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

EXERCISE
 A program computes volume of a cylinder by requesting
user to enter radius in cm and height in cm. The formula
to calculate volume of a cylinder is
 volume = π * radius * radius * height
 Write a function definition calcVolume : accepts radius
and height in order to calculate volume by passing those
two arguments by value and return calculation of volume.

Save as func_VolumeOfCylinder.py

09/12/201 PYTHON CRASH 61


8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

EXERCISE (CONT.)
 Sample output:

--- Calculation of Volume of Cylinder ---


Please key in radius(cm) & height(cm): 5 5
The volume of cylinder is 392.70 cm^3

09/12/201 PYTHON CRASH 62


8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

PYTHON CRASH COURSE

DICTIONARIES

09/12/201 PYTHON CRASH 63


8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

DICTIONARIES

 Dictionaries allow you to connect pieces of related


information.
 Allow you to model a variety of real-world objects more

accurately.
 Create a dictionary representing a person then store as
much information as you want about the person – age,
name, location, profession.
 Store any two kinds of information that can be matched

such as a list of words and their meanings.


 A list of people’s name and their favorite number, a list of

mountains and their elevation.

09/12/201 PYTHON CRASH 64


8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

A SIMPLE DICTIONARY

 Consider a game featuring aliens that can have different


colors and point values.

alien_0={’color’ : ’green’ , ’points’ : 5}


print (alien_0[‘color’])
print (alien_0[‘points’])

Output:
green
5

09/12/201 PYTHON CRASH 65


8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

WORKING WITH DICTIONARIES

 key-value pairs.
 Each key is connected to a value.
 value - can be any number, a string, a list or even
another dictionary.
 When you provide a key, Python returns the value
associated with that key.

09/12/201 PYTHON CRASH 66


8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

WORKING WITH DICTIONARIES


Accessing values in a dictionary
alien_0={’color’:’green’,’points’:5}
print (alien_0[‘color’]);

Output:
green

alien_0={’color’:’green’,’points’:5}
new_points=alien_0[‘points’]
print (“You just earned ” + str(new_points)+ ”points!”)
Output:
You just earned 5 points!
09/12/201 PYTHON CRASH 67
8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

WORKING WITH DICTIONARIES


Adding New Key-Value Pairs
alien_0={’color’:’green’,’points’:5}
print (alien_0)
alien_0['x_position']=0
alien_0['y_position']=25
print(alien_0)

Output:
{‘color’: ‘green’, ‘points’:5}
{‘color’: ‘green’, ‘points’:5, ‘x_position’:0, ‘y_position’:25}

09/12/201 PYTHON CRASH 68


8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

WORKING WITH DICTIONARIES


Starting withan Empty Dictionary
alien_0={}
alien_0['color']='green'
Alien_0['points']=5
print(alien_0)

Output:
{‘color’: ‘green’, ‘points’:5}

09/12/201 PYTHON CRASH 69


8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

WORKING WITH DICTIONARIES


Modifying Values in a Dictionary
alien_0={’color’:’green’}
print(“The alien is “+ alien_0[‘color’]+”.”)
alien_0[‘color’]=’yellow’
print(“The alien now is “+ alien_0[‘color’]+”.”)

Output:

The alien is green.


The alien is now yellow.

09/12/201 PYTHON CRASH 70


8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

WORKING WITH DICTIONARIES


Removing Key-Value pairs
alien_0={’color’:’green’,’points’:5}
print(alien_0)

del alien_0[‘points’]
print(alien_0)

Output:
{‘color’: ‘green’, ‘points’:5}
{‘color’: ‘green’}

09/12/201 PYTHON CRASH 71


8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

WORKING WITH DICTIONARIES


A Dictionary of Similar Objects
favorite_languages ={
‘jen’: ‘python’,
‘sarah’: ‘c’,
‘edward’: ‘ruby’,
‘phil’: ‘python’,
}
print (“Sarah’s favorite language is “ +
favorite_languages[‘sarah’].title()+ “.”)

Output:
Sarah’s favorite language is C.
09/12/201 PYTHON CRASH 72
8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

LOOPING THROUGH A DICTIONARY


Looping Through All the Keys in a Dictionary
user_0 ={
‘username’: ‘efermi’,
‘first’: ‘enrico’,
‘last’: ‘fermi’,
}

for key,value in user_0.items():


print(“\nKey: ” +key) OR
print(“Value: ” +value)

for k,v in user_0.items():


print(“\nKey: ” +k)
print(“Value: ” +v)
09/12/201 PYTHON RASH 7
8 C COURSE 6
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

LOOPING THROUGH A DICTIONARY


Looping Through All the Key-Value Pairs
favorite_languages ={
‘jen’: ‘python’,
‘sarah’: ‘c’,
‘edward’: ‘ruby’,
‘phil’: ‘python’,
}

for name,language in favorite_languages.items():


print(name.title()+”’s favorite language is “+
language.title()+”.”)
Output:
Jen’s favorite language is Python.
Sarah’s favorite language is C.
Edward’s favorite language is Ruby.
09/1P2/h20i1l’8sfavorite language is PPYyTHthOoNnC.RASHCOURSE 7
7
Prepared by: NG HUI QUN

LOOPING THROUGH A DICTIONARY


Looping Through All the Keys in a Dictionary
favorite_languages ={
‘jen’: ‘python’,
‘sarah’: ‘c’,
‘edward’: ‘ruby’,
‘phil’: ‘python’,
}
for name in favorite_languages.keys():
print(name.title())
Output:
Jen
Sarah
Edward
09/12P/2h
01i8 PYTHON CRASH 7
l COURSE 8
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

LOOPING THROUGH A DICTIONARY


Looping Through All the Keys in a Dictionary
favorite_languages ={
‘jen’: ‘python’,
‘sarah’: ‘c’,
‘edward’: ‘ruby’,
‘phil’: ‘python’,
}
friends={‘phil’, ’sarah’}
for name in favorite_languages.keys():
print(name.title())
if name in friends:
print(“ Hi”+ name.title()+
“, I see your favorite language is “+
favorite_languages[name].title()+”!”)
09/12/201 PYTHON CRASH 76
8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

LOOPING THROUGH A DICTIONARY


Looping Through All the Keys in a Dictionary

Output:

Jen
Sarah
Hi Sarah, I see your favorite language is C!
Edward
Phil
Hi Phil, I see your favorite language is Python!

09/12/201 PYTHON CRASH 77


8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

LOOPING THROUGH A DICTIONARY


Looping Through All the Keys in a Dictionary
favorite_languages ={
‘jen’: ‘python’,
‘sarah’: ‘c’,
‘edward’: ‘ruby’,
‘phil’: ‘python’,
}

if ‘erin’not in favorite_languages.keys():
print (“Erin, please take our poll!”);

Output:
Erin, please take our poll!

09/12/201 PYTHON CRASH 78


8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

LOOPING THROUGH A DICTIONARY


Looping Through a Dictionary's Keys in
Order
 A dictionary links each key and its associated value, but you
never get the items from a dictionary in any predictable
order.
 You can return the item in a certain order by sorting the keys
as they’re return in the for loop- by using sorted()
function

09/12/201 PYTHON CRASH 79


8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

LOOPING THROUGH A DICTIONARY


Looping Through a Dictionary's Keys in
Order
favorite_languages ={
‘jen’: ‘python’,
‘sarah’: ‘c’,
‘edward’: ‘ruby’,
‘phil’: ‘python’,
}
for name in sorted(favorite_languages.keys()):
print(name.title())
Output:
Edward
Jen
Phil
09S/1a2/2r0a18 PYTHON CRASH 8
COURSE 3
h
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

LOOPING THROUGH A DICTIONARY


Looping Through All Values in a Dictionary
favorite_languages ={
‘jen’: ‘python’,
‘sarah’: ‘c’,
‘edward’: ‘ruby’,
‘phil’: ‘python’,
}
printf(“The following languages have been mentioned:”)
for language in favorite_languages.values()):
print(language.title())
Output:
The following languages have been mentioned:
Python
C
Python
0R
9/1u
2/b
20y
1 PYTHON CRASH COURSE
8 8
4
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

LOOPING THROUGH A DICTIONARY


Looping Through All Values in a Dictionary
favorite_languages ={
‘jen’: ‘python’,
‘sarah’: ‘c’,
‘edward’: ‘ruby’,
‘phil’: ‘python’,
}
printf(“The following languages have been mentioned:”)
for language in set(favorite_languages.values()):
print(language.title())
Output:
The following languages have been mentioned:
Python
C
Ruby
09/12/201 PYTHON CRASH 82
8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

NESTING

A List of Dictionaries
alien_0={‘color’:‘green’,‘points’:5}
alien_1={‘color’:‘yellow’,‘points’:10}
alien_2={‘color’:‘red’, ‘points’:15}
aliens=[alien_0, alien_1,alien_2]

for alien in aliens:


print(alien)

Output:

{‘color’: ‘green’, ‘points’:5}


{‘color’: ‘yellow’, ‘points’:10}
{‘color’: ‘red’, ‘points’:15}
09/12/201 PYTHON CRASH 83
8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

NESTING
A List of Dictionaries
#Make an empty list for storing aliens.
aliens =[]
#Make 30 green aliens.
for alien_number in range(30):
new_alien={‘color’: ‘green’, ‘points’:5, ‘speed’:
‘slow’}
aliens.append(new_alien)

#Show the first 5 aliens.


for alien in aliens[:5]:
print(alien)
print(“…”)
#Show how many aliens have been created
print( “Total number of aliens: ”+ str(len(aliens)))

09/12/201 PYTHON CRASH 84


8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

NESTING
A List of Dictionaries
Output:

{’speed’: ‘slow’, ‘color’: ‘green’, ‘points’:5}


{’speed’: ‘slow’, ‘color’: ‘green’, ‘points’:5}
{’speed’: ‘slow’, ‘color’: ‘green’, ‘points’:5}
{’speed’: ‘slow’, ‘color’: ‘green’, ‘points’:5}
{’speed’: ‘slow’, ‘color’: ‘green’, ‘points’:5}

Total number of aliens: 30

09/12/201 PYTHON CRASH 85


8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

NESTING
A List of Dictionaries (Change the First Three Items
#Make an empty list for storing aliens.
aliens=[]
#Make 30 green aliens.
for alien_number in range(30):
new_alien={‘color’: ‘green’, ‘points’:5, ‘speed’:‘slow’}
aliens.append(new_alien)
for alien in aliens[0:3]:
if alien[‘color’] == ‘green’:
alien[‘color’] =‘yellow’
alien[‘speed’] =‘medium’
alien[‘points’]= 10

#Show the first 5 aliens.


for alien in aliens[:5]:
print(alien)
print(“…”)

09/12/201 PYTHON CRASH 86


8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

NESTING
A List of Dictionaries
Output:

{’speed’: ‘medium’, ‘color’: ‘yellow’, ‘points’:10}


{’speed’: ‘medium’, ‘color’: ‘yellow’, ‘points’:10}
{’speed’: ‘medium’, ‘color’: ‘yellow’, ‘points’:10}
{’speed’: ‘slow’, ‘color’: ‘green’, ‘points’:5}
{’speed’: ‘slow’, ‘color’: ‘green’, ‘points’:5}

Total number of aliens: 30

09/12/201 PYTHON CRASH 87


8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

FILLING A DICTIONARY WITH USER INPUT (EXAMPLE)


responses = {}
polling_active = True
while polling_active:
name = input("\nWhat is your name? ")
response = input("Which mountain would you like to climb someday? ")
responses[name] = response
repeat = input("Would you like to let another person respond? (yes/ no) ")
if repeat == 'no':
polling_active = False

print("\n--- Poll Results ---")


for name, response in responses.items():
print(name + " would like to climb " + response + ".")
09/12/201 PYTHON CRASH 88
8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

FILLING A DICTIONARY WITH USER INPUT (EXAMPLE) (CONT.)

 Output:

What is your name? Eric


Which mountain would you like to climb someday? Denali
Would you like to let another person respond? (yes/ no) yes

What is your name? Lynn


Which mountain would you like to climb someday? Devil's Thumb
Would you like to let another person respond? (yes/ no) no

--- Poll Results ---


Lynn would like to climb Devil's Thumb.
Eric would like to climb Denali.
09/12/201 PYTHON CRASH 89
8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

EXERCISE
 Write a Python program that uses a loop to prompt user to
key-in name & marks of student & store the details using a
dictionary
 In while the loop, append the dictionary to a list named
list_student
 The program continues repetition when user enter ‘Y’ or
‘y’; otherwise it stops.
 After exiting the loop, print the average marks

Save as List_of_Dictionaries.py

09/12/201 PYTHON CRASH 90


8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

EXERCISE
 Sample output:

--- This program scans detail of students ---


Name: Susan
Marks: 20
Continue? (Y/y): y
Name: Fred
Marks: 30
Continue? (Y/y): Y
Name: Jane
Marks: 40
Continue? (Y/y): n
Average marks = 30.00

09/12/201 PYTHON CRASH 91


8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

PYTHON CRASH COURSE

DATAVISUALIZATION

09/12/201 PYTHON CRASH 92


8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

INSTALLING MATPLOTLIB (WINS)

1)Right-click This PC > Properties


2)At the left, click Advanced system settings
3)Click Environment Variables > New...
Path name: PATH
Path value: C:\Users\PCName\AppData\Local\Programs\Python\Python37-32;
C:\Users\PCName\AppData\Local\Programs\Python\Python37-32\Scripts
4)Restart PC
5)Go to cmd (Admin)
6) Type $python
You should be able to see the version of Python

NOTE: Path value may vary, depending on the file location

09/12/201 PYTHON CRASH 93


8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

INSTALLING MATPLOTLIB (WINS) (CONT.)

7) Open new cmd (Admin)


At cmd (Admin), type these commands:
C:\WINDOWS\system32 >python -m pip install -U pip
C:\WINDOWS\system32 >pip install matplotlib

SUMMARY:
1.Add Python folder to system path
2.Upgrade pip using command prompt
3. Install matplotlib using 'pip install matplotlib'

09/12/201 PYTHON CRASH 94


8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

INSTALLING MATPLOTLIB (LINUX)

$ sudo apt-get install python3-matplotlib

If you’re running Python 2.7, use this line:


$ sudo apt-get install python-matplotlib

Then use pip to install matplotlib:


$ pip install --user matplotlib

09/12/201 PYTHON CRASH 95


8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

DATA VISUALIZATION

 Making beautiful representations of data.


 To see patterns and significance of your datasets.
 Python is used for data-intensive work in genetics, climate
research, political and economic analysis.
 Example tools in Python for data visualization: matplotlib and
Pygal.
 matplotlib :mathematical plotting library. To make simple plots
such as line graphs and scatter plots.
 Pygal: creating visualisation that works well on digital devices.
 https://ehmatthes.github.io/pcc/solutions/chapter_16.html

09/12/201 PYTHON CRASH 96


8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

PLOTTING A SIMPLE LINE GRAPH


import matplotlib.pyplot as plt
squares=[1, 4, 9, 16, 25]
plt.plot(squares)
plt.show()

PLOTTING A SIMPLE ARRAY


import matplotlib.pyplot as plt
squares=[1, 4, 9, 16, 25]
plt.plot(squares,linewidth=5)
#Set chart title and label axes
plt.title(“Square Number”, fontsize=24)
plt.xlabel(“Value”,fontsize=14)
plt.ylabel(“Square of Value”,fontsize=14)
# Set size of tick labels.
plt.tick_params(axis=‘both’,labelsize=14)
plt.show()
09/12/201 PYTHON CRASH 97
8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

CORRECTING THE PLOT


import matplotlib.pyplot as plt

input_values=[1, 2, 3, 4, 5]
squares=[1, 4, 9, 16, 25]
plt.plot(input_value, squares, linewidth=5)

#Set chart title and label axes


plt.title(“Square Number”, fontsize=24)
plt.xlabel(“Value”,fontsize=14)
plt.ylabel(“Square of Value”,fontsize=14)

# Set size of tick labels.


plt.tick_params(axis=‘both’,labelsize=14)

plt.show()
09/12/201 PYTHON CRASH 98
8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

CALCULATING DATA AUTOMATICALLY


import matplotlib.pyplot as plt

x_values= list(range(1, 1001))


y_values =[x**2 for x in x_values]

#Set chart title and label axes


plt.title(“Square Number”, fontsize=24)
plt.xlabel(“Value”,fontsize=14)
plt.ylabel(“Square of Value”,fontsize=14)

# Set size of tick labels.


plt.tick_param(axis=‘both’,labelsize=14)

plt.scatter (x_values, y_values, s=40)


plt.axis ([0,1100,0,1100000])
plt.show()
09/12/201 PYTHON CRASH 99
8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

DEFINING CUSTOM COLORS


import matplotlib.pyplot as plt

x_values= list(range(1, 1001))


y_values =[x**2 for x in x_values]

#Set chart title and label axes


plt.title(“Square Number”, fontsize=24)
plt.xlabel(“Value”,fontsize=14)
plt.ylabel(“Square of Value”,fontsize=14)

# Set size of tick labels.


plt.tick_param(axis=‘both’,labelsize=14)

plt.scatter (x_values, y_values, c=‘red’,


edgecolor=‘none’,s=40)
plt.axis ([0,1100,0,1100000])
plt.show()
09/12/2018
COURSE
PYTHON CRASH 10
0
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

USING A COLORMAP
import matplotlib.pyplot as plt

x_values= list(range(1, 1001))


y_values =[x**2 for x in x_values]

#Set chart title and label axes


plt.title(“Square Number”, fontsize=24)
plt.xlabel(“Value”,fontsize=14)
plt.ylabel(“Square of Value”,fontsize=14)

# Set size of tick labels.


plt.tick_param(axis=‘both’,labelsize=14)

plt.scatter (x_values, y_values, c=y_values,


cmap=plt.cm.Blues, s=40)
plt.axis ([0,1100,0,1100000])
plt.show()
09/12/2018
COURSE
PYTHON CRASH 10
1
Prepared by: NG HUI QUN &MUKRIMAH NAWIR Download the sitka_weather_07-2014.csv
READING CSV FILE at the link:
https://github.com/Malekai/Downloading-Data
import csv & save it to the folder where you store the code
from matplotlib import pyplot as plt
from datetime import datetime Code name:mpl_read_sitka_weather.py

filename='sitka_weather_07-2014.csv'
with open(filename) as f:
reader = csv.reader(f)
header_row = next(reader)

dates, highs = [], []


for row in reader:
current_date = datetime.strptime(row[0], "%Y-%m-%d")
dates.append(current_date)
highs.append(int(row[1]))
# Plot data.
fig = plt.figure(figsize=(10, 6))
plt.plot(dates, highs, c='blue')
# Format plot.
fig.autofmt_xdate() #draw the date labels diagonally
#to prevent them from overlapping.
plt.title("Daily high temperatures, July 2014", fontsize=24)
plt.xlabel('', fontsize=16)
plt.ylabel("Temperature (F)", fontsize=16)
plt.tick_params(axis='both', which='major', labelsize=16)
09/12/2018 PYTHON CRASH 10
plt.show()
COURSE 6
Prepared by: NG HUI QUN &MUKRIMAH NAWIR

THE DATETIME MODULE


 Data will be read as a string, so data will be read in as a string.
 Using the strptime() method from the datetime module.
 First argument is the date and the second tell how the date is formatted.

09/12/201 PYTHON CRASH 10


8 COURSE 7

You might also like