Professional Documents
Culture Documents
PythonSlide Latest 2018
PythonSlide Latest 2018
1.00pm
BREAK TIME 2.00pm
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.
STRINGS
A series of characters. Anything inside quotes is considered a
string in Python and you can use single or double quotes
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
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
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.
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']
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
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
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)
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’ ]
[‘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’ ]
my_foods.append(‘cannoli’)
friend_foods.append(‘ice cream’)
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]);
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
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
Indentation
PEP 8 recommends four spaces per indentation level.
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
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.
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
IFSTATEMENTS
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
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) + ".")
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) + ".")
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) + ".")
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!
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.
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:
INTRODUCTION (CONT.)
Another method:
x = input('Enter your name:')
print('Hello, ' + x)
Output:
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
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
EXERCISE (CONT.)
Sample output:
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
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
FUNCTIONS
INTRODUCTION
Use keyword def to inform Python that you’re defining a
function:
def greet_user():
#Display a simple greeting. Function definition
print("Hello!")
Output
Hello!
09/12/201 PYTHON CRASH 54
8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR
def greet_user(username):
#Display a simple greeting.
print("Hello, " + username.title() + "!")
greet_user('jesse')
Output
Hello, Jesse!
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.
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')
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'):
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
Output
I have a cat.
My cat's name is Willie.
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
EXERCISE (CONT.)
Sample output:
DICTIONARIES
DICTIONARIES
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
A SIMPLE DICTIONARY
Output:
green
5
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.
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
Output:
{‘color’: ‘green’, ‘points’:5}
{‘color’: ‘green’, ‘points’:5, ‘x_position’:0, ‘y_position’:25}
Output:
{‘color’: ‘green’, ‘points’:5}
Output:
del alien_0[‘points’]
print(alien_0)
Output:
{‘color’: ‘green’, ‘points’:5}
{‘color’: ‘green’}
Output:
Sarah’s favorite language is C.
09/12/201 PYTHON CRASH 72
8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR
Output:
Jen
Sarah
Hi Sarah, I see your favorite language is C!
Edward
Phil
Hi Phil, I see your favorite language is Python!
if ‘erin’not in favorite_languages.keys():
print (“Erin, please take our poll!”);
Output:
Erin, please take our poll!
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]
Output:
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)
NESTING
A List of Dictionaries
Output:
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
NESTING
A List of Dictionaries
Output:
Output:
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
EXERCISE
Sample output:
DATAVISUALIZATION
SUMMARY:
1.Add Python folder to system path
2.Upgrade pip using command prompt
3. Install matplotlib using 'pip install matplotlib'
DATA VISUALIZATION
input_values=[1, 2, 3, 4, 5]
squares=[1, 4, 9, 16, 25]
plt.plot(input_value, squares, linewidth=5)
plt.show()
09/12/201 PYTHON CRASH 98
8 COURSE
Prepared by: NG HUI QUN &MUKRIMAH NAWIR
USING A COLORMAP
import matplotlib.pyplot as plt
filename='sitka_weather_07-2014.csv'
with open(filename) as f:
reader = csv.reader(f)
header_row = next(reader)