PythonSlide Latest 2018-Converted
Short Description
phy sld cnvr/...
Description
Prepared by: NG NG HUI QUN &MUKRIMAH NAWIR
School of Compu Computer ter and Commu Communic nicati ation on Engineering
Organized by School of Computer Computer and Communication Communication Engineering Engineering
09/12/201 8
PYTHON CRASH COURSE
1
Prepared by: NG NG HUI QUN &MUKRIMAH NAWIR
PYTHON CR CRASH COURSE COURSE 9.00am
Variables ariables and Simple Simple Data Types
10.00am
10.00am
Introduct Introduction ion and Working Working wit with LIST LISTS S
12.00pm
12.00pm
IF Sta Statem tements ents
1.00pm
1.00pm
BREAK TIME
2.00pm
2.00pm
User User Inpu Inputt and While loop loops s
3.00pm
3.00pm
Functions
4.00pm
4.00pm
Dicti Dictiona onarie ries s and Data Data Visualiz Visualizat ation ion
5.15pm
09/12/201 8
PYTHON CRASH COURSE
2
Prepared by: NG NG HUI QUN &MUKRIMAH NAWIR
PYTHON CR CRASH COURSE COURSE
VARIABLES & SIMPLE DATA TYPES 09/12/201 8
PYTHON CRASH COURSE
3
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 8
PYTHON CRASH COURSE
4
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 8
PYTHON CRASH COURSE
5
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 s ing le or double quotes
String with Methods Name = “ mukrimah nawir” print(Name.title())
Output: Mukrimah Nawir
print(Name.upper())
MUKRIMAH NAWIR
print(Name.lower())
mukrimah nawir
Combining and Concatenating Strings first_name=”mukrimah” last_name=”nawir” full_name= first_name + “ “ + last_name print(full_name)
mukrimah nawir
print(“Hello, “ + full_name.title() + “!”) Hello, Mukrimah Nawir! 09/12/201 8
PYTHON CRASH COURSE
6
Prepared by: NG HUI QUN
STRINGS Output: Python Python
String with Tabs print(“Python”)
print(“ \tPython”) String with Newlines print(“Languages: \nPython \nC \nJavaScript”)
String with Apostrophe
Languages: Python C JavaScript
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
09/12/201 8
lstrip() : left strip PYTHON CRASH COURSE
strip() : both side strip 7
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 8
PYTHON CRASH COURSE
8
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 ON C RASe Hn COt URw SE ith few m
9
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 8
PYTHON CRASH COURSE
10
Prepared by: NG NG HUI QUN &MUKRIMAH NAWIR
PYTHO PYTHON N CRASH CRASH COUR COURSE SE
INTRODUCTI TION & WORKINGWITH LISTS 09/12/201 8
PYTHON CRASH COURSE
11
Prepared by: NG NG HUI QUN &MUKRIMAH NAWIR
INT IN TRO RODU DUCT CTIO ION N TO LI LIS STS
A list is a collection of items in a particular particular order [ ] indi indica cate tes s a list list and and indi indivi vidu dual al elem elemen ents ts in the the list list are are sepa separa rate ted d by commas bicycles bicycles = ['trek','c ['trek','cannond annondale', ale', 'redline', 'redline', 'specializ 'specialized'] ed'] print(bicycles) ['trek','cannondale', 'redline', 'specialized']
Accessing Elements in a List
List are ordered collections, access any element in a list by telling Python Python the position/in position/index dex of the the item desired. desired. bicycles = ['trek','cannondale', 'redline', 'specialized'] print(bicycles[0]) trek print(bicycles[0].title()) Trek 09/12/201 8
PYTHON CRASH COURSE
12
Prepared by: NG NG HUI QUN &MUKRIMAH NAWIR
INTRO IN TRODU DUCTI CTION ON TO LIS LISTS TS (CONT.) Index Index Positio Positions ns Start Start at 0, Not 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]) specialized print(bicycles[-2])
redline
Using Individual Individual Valu Values es from a List
Use concatenation to create a message based on a va valu lue e fro from m a lilist st bicycles = ['trek','cannondale', 'redline', 'specialized'] message= “My first bicycle was a” + bicycles[0].title()+”.” print(message)
My first bicycle bicycle was was a Trek rek..
09/12/201 8
PYTHON CRASH COURSE
13
Prepared by: NG HUI QUN &MUKRIMAH NAWIR
CHANGING, ADDING, &REMOVING 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) 09/12/201 8
['peugeot' ,'merc', 'mazda'] ['merc', 'mazda']
PYTHON CRASH COURSE
14
Prepared by: NG HUI QUN &MUKRIMAH NAWIR
CHANGING, ADDING, &REMOVING ELEMENTS (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
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) ['honda','yamaha', 'suzuki','ducati'] motorcycles.remove('ducati') ['honda','yamaha', 'suzuki'] print(motorcycles) 09/12/201 8
PYTHON CRASH COURSE
15
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() cars = ['bmw', 'audi', 'toyota', 'subaru'] print(“Here is the original list:”) print(“\nHere is the sorted list:”) print(sorted(cars))
Here is the original list: ['bmw', 'audi', 'toyota', 'subaru'] Here is the sorted list: ['audi','bmw', subaru', 'toyota', ]
Printing a List in Reverse Order - .reverse() cars = ['bmw', 'audi', 'toyota', 'subaru'] print(cars) cars.reverse
['bmw', 'audi', 'toyota', 'subaru'] ['subaru', 'toyota','audi', 'bmw' ]
print(cars)
Finding the length of a list - len() cars = ['bmw', 'audi', 'toyota', 'subaru'] len(cars) 09/12/201 8
PYTHON CRASH COURSE
output 4 16
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 8
PYTHON CRASH COURSE
17
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() cars = ['bmw', 'audi', 'toyota', 'subaru'] print(“Here is the original list:”) print(“\nHere is the sorted list:”) print(sorted(cars))
Here is the original list: ['bmw', 'audi', 'toyota', 'subaru'] Here is the sorted list: ['audi','bmw', subaru', 'toyota', ]
Printing a List in Reverse Order - .reverse() cars = ['bmw', 'audi', 'toyota', 'subaru'] print(cars) cars.reverse
['bmw', 'audi', 'toyota', 'subaru'] ['subaru', 'toyota','audi', 'bmw' ]
print(cars)
Finding the length of a list - len() cars = ['bmw', 'audi', 'toyota', 'subaru'] len(cars) 09/12/201 8
PYTHON CRASH COURSE
output 4 18
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 8
PYTHON CRASH COURSE
19
Prepared by: NG HUI QUN &MUKRIMAH NAWIR
MAKING NUMERICAL LIST
Using the range() Function For value in range(1,5) print(value)
1 2 3 4 c
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
numbers = list(range(1,6)) print(numbers) even_numbers = list(range(2,11,2)) print(even_numbers) [2, 4, 6, 8, 10]
[1, 2, 3, 4, 5]
Starting number is 2 Adds 2 repeatedly until it reaches or passes the end value
squares = [] for value in range(1,11): [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] square = value**2 09/12/20s18quares.append(squareP)YTHON CRASH
2 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 45 print(max(digits) 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.append(value**2) print (squares) 09/12/201 8
squares = [value**2 in range (1,11)] print (squares)
PYTHON CRASH COURSE
21
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 8
PYTHON CRASH COURSE
22
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 8
PYTHON CRASH COURSE
23
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:
09/12/201 8
The first three players: Charles Martina Michael
PYTHON CRASH COURSE
24
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’]
09/12/201 8
My friend’s favorite foods are: [‘pizza’,`falafel’,`carrot cake’,’ice cream’] PYTHON CRASH COURSE
2 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) print(dimensions[0]); print(dimensions[1]);
200 50
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 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: print(dimension)
200 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: print(dimension) dimensions=(400, 100) print(“\n Modified dimensions:”) for dimension in dimensions: 09/12/201 PYTHON CRASH print(dimension) 8 CO
Original dimensions: 200 50 Modified dimensions: 400 100 URS E
2 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 8
PYTHON CRASH COURSE
28
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 8
PYTHON CRASH COURSE
29
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 8
PYTHON CRASH COURSE
30
Prepared by: NG HUI QUN &MUKRIMAH NAWIR
PYTHON CRASH COURSE
IFSTATEMENTS
09/12/201 8
PYTHON CRASH COURSE
31
Prepared by: NG HUI QUN &MUKRIMAH NAWIR
A SIMPLE EXAMPLE cars = ['audi', 'bmw', 'subaru', 'toyota'] for car in cars: if car == 'bmw': print(car.upper()) else: print(car.title())
Output: Audi BMW Subaru 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 8
PYTHON CRASH COURSE
32
Prepared by: NG HUI QUN &MUKRIMAH NAWIR
CONDITIONAL TESTS (CONT.) Checking for Inequality Output: Hold the anchovies!
requested_topping = 'mushrooms' if requested_topping != 'anchovies': print(“Hold the anchovies!”) Numerical Comparisons >>> age = 19 >>> age < 21
True
09/12/201 8
>>> age = 19 >>> age >> age = 19 >>> age > 21
False
PYTHON CRASH COURSE
>>> age = 19 >>> age >= 21
False
33
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 8
PYTHON CRASH COURSE
34
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: print("Your admission cost is $5.") else: print("Your admission cost is $10.")
Your admission cost is $5
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 8
PYTHON CRASH COURSE
35
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
View more...
Comments