• No results found

PythonSlide Latest 2018-Converted

N/A
N/A
Protected

Academic year: 2021

Share "PythonSlide Latest 2018-Converted"

Copied!
103
0
0

Loading.... (view fulltext now)

Full text

(1)

09/12/201 09/12/201 8 8 PYTHON CRASH PYTHON CRASH COURSE COURSE 1 1 Organized by School of Com

Organized by School of Computer and Communputer and Communicationication EngineEngineeringering

School of Compu

(2)
(3)

P

PY

YT

TH

HO

ON C

N CR

RA

ASH

SH COU

COURSE

RSE

V

Varia

ariables and Simpl

bles and Simple Data Types

e Data Types

Intro

Introduct

duction and

ion and Worki

Working wi

ng witth

h LI

LIST

STS

S

IF

IF St

Sta

ate

tem

men

ents

ts

Us

User

er In

Inpu

put

t and

and While

While lo

loop

ops

s

Functions

Functions

Dic

Dicti

tiona

onarie

ries and Dat

s and Data

a Visu

Visualiz

alizat

ation

ion

10.00am 10.00am 9.00am 9.00am 1 100..0000aamm 1122..0000ppmm 1 122..0000ppmm 11..0000ppmm 1.00pm 1.00pm

B

B

R

R

E

E

A

A

K

K

T

T

I

I

M

M

E

E

2 2..0000ppmm 3..03 000ppmm 3 3..0000ppmm 4..04 000ppmm 4.00pm 4.00pm 2.00pm 2.00pm 5.15pm 5.15pm 09/12/201 09/12/201 8 8 PYTHON CRASH PYTHON CRASH COURSE COURSE 2 2

(4)

VARIABLES

VARIABLES

SI

SI

MP

MP

LE D

LE D

A

A

T

T

A

A

TYPES

TYPES

09/12/201 09/12/201 8 8 PYTHON CRASH PYTHON CRASH COURSE COURSE 3 3

P

(5)

message

=

“Hello Python World!”

message

=

“Hello Python World!”

print (

message

)

print (“Hello Python World!”)

Hello Python World!

print (

message

)

Hello Python World!

message

=

“Hello Python

Crash Course

World!”

print (

message

)

Hello Python World!

Hello Python Crash Course World! 09/12/201 8 PYTHON CRASH COURSE 4

VARIABLES

word

 print 

, it prints to the screen whatever is inside the parentheses.

(6)

 09/12/201 8 PYTHON CRASH COURSE 5   

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

(7)

STRINGS

Mukrimah Nawir 

MUKRIMAH NAWIR

mukrimah nawir 

Hello, Mukrimah Nawir!

 A series of characters. Anything inside quotes is considered a

string in Python and you can use

 s ing le or double quotes

Output:

String with Methods

Name

= “ mukrimah nawir”

print(Name

.title()

)

print(Name

.upper()

)

print(Name

.lower()

)

Combining and Concatenating Strings

first_name=”mukrimah”

last_name=”nawir”

mukrimah nawir 

09/12/201 8

PYTHON CRASH COURSE

6

full_name= first_name + “ “ + last_name

print(full_name)

(8)

STRINGS

Python

Languages:

Python

C

JavaScript

One of the Python's strengths is its diverse community

Output:

Python

09/12/201 8 PYTHON CRASH COURSE 7

String with Tabs

print(“Python”)

print(“

 \t

Python”)

String with Newlines

print(“Languages: \nPython \nC \nJavaScript”)

String with Apostrophe

message=

One of Python

's

strengths is its diverse community.

print(message)

message=

'

One of Python

's

strengths is its diverse community.

'

print(message)

rstrip() : right strip

lstrip() : left strip

SyntaxError: invalid syntax

(9)

Integers

NUMBERS

 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 8 PYTHON CRASH COURSE 8

(10)

9

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

PY

o

TH

m

ON C

m

RAS

e

H

n

CO

t

UR

w

SE

ith few

(11)

 

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 8 PYTHON CRASH COURSE 10

(12)

PY

PYTHO

THON CR

N CRASH

ASH CO

COUR

URSE

SE

09/12/201 09/12/201 8 8 PYTHON CRASH PYTHON CRASH COURSE COURSE 1 111

INTRODUCT

INTRODUCT

ION &

ION &

W

W

O

O

R

R

K

K

I

I

N

N

G

G

W

W

I

I

T

T

H

H

LISTS

(13)

   

IN

IN

T

T

RO

RO

DU

DU

CT

CT

IO

IO

N TO

N TO

LI

LI

S

S

TS

TS

 A

 A list is a collection

list is a collection of items in a particula

of items in a particularr order 

order 

[[ ]] in

indi

dica

cate

tes

s a

a lilist

st an

and

d in

indi

divi

vidu

dual

al el

elem

emen

ents

ts in

in th

the

e lilist

st ar

are

e se

sepa

para

rate

ted

d

by commas

by commas

bicy

bicycles =

cles = ['trek

['trek','c

','cannond

annondale', 'redline

ale', 'redline',', 'spec

'specializ

ialized']

ed']

print(bicycles)

print(bicycles)

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

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

 

 Accessing Elements in a

 Accessing Elements in a List

List

List are ordered collections, access any element in a list

List are ordered collections, access any element in a list by telling

by telling

Pytho

Python the posit

n the position/in

ion/index of th

dex of the item

e item desir

desired.

ed.

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

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

print(bicycles[0])

print(bicycles[0])

print(bicycles[0].title())

print(bicycles[0].title())

trek

trek

Trek

Trek

09/12/201 09/12/201 8 8 PYTHON CRASH PYTHON CRASH COURSE COURSE 12 12

(14)

IN

IN

TRO

TRO

DU

DU

CTI

CTI

ON

ON

TO

TO

LIS

LIS

TS

TS

(CONT.)

(CONT.)

 

Inde

Index Posi

x Positio

tions St

ns Start at 0, No

art at 0, Nott 1

1

  

Python considers the first item in a

Python considers the first item in a list to be at

list to be at position 0, not position 1

position 0, not position 1

Special syntax for accessing the

Special syntax for accessing the last element

last element

in a list by asking for the

in a list by asking for the

item at index

item at index -1

-1

bicycles = ['trek','cannondale', 'redline', 'specialized'] bicycles = ['trek','cannondale', 'redline', 'specialized'] print(bicycles[1]) print(bicycles[1]) print(bicycles[3]) print(bicycles[3]) print(bicycles[-1]) print(bicycles[-1]) print(bicycles[-2]) print(bicycles[-2])

cannondale

cannondale

specialized

specialized

specialized

specialized

redline

redline

Using Indiv

Using Individual V

idual Valu

alues

es from a

from a List

List

Use

Use concatenation

concatenation

to create a message based on a

to create a message based on a va

va

lu

lu

e f

e f

ro

ro

m a

m a

li

li

st

st

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

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

message= “My first

message= “My first

bicycle

bicycle

was a”was a”

+

+

bicycles[0].title()+”.”bicycles[0].title()+”.”

print(message)

print(message)

My first bic

My first bic

ycle wa

ycle wa

s a

s a

T

T

rek

rek

.

.

09/12/201 09/12/201 8 8 PYTHON CRASH PYTHON CRASH COURSE COURSE 13 13

(15)

ELEMENTS

Modifying elements in a list

cars = ['peugeot','merc', 'mazda']

print(cars)

cars[0]='myvi'

print(cars)

['

peugeot'

,'merc', 'mazda']

[

'myvi'

,'merc', 'mazda']

 Adding elements in a list

 –

.append() or .insert()

cars

.append

= ('volvo')

print(cars)

cars

.insert

(2,'kancil')

print(cars)

[

'myvi'

,'merc', 'mazda','volvo']

[

'myvi'

,'merc', 'kancil', 'mazda','volvo']

Removing elements in a list

 –

del

cars = ['peugeot','merc', 'mazda']

print(cars)

del cars[0]

print(cars)

['

peugeot'

,'merc', 'mazda']

['merc', 'mazda']

09/12/201 8 PYTHON CRASH COURSE 14

(16)

(CONT.)

Removing elements in a list - .pop()

motorcycles = ['honda','yamaha', 'suzuki'] print(motorcycles) popped_motorcycle=motorcycles.pop() print(motorcycles) print(popped_motorcycles)

['honda','yamaha', 'suzuki']

['honda','yamaha']

suzuki

['honda','yamaha', 'suzuki','ducati']

['honda','yamaha', 'suzuki']

09/12/201 8 PYTHON CRASH COURSE 15

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')

print(motorcycles)

(17)

ORGANIZING A LIST

09/12/201 8 PYTHON CRASH COURSE 16

Printing a List in Reverse Order -

.reverse()

cars = ['bmw', 'audi', 'toyota', 'subaru'] print(cars)

cars.reverse

print(cars)

Finding the length of a list -

len()

cars = ['bmw', 'audi', 'toyota', 'subaru']

len(cars) 4

output

['bmw', 'audi', 'toyota', 'subaru'] ['subaru', 'toyota','audi', 'bmw' ]

Here is the original list:

['bmw', 'audi', 'toyota', 'subaru'] Here is the sorted list:

['audi','bmw', subaru', 'toyota', ]

Sorting a List Permanently

 – .sort()

cars = ['bmw', 'audi', 'toyota', 'subaru']

cars.sort()

print(cars)

Sorting a List Temporarily

 – sorted()

cars = ['bmw', 'audi', 'toyota', 'subaru']

print(“Here is the original list:”) print(“\nHere is the sorted list:”)

print(sorted(cars))

(18)

WORKING WITH LISTS

Looping Through Entire List

 09/12/201 8 PYTHON CRASH COURSE 17   

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!”)

(19)

ORGANIZING A LIST

09/12/201 8 PYTHON CRASH COURSE 18

Printing a List in Reverse Order -

.reverse()

cars = ['bmw', 'audi', 'toyota', 'subaru'] print(cars)

cars.reverse

print(cars)

Finding the length of a list -

len()

cars = ['bmw', 'audi', 'toyota', 'subaru']

len(cars) 4

output

['bmw', 'audi', 'toyota', 'subaru'] ['subaru', 'toyota','audi', 'bmw' ]

Here is the original list:

['bmw', 'audi', 'toyota', 'subaru'] Here is the sorted list:

['audi','bmw', subaru', 'toyota', ]

Sorting a List Permanently

 – .sort()

cars = ['bmw', 'audi', 'toyota', 'subaru']

cars.sort()

print(cars)

Sorting a List Temporarily

 – sorted()

cars = ['bmw', 'audi', 'toyota', 'subaru']

print(“Here is the original list:”) print(“\nHere is the sorted list:”)

print(sorted(cars))

(20)

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 8 PYTHON CRASH COURSE 19

(21)

2 0

Using the range() Function

MAKING NUMERICAL LIST

Range()

function starts counting at the

first value you give and stops when it

reaches the second value. Therefore, the

output never contains the end value.

Using the range() to Make a List of Numbers

Starting number is 2

Adds 2 repeatedly until it reaches or passes the end value

For value in range(1,5)

print(value)

1 2 3 4 c 1 2 3 4

numbers = list(range(1,6))

print(numbers)

[1, 2, 3, 4, 5]

even_numbers = list(range(2,11,2))

print(even_numbers)

[2, 4, 6, 8, 10]

squares = []

for value in range(1,11):

square = value**2

09/12/20

s

18

quares.append(square

P

)

YTHON CRASH

(22)

MAKING NUMERICA LISTS (CONT.)

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 = [value**2 in range (1,11)] print (squares)

digits = [1,2,3,4,5,6,7,8,9,0]

print(min(digits)

print(max(digits)

print(sum(digits)

0 9 45 squares = []

for value in range (1,11):

squares.append(value**2) print (squares)

Simple Statistics with a List of Numbers

You can easily find the minimum, maximum and sum of a list of numbers.

09/12/201 8

PYTHON CRASH COURSE

(23)

WORKING WITH PART OF A LIST

09/12/201 8 PYTHON CRASH COURSE 22 

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 2

nd

,3

rd

and 4

th

items, you would request indices 1 through 4.

players =[‘charles’,’martina’,’micheal’, ‘florence’,’eli’]

print(players[1:4])

[martina’,’micheal',‘florence’

]

(24)

WORKING WITH PART OF A LIST (CONT.)

09/12/201 8 PYTHON CRASH COURSE 23

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’

]

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

]

If you want all items from the third item through the last item.

players =[‘charles’,’martina’,’micheal’, ‘florence’,’eli’]

print(players[2:])

The last three players on the list.

players =[‘charles’,’martina’,’micheal’, ‘florence’,’eli’]

print(players[-3:])

(25)

WORKING WITH PART OF A LIST (CONT.)

09/12/201 8 PYTHON CRASH COURSE 24

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())

The first three players: Charles

Martina Michael Output:

(26)

09/12/201 8 PYTHON CRASH COURSE 2 5

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:

[‘pizza’,`falafel’,`carrot cake’,’ice cream’]

(27)

09/12/2018 PYTHON CRASH COURSE 26

Defining a Tuple

dimensions=(200, 50) print(dimensions[0]); print(dimensions[1]); 200 50

TUPLES

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).

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

(28)

09/12/201 8 PYTHON CRASH CO URS E 2 7

Looping Through All Values in a Tupple

You can loop over all the values in a tuple using a for loop.

200 50

TUPLES (CONT.)

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: print(dimension)

dimensions=(400, 100)

print(“\n Modified dimensions:”)

for dimension in dimensions: print(dimension) Original dimensions: 200 50 Modified dimensions: 400 100 dimensions=(200, 50)

for dimension in dimensions: print(dimension)

(29)

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 8

PYTHON CRASH COURSE

28

(30)

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 8

PYTHON CRASH COURSE

(31)

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 8 PYTHON CRASH COURSE 30

EXERCISE

(32)

PYTHON CRASH COURSE

09/12/201 8 PYTHON CRASH COURSE 31

IFSTATEMENTS

(33)

A SIMPLE EXAMPLE

Output:

 Audi

BMW

Subaru

Toyoto

cars = ['audi', 'bmw', 'subaru', 'toyota']

for car in cars:

if car == 'bmw':

print(car.upper())

else:

print(car.title())

CONDITIONAL TESTS

Checking for Equality

>>> car = 'bmw'

>>> car == 'bmw'

>>> car = 'audi'

>>> 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

True

False

09/12/201 8 PYTHON CRASH COURSE 32

(34)

Output:

Hold the anchovies!

09/12/201 8

PYTHON CRASH COURSE

33

CONDITIONAL TESTS (CONT.)

Checking for Inequality

requested_topping = 'mushrooms'

if requested_topping != 'anchovies':

print(“Hold the anchovies!”)

Numerical Comparisons

>>> age = 19

>>> age < 21

>>> age = 19

>>> age <= 21

>>> age = 19

>>> age > 21

>>> age = 19

>>> age >= 21

(35)

Simple if Statements

age = 19

if age >= 18:

print("You are old enough to vote!")

09/12/201 8 PYTHON CRASH COURSE 34

if Statements

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.

(36)

The if-elif-else Chain

09/12/201 8 PYTHON CRASH COURSE 35 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) + ".")

(37)

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 8

PYTHON CRASH COURSE

36

Using Multiple elif Blocks

(38)

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 8

PYTHON CRASH COURSE

37

Omitting the else Block

(39)

 Adding mushrooms.  Adding extra cheese.

Finished making your pizza!

09/12/201 8

PYTHON CRASH COURSE

38

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!")

(40)

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!")

09/12/201 8 PYTHON CRASH COURSE 39  Adding mushrooms.

Finished making your pizza!

(41)

09/12/201 8

 ASH COURSE

4

print("\nFinished making your pizza!")

USING if Statement WITH LISTS

 Adding mushrooms  Adding green peppers.  Adding extra cheese.

Finished making your pizza!

C heck ing for S pecial Items

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

for requested_topping in requested_toppings:

print("Adding " + requested_topping + ".")

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. PYTHON CR Adding extra cheese.

(42)

09/12/201 8  ASH COURSE 4 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?")

USING if Statement WITH LISTS (CONT.)

 Are you sure you want a plain pizza?

C hecking That a Lis t Is Not Empty 

print("\nFinished making your pizza!")  Adding mushrooms.

Sorry, we don't have french fries. PYTHON CR Adding extra cheese.

Us ing Multiple Lis ts

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:

(43)

PYTHON CRASH COURSE

09/12/201 8 PYTHON CRASH COURSE 42

USERINPUT

&

WHILELOOPS

(44)

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 8 PYTHON CRASH COURSE 43

(45)

INTRODUCTION (CONT.)

 Another method:

x = input('Enter your name:')

print('Hello, ' + x)

Output:

Enter your name:

Sarah

Hello, Sarah

09/12/201 8 PYTHON CRASH COURSE 44

(46)

PYTHON

09/12/201 8 PYTHON CRASH COURSE 45

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()

(47)

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 8 PYTHON CRASH COURSE 46

(48)

09/12/201 8 PYTHON CRASH COURSE 4 7

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

(49)

09/12/201 8 PYTHON CRASH COURSE 4 8

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 quit

(50)

09/12/201 8 PYTHON CRASH COURSE 4 9

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

(51)

09/12/201 8 5 0

EXERCISE (CONT.)

Sample output:

Table of Celsius and Fahrenheit degrees

Degrees

Celsius

Degrees

Celsius

0.00

32.00

20.00

68.00

40.00

104.00

60.00

140.00

80.00

176.00

(52)

EXERCISE

09/12/201 8 PYTHON CRASH COURSE 51

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.

(53)

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

8

PYTHON CRASH COURSE

(54)

PYTHON CRASH COURSE

09/12/201 8 PYTHON CRASH COURSE 53

FUNCTIONS

(55)

INTRODUCTION

Use keyword def 

to inform Python that you’re defining

a

function:

def greet_user():

#Display a simple greeting.

print("Hello!")

greet_user()

Function call

Function definition 

Output

Hello!

09/12/201 8 PYTHON CRASH COURSE 54

(56)

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 8 PYTHON CRASH COURSE 55

(57)

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 8

PYTHON CRASH COURSE

(58)

09/12/201 8 PYTHON CRASH COURSE 5 9

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 are equivalent

(59)

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 8

PYTHON CRASH COURSE

(60)

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 8

PYTHON CRASH COURSE

(61)

USING A FUNCTION WITH A WHILE LOOP

09/12/201 8 PYTHON CRASH COURSE 60

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 + "!")

(62)

EXERCISE

09/12/201 8 PYTHON CRASH COURSE 61

 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.

(63)

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 8

PYTHON CRASH COURSE

(64)

DICTIONARIES

09/12/201 8 PYTHON CRASH COURSE 63

PYTHON CRASH COURSE

(65)

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 8 PYTHON CRASH COURSE 64

DICTIONARIES

(66)

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 8 PYTHON CRASH COURSE 65

(67)

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 8

PYTHON CRASH COURSE

66

(68)

WORKING WITH DICTIONARIES

Accessing values in a dictionar y

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

8

PYTHON CRASH COURSE

(69)

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 8

PYTHON CRASH COURSE

(70)

WORKING WITH DICTIONARIES

Starting with an Empty Dictionary

alien_0={}

alien_0['color']='green'

Alien_0['points']=5

print(alien_0)

Output:

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

09/12/201 8

PYTHON CRASH COURSE

(71)

WORKING WITH DICTIONARIES

Modifying Values in a Dictionar y

alien_0={’color’:’green’}

print(“Th

e 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 8

PYTHON CRASH COURSE

(72)

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 8 PYTHON CRASH COURSE 71

(73)

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

8

PYTHON CRASH COURSE

(74)

09/12/201 8 PYTHON C RASH COURSE 7 6 print(“\nKey: print(“Value: ” +key) ” +value)

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():

for k,v in user_0.items():

print(“\nKey: ” +k)

print(“Value: ” +v)

(75)

7 7

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.

(76)

PYTHON CRASH COURSE

7 8

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/12

P

/2

h

01

i

8

l

(77)

LOOPING THROUGH A DICTIONARY

09/12/201 8 PYTHON CRASH COURSE 76

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()+”!”)

(78)

Looping

Looping

T

T

hroug

hroug

h All the

h All the

K

K

e

e

y

y

s i

s i

n a

n a

Di

Di

ct

ct

io

io

na

na

r

r

y

y

LOOPI

LOOPI

NG TH

NG TH

RO

RO

UGH

UGH

A

A

DI

DI

CT

CT

ION

ION

AR

AR

Y

Y

Output:

Output:

Jen

Jen

Sarah

Sarah

Hi Sarah

Hi Sarah

, I see you

, I see you

r favor

r favor

ite la

ite la

ngu

ngu

age is

age is

C!

C!

Edward

Edward

Phil

Phil

Hi Phil

Hi Phil

, I see your fav

, I see your fav

orite l

orite l

angu

angu

age is

age is

Pytho

Pytho

n!

n!

09/12/201 09/12/201 8 8 PYTHON CRASH PYTHON CRASH COURSE COURSE 77 77

(79)

LOOPI

LOOPI

NG TH

NG TH

RO

RO

UGH

UGH

A

A

DI

DI

CT

CT

ION

ION

AR

AR

Y

Y

Looping

Looping

T

T

hroug

hroug

h All the

h All the

K

K

e

e

y

y

s i

s i

n a

n a

Di

Di

ct

ct

io

io

na

na

r

r

y

y

favorite_l

favorite_languages

anguages ={

={

‘jen’: ‘python’,

‘jen’: ‘python’,

‘sarah’: ‘c’,

‘sarah’: ‘c’,

‘edward’: ‘ruby’,

‘edward’: ‘ruby’,

‘phil’: ‘python’,

‘phil’: ‘python’,

}

}

if

if

 ‘erin’

 ‘erin’

not

not in

in favori

favorite_l

te_langu

anguages

ages.key

.keys():

s():

print

print

 (“Erin,

 (“Erin,

 please take our

 please take our

 poll!”);

 poll!”);

Output:

Output:

Erin,

Erin,

pleas

pleas

e take

e take

our

our

poll

poll

!

!

09/12/201 09/12/201 8 8 PYTHON CRASH PYTHON CRASH COURSE COURSE 78 78

(80)

LOOPI

LOOPI

NG TH

NG TH

RO

RO

UGH

UGH

A

A

DI

DI

CT

CT

ION

ION

AR

AR

Y

Y

Looping Throu

Looping Throu

gh a D

gh a D

ictionar 

ictionar 

y's Keys in

y's Keys in

Order 

Order 

09/12/201 09/12/201 8 8 PYTHON CRASH PYTHON CRASH COURSE COURSE 79 79 

A dictionary links each key a

A dictionary lin

ks each key and it

nd its

s associated val

associated value

ue,, but

but you

you

never get the items from a dictionary in any predictable

never get the items from a dictionary in any predictable

order.

order.

Y

You can return t

ou can return the i

he item

tem in a certai

in a certain or

n order

der b

by

y sor

sortin

ting the

g the ke

keys

ys

as

as

they’re

they’re

return in the

return in the

for

for

loo

loop- by

p- by using

using

sorted()

sorted()

function

function

(81)

PYTHON CRASH COURSE

8 3

LOOPING THROUGH A DICTIONARY

Looping Through a Dictionar y'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

09

S

/1

a

2/2

0

a

18

(82)

PYTHON CRASH COURSE

8

LOOPING THROUGH A DICTIONARY

Looping Through All Values in a Dictionar y

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

0

R

9/1

u

2/

b

20

y

1 8

(83)

LOOPING THROUGH A DICTIONARY

Looping Through All Values in a Dictionar y

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 8 PYTHON CRASH COURSE 82

(84)

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 8

PYTHON CRASH COURSE

(85)

NESTING

09/12/201 8 PYTHON CRASH COURSE 84

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

(86)

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 8

PYTHON CRASH COURSE

(87)

NESTING

09/12/201 8 PYTHON CRASH COURSE 86

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)

(88)

NESTING

{’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 8 PYTHON CRASH COURSE 87

A List of Dictionaries

Output:

(89)

FILLING A DICTIONARY WITH USER INPUT (EXAMPLE)

09/12/201 8 PYTHON CRASH COURSE 88 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():

(90)

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 8

PYTHON CRASH COURSE

(91)

EXERCISE

09/12/201 8 PYTHON CRASH COURSE 90

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

(92)

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 8 PYTHON CRASH COURSE 91

(93)

DATAVISUALIZATION

09/12/201 8 PYTHON CRASH COURSE 92

PYTHON CRASH COURSE

(94)

INSTALLING MATPLOTLIB (WINS)

09/12/201 8 PYTHON CRASH COURSE 93 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 b e able to see the version of Python

(95)

INSTALLING MATPLOTLIB (WINS) (CONT.)

09/12/201 8 PYTHON CRASH COURSE 94

7) Open new cmd (Admin)

At cmd (Admin), type these commands:

C:\WINDOWS\sys tem32 >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

(96)

INSTALLING MATPLOTLIB (LINUX)

09/12/201 8 PYTHON CRASH COURSE 95

$ 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:

(97)

DATA VISUALIZATION

09/12/201 8 PYTHON CRASH COURSE 96

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

(98)

import matplotlib.pyplot as plt squares=[1, 4, 9, 16, 25] plt.plot(squares) plt.show() 09/12/201 8 PYTHON CRASH COURSE 97

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()

(99)

CORRECTING THE PLOT

09/12/201 8 PYTHON CRASH COURSE 98 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)

(100)

CALCULATING DATA AUTOMATICALLY

09/12/201 8 PYTHON CRASH COURSE 99 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])

(101)

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) 09/12/2018 PYTHON CRASH COURSE plt.axis ([0,1100,0,1100000]) 10 0 plt.show()

(102)

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) 09/12/2018 PYTHON CRASH COURSE plt.axis ([0,1100,0,1100000]) 10 1 plt.show()

(103)

09/12/2018 PYTHON CRASH COURSE 10 6

READING CSV FILE

import csv

from matplotlib import pyplot as plt from datetime import datetime

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) plt.show()

https://github.com/Malekai/Downloading-Data & save it to the folder where you store the code Code name:mpl_read_sitka_weather.py

References

Related documents

We present a novel algorithm called rotation-and-scale invariant nonlo- cal means filter (RSNLM) to simultaneously remove mixed noise from different kinds of three-dimensional (3D)

Nonetheless, with the loss of lucrative Libyan oil concessions for Western companies and with Qadhafi soon accused of funding countless governments and movements around the

Rosemary Mushroom Caps and Grilled Portobello Mushrooms Over Roasted Garlic and Asiago Whole Wheat Coucous captured the taste buds of judges at the Make It With Mushrooms

To obtain a motorcycle learner’s licence in addition to your regular driver’s licence, you must pass the following tests: 1 a written test on motorcycle safety rules.. 2 a

Notes were taken of the types of information that were requested from parties submitting appeals , including identifying and contact information, as well as whether they

8-9 Evaluating Portfolio Risk and Diversification • Unlike expected return, standard deviation is not generally equal to the a weighted average of the standard deviations of

“Touch early, touch often.” Just like during a nightclub approach, if you don’t touch early it will be awkward to touch later, and a guy who doesn’t start touching until he gets

The distance from each 250 meters square grid center in Dhaka, Chittagong and Sylhet to source fault models were calculated and PGA, PGV and Sa (h=5%, T=0.3 and 1.0 sec) were