SlideShare a Scribd company logo
Final Review
By: Raj and Kendrick
Structure of final exam
• Multiple-choice Questions (20 mark)
• 2 marks. 10 questions
• True/False(10 mark)
• 1 marks. 10 questions
• Write the missing statement (15
mark)
• 3 marks. 5 questions
• Write programs.(20 mark)
• 10 mark. 2 questions
• Write Outputs.(20 marks)
• 4 marks. 5 questions
• Q&A.(15 marks)
• 15 marks. 1 question.
Closed Book. 120min
L1 Review
How does it work?
• So our question was “ How does a Computer work? ”
• If we talk about latest computers;
• These machines(Hardware) work with Software.
• Who design and develop these Hardware and Software?
• Engineers!!!
• What does a software engineer do?
• Write programs!
What is a Program?
• In computer sicence,
a program is a
specific set of
“ordered operations”
for a computer to
perform.
• What is set of
“ordered operations”
Ordered Operations!
• To understand ordered
operation,
• Let’s talk about “How to
go out of this classroom?”
• What are the possible
ways?
L2 Review
Name:
• What’s your name?
• Name: James
• Code: 007
• Address: MI3
• What are these things?
• Do we need to use such things in programming language too?
• ?????
Variable!
• What is Variable?
• Variables are containers for storing data values.
• So In python we can write code=007
• Now again, What is variable?
• Can I write code=700?
• So now code is 007 or 700?, and why?
• Variable= “vary + able”
• Vary means “can change”
Variables:
• Can I write? Name = 007
• Code=James
• Are they same?
• Can I write a=10
• b=20
• C=a+b
• We will learn more about it in next class.
L3 Review
Try Python Programs:
• Let’s try declaring an Integer variable first.
• a=10
• b=5
• print(a+b)
• We can also do a+b directly, but it’s not same as print(a+b)
• We can also try 10+5 without using variables, python is very user friendly.
• By the way “ Do you have a Question What is Integer?”
• It is Data type, we will learn about it later.
Data Types in Python
• Text Type: str
• Numeric Types: int, float, complex
• Sequence Types: list, tuple, range
• Mapping Type: dict
• Set Types: set, frozenset
• Boolean Type: bool
• Binary Types: bytes, bytearray, memoryview
Integer
• Python could deal with any size of Integer, including negative integer.
• The expressions in the program are exactly the same as those in mathematics,
for example: 1100, -8080, 0, and so on.
• Because computers use binary, it is sometimes convenient to use hexadecimal
to represent integers. Hexadecimal is represented by 0x prefix and 0-9, A-F,
such as 0xff00, 0xa5b4c3d2, etc.
• For large numbers, such as 100000000, it is difficult to count the number of
zeros. Python allows the middle of numbers to be_ Separate, therefore, write
10_ 000_ 000_ 000 and 1000000000 are exactly the same. Hexadecimal
numbers can also be written as 0xa1b2_ c3d4 。
Integer
• Try to type the following code in
your computer:
• a = 2
• b = 3
• a*b
• a**b
• a/b
• print(type(a/b))
• print(type(a))
▪ Try to type the following
code in your computer:
▪ x = 16
▪ y = - 16
▪ z = 0x10
▪ t = 1_6
▪ x + y
▪ x – y
▪ x – z
▪ t - x
Float
• Floating point numbers, that is, decimals, are called floating-point
numbers because when expressed in scientific notation, the decimal
point position of a floating-point number is variable. For example, 1.23x
and 12.3x are completely equal.
• Floating point numbers can be written mathematically, such as 1.23,
3.14, - 9.01, and so on. However, for large or small floating-point
numbers, they must be represented by scientific counting. Replace 10
with e, 1.23x is 1.23e9, or 12.3e8, 0.000012 can be written as 1.2e-5, etc.
• Integer and floating-point numbers are stored in different ways in the
computer.
Float
• Try to type the following code in
your computer:
• a = 2.0
• b = 3.0
• a*b
• a**b
• a/b
• print(type(a/b))
• print(type(a))
▪ Try to type the following
code in your computer:
▪ x = 1.0
▪ y = -2.0
▪ x + y
▪ x – y
▪ z = x + y
▪ (Is there any output for the
expression above? Why?)
L4 Review
Python - Variable Names
• A variable can have a short name (like x and y) or a more descriptive
name (age, yourname, total_amount).
• Rules for Python variables:
• A variable name must start with a letter or the _ underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
• Variable names are case-sensitive (age, Age and AGE are three different
variables)
Expressions
• Python Expressions are sequence of operands(objects) and operators.
• 3+5*8 #here 3,5,8 are operands and +, * are operators
• a,b = 10,20
• c = a + b
• d = a + b * c / a
• a = a + b + c
• f = f + a + b + c # are you getting an error?
• del a # deleting a variable
• a = a + b
Python Comments
• Comments can be used to explain Python code.
• Comments can be used to make the code more readable.
• Comments can be used to prevent execution when testing code.
• #This is a comment
print("Hello, World!")
• print("Hello, World!") #This is a comment
• #print("Hello, World!")
print("Cheers, NUIT!")
Python Numbers
• There are three numeric types in Python:
• int
• float
• complex
• Variables of numeric types are created when
you assign a value to them:
• x = 1 # int
y = 2.8 # float
z = 1j # complex
• To verify the type of any
object in Python, use the
type() function:
• print(type(x))
• print(type(y))
• print(type(z))
Type Conversion
You can convert from one type to another with the int(), float(), and
complex() methods:
• x = 1 # int
y = 2.8 # float
z = 1j # complex
#convert from int to float:
a = float(x)
#convert from float to int:
b = int(y)
#convert from int to
complex:
c = complex(x)
• print(a)
print(b)
print(c)
print(type(a))
print(type(b))
print(type(c))
Bool
• Please run the following code:
• 3 > 2
• 2 > 3
• 1+3>2
• 0.001 >2
• True – True
• False + True
• 0==False
• type(True)
▪ Please run the following
code:
▪ a = 2 > 3
▪ print(a)
▪ b = 3 > 2
▪ print(b)
▪ c = True < False
▪ print(c)
▪ d = True – False
None
• Null value is a special value in Python, represented by None.
• None cannot be understood as 0. Because 0 is meaningful and None is a special
null value.
Please run the following code:
• print(None)
• a = None
• None – None
• None + True
• type(a)
L5 Review
Strings
• We already know what is string and what is use of it; Today we will try
more examples with strings.
• Strings in python are surrounded by either single quotation marks, or
double quotation marks.
• ‘Neusoft' is the same as “Neusoft“
• Assign String to a Variable:
• Assigning a string to a variable is done with the variable name followed
by an equal sign and the string:
• a = “Neusoft"
print(a)
Strings are Arrays
• Get the character at position 1 (remember that the first character has the
position 0):
• What is I just want to print one letter from the given string?
• a = "Hello, World!"
print(a[1])
• The len() function returns the length of a string:
• print(len(a))
• To check if a certain phrase or character is present in a string, we can use
the keyword in.
• txt = "The Coffee in the Library is free!"
print("free" in txt)
▪ Try this one; print("Milk" not in txt)
Python - Slicing Strings
• What if I want to print ello from the above given string?
• You can return a range of characters by using the slice
syntax.
• Specify the start index and the end index, separated by a
colon, to return a part of the string.
• b = "Hello, World!"
print(b[1:5])
• Note: The first character has index 0.
▪ Slice From the Start
▪ b = "Hello, World!"
print(b[:5])
▪ Slice To the End
▪ print(b[2:])
▪ Negative Indexing
▪ Get the characters:
▪ From: "o" in "World!" (position -5)
▪ To, but not included: "d" in "World!" (position -2)
▪ b = "Hello, World!"
print(b[-5:-2])
▪ String[start : end : step]
▪ nums = “0123456789"
print(nums[0:10:1])
▪ print(nums[0:10:2])
▪ String[ start : end : step]
▪ String slicing can accept a third parameter in addition to
two index numbers. The third parameter specifies
the stride, which refers to how many characters to move
forward after the first character is retrieved from the
string.
Python - Escape Characters
• Can we use?:
txt = "We are the Students of
"Neusoft" from China. "
• To fix this problem, use the escape
character ":
r ":
Code Result
' Single Quote
 Backslash
n New Line
r Carriage Return
t Tab
b Backspace
f Form Feed
ooo Octal value
xhh Hex value
L6 Review
▪ Python Arithmetic Operators
▪ Arithmetic operators are used with numeric values to perform
common mathematical operations:
Operator Name Example
+ Addition x + y
- Subtraction x - y
* Multiplication x * y
/ Division x / y
% Modulus x % y
** Exponentiation x ** y
// Floor division x // y
▪ Python Assignment Operators
▪ Assignment operators are used to assign values to variables:
Operator Example Same As
= x = 5 x = 5
+= x += 3 x = x + 3
-= x -= 3 x = x - 3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
%= x %= 3 x = x % 3
▪ Python Assignment Operators
▪ Assignment operators are used to assign values to variables:
▪ We will try some of them.
Operator Example Same As
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x = x & 3
|= x |= 3 x = x | 3
^= x ^= 3 x = x ^ 3
>>= x >>= 3 x = x >> 3
▪ Python Comparison Operators
▪ Comparison operators are used to compare two values:
Operator Name Example
== Equal x == y
!= Not equal x != y
> Greater than x > y
< Less than x < y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y
▪ Python Logical Operators
▪ Logical operators are used to combine conditional statements
Operator Description Example
and Returns True if both
statements are true
x < 5 and x < 10
or Returns True if one of the
statements is true
x < 5 or x < 4
not Reverse the result, returns
False if the result is true
not(x < 5 and x < 10)
▪ Python Identity Operators
▪ Identity operators are used to compare the objects, not if they
are equal, but if they are actually the same object, with the same
memory location:
Operator Description Example
is Returns True if both
variables are the same
object
x is y
is not Returns True if both
variables are not the
same object
x is not y
▪ Python Bitwise Operators
▪ Bitwise operators are used to compare (binary) numbers:
▪ We will not practice Examples of bitwise operators.
Operat
or
Name Description
& AND Sets each bit to 1 if both bits are 1
| OR Sets each bit to 1 if one of two bits is 1
^ XOR Sets each bit to 1 if only one of two bits is 1
~ NOT Inverts all the bits
<< Zero fill
left shift
Shift left by pushing zeros in from the right and let the
leftmost bits fall off
>> Signed
right shift
Shift right by pushing copies of the leftmost bit in from
the left, and let the rightmost bits fall off
L7 Review
Branching programs
• Do you remember the problem of opening a
door?
• The simplest branching statement is a
conditional.
• A test(expression that evaluates to True or
False)
• A block of code to execute if the test is True
• An optional block of code to execute if the test
is False
Code
True
Block
False
Block
Test
Code
Python Conditions and If
statements
• Python supports the usual logical conditions from mathematics:
• Equals: a == b
• Not Equals: a != b
• Less than: a < b
• Less than or equal to: a <= b
• Greater than: a > b
• Greater than or equal to: a >= b
Example:
• An "if statement" is written by using the if keyword.
• Example: If statement:
• a = 33
b = 200
if b > a:
print ("b is greater than a")
Indentation
• Python relies on indentation (whitespace at the beginning of a line) to
define scope in the code. Each indented set of expressions
denotes a block of instructions.
• Other programming languages often use curly-brackets for this purpose.
• Example: If statement, without indentation (will raise an error):
• a = 33
b = 200
if b > a:
print ("b is greater than a") # you will get an error
Indent
expected
!!
Python User Input
• Python allows for user input.
• That means we are able to ask the user for input.
• name = input("Enter your name:")
print(“Your name is: " + name)
• Can you write a program to calculate a+b using input?
• a=input(“Enter value of a:”)
• b=input(“Enter value of b:”)
• print(“The sum of a+b is:”, a+b) #Does this work?
If - else
• Question time: Given the following code, which part of it
is the True block? Which part of it is the False block?
Code
True
Block
False
Block
Test
Code
a = int(input(“Enter first number:”))
b = int(input(“Enter second number:”))
if a>b:
print("The bigger number: ”, a )
else:
print("The bigger number: ”, b )
print('Done with conditional')
Example of Branching programs (elif)
• The elif keyword is python way of saying "if the
previous conditions were not true, then try this
condition".
a = int(input(“Enter first
number:”))
b = int(input(“Enter second
number:”))
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("b is smaller than a")
The pass Statement
• if statements cannot be empty, but if you for some
reason have an if statement with no content, put in
the pass statement to avoid getting an error.
• a = 33
b = 200
if b > a:
pass
L8 Review
Iteration
• Concept of iteration let us extend
simple branching algorithms to
be able to write programs of
arbitrary complexity
• Strat with a test
• If evaluates to True , then
execute loop body once, and
go back to reevaluate the test.
• Repeat until the test is False,
after which code following
iteration statement is
executed.
Code
Loop body
Test
Code
True
False
An example of while loop
x = int(input("Please input an integer:
"))
ans = 0
iterLeft = x
while iterLeft != 0:
ans = ans + x
iterLeft = iterLeft - 1
print(str(x) + '*' + str(x) + '=' +
str(ans))
This program square the value of x by
addition.
Python For Loops
• A for loop is used for iterating over a sequence.
•Looping Through a String
• Even strings are iterable objects, they contain a
sequence of characters
• Example:
• for x in "Neusoft":
print(x)
The range() Function
• To loop through a set of code a specified number of
times, we can use the range() function,
• The range() function returns a sequence of numbers,
starting from 0 by default, and increments by 1 (by
default), and ends at a specified number.
• Example:
• for x in range(6):
print(x)
• Note that range(6) is not the values of 0 to 6, but the values 0 to 5.
The break Statement
• With the break statement we can
stop the loop before it has looped
through all the items:
• Exit the loop when x is "banana":
• fruits =
["apple", "banana", "cherry"
]
for x in fruits:
print(x)
if x == "banana":
break
• Exit the loop when x is "banana",
but this time the break comes
before the print:
• fruits =
["apple", "banana", "cherry
"]
for x in fruits:
if x == "banana":
break
print(x)
The continue Statement
• With the continue statement we can stop the current iteration of the
loop, and continue with the next:
• Example:
• Do not print banana:
• fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
Else in For Loop
• The else keyword in a for loop specifies a block of code to be
executed when the loop is finished:
• Print all numbers from 0 to 5, and print a message
when the loop has ended:
• for x in range(6):
print(x)
else:
print(“For Loop finished!")
• Note: The else block will NOT be executed if the loop is
stopped by a break statement.
L9 Review
Python Lists
• Ordered
• When we say that lists are ordered, it means that the items have a defined order, and that
order will not change.
• If you add new items to a list, the new items will be placed at the end of the list.
• Changeable
• The list is changeable, meaning that we can change, add, and remove items in a list after
it has been created.
• Allow Duplicates
• Since lists are indexed, lists can have items with the same value:
Allow Duplicates
• Example:
• Lists allow duplicate values:
• list1 = ["apple", "banana", "cherry", "apple", "cherry"]
print(list1)
• List Length
• To determine how many items a list has, use the len() function:
• list1 = ["apple", "banana", "cherry"]
print(len(list1))
List Items - Data Types
• List items can be of any data type:
• Example:
• list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]
• A list can contain different data types:
• list1 = ["abc", 34, True, 40, "male"]
• Check type:
• print(type(list1))
L11 Review
Tuple Items
• Tuple items are ordered, unchangeable, and allow duplicate
values.
• Tuple items are indexed, the first item has index [0], the
second item has index [1] etc.
• Ordered: When we say that tuples are ordered, it means
that the items have a defined order, and that order will not
change.
• Unchangeable: Tuples are unchangeable, meaning that we
cannot change, add or remove items after the tuple has been
created.
• Allow Duplicates: Since tuples are indexed, they can have
items with the same value:
Create Tuple With One Item
• To create a tuple with only one item, you have to
add a comma after the item, otherwise Python will
not recognize it as a tuple.
• tuple1 = ("apple",)
print(type(tuple1))
#NOT a tuple
tuple2 = ("apple")
print(type(tuple2))
Tuple Items - Data Types
• Tuple items can be of any data type:
• tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)
• A tuple can contain different data types:
• tuple1 = ("abc", 34, True, 40, "male")
• The tuple() Constructor
• tuple3 = tuple(("apple", "banana", "cherry")) #
note the double round-brackets
print(tuple3)
L13 Review
Python Functions
• A function is a block of code which only runs when it is called.
• You can pass data, known as parameters, into a function.
• A function can return data as a result.
• In Python a function is defined using the def keyword:
• def my_function():
print("Hello from a function")
Why use Python functions?
• Functions provide a way to compartmentalize your code into small tasks
that can be called from multiple places within a program
• This is especially useful if the code in question will be used several times in
different parts of your program.
• You can think of functions as mini-programs within your bigger program
that implement specific tasks.
• If you have a block of code that gets called more than once, put it in a
function.
• Functions may take optional inputs to work with and may optionally return
a value or values.
User-defined function
• As the name suggests, these are functions that are written by the user, to
aid them in achieving a specific goal.
• The main use of functions is to help us organize our programs into
logical fragments that work together to solve a specific part of our
problem.
• General structure of Python function (Syntax)
• The structure of a function is very simple but very important.
def {FunctionName}[(parameters)]: # Function
Header Indented code..... # Code begins here
return
Syntax:
• Use the def keyword, followed by the function name.
• The function name must follow the same naming rules for variables (Single
word, No spaces, must start with either a letter or an underscore, etc).
• Add parameters (if any) to the function within the parentheses. End the
function definition with a full colon.
• Write the logic of the function. All code for the function must be indented.
• Finally, use the return keyword to return the output of the function. This is
optional, and if it is not included, the function automatically returns None.
def {FunctionName}[(parameters)]: # Function
Header Indented code..... # Code begins here
return
L15 Review
Python Classes/Objects
• Everything in Python is an object and has a type
• Objects are a data abstraction that capture:
• Internal representation through data attributes
• Interface for interacting with object through methods(procedures), defines
behaviors but hides implementation
• Can create new instances of objects
• Can destroy objects
• Explicitly using del or just forget about them
• Python system will reclaim destroyed or inaccessible objects – called ‘garbage
collection’
Create a Class
• To create a class, use the keyword class:
• We can say a class is a user defined data type.
• And class can have
• Attributes = variables
• Behavior = Methods(Functions)
class Coordinate(object):
"""
define attributes here.
"""
Create a Class
• Similar to def, it needs indentation to indicate which statements are part of the
class definition
• The word object means that Coordinate is a Python object and inherits all its
attributes (Recommend to inherit object)
• Coordinate is a subclass of object
• Object is a superclass of Coordinate.
class Coordinate(object):
"""
define attributes here.
"""
What are attributes?
• The data and procedures that “belong” to the class
• Data attributes
• Think of the data as other objects that make up the class
• For example, a coordinate is made up of two numbers
• Procedure attributes(methods or functions)
• Methods that only work with this class
• For example, define a distance between two coordinate instances.
class Coordinate(object):
"""
define attributes here.
"""
Creating a class
• First have to define how to create an instance of object
• Use a special method called __init__() to initialize some data attributes
• In python when something starts with “__” it means it’s special
• But the __init__() is being called by default(automatically) in python.
• Self is the parameter which refer to the instance of the class.
class Coordinate(object):
def __init__(self, x, y):
self.x = x
self.y = y
Creating a class
• About the x, y(data attribute)
• When we invokes the creation of an instance, this will bind the variables x and
y within that instance to the supplied values.
• For every instance of Coordinate, it will have two data attribute, x and y.
class Coordinate(object):
def __init__(self, x, y):
self.x = x
self.y = y
L16 Review
Main Concepts of Object-Oriented
Programming (OOPs)
•Class
•Objects
•Inheritance
•Polymorphism
•Encapsulation
Structured Programming & 3 characteristic of
OOP
•Structured Programming:
•Structured programming adopts the top-down and
gradual refinement design method. Each module is
connected through the control structure of
"sequence, iteration, branching structure and
loop", and there is only one entrance and one exit
Structured Programming & 3 characteristic of
OOP
• 3 characteristic of OOP :
• Encapsulation(1 mark): that is to encapsulate objective things into abstract
classes, and classes can only allow trusted classes or objects to operate their
own data and methods, and hide information from untrusted ones.(3 marks)
• Inheritance(1 mark): refers to the ability to use all the functions of existing
classes and extend them without rewriting the original classes. (3 marks)
• Polymorphism(1 mark) is a technology that allows you to set the parent object
equal to one or more of its child objects. After assignment, the parent object
can operate in different ways according to the characteristics of the child
object currently assigned to it. (3 marks)
Thank you!

More Related Content

Similar to Review old Pygame made using python programming.pptx (20)

Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developers
Jim Roepcke
 
Python for beginner, learn python from scratch.pptx
Python for beginner,  learn python from scratch.pptxPython for beginner,  learn python from scratch.pptx
Python for beginner, learn python from scratch.pptx
olieee2023
 
An Introduction : Python
An Introduction : PythonAn Introduction : Python
An Introduction : Python
Raghu Kumar
 
parts_of_python_programming_language.pptx
parts_of_python_programming_language.pptxparts_of_python_programming_language.pptx
parts_of_python_programming_language.pptx
Koteswari Kasireddy
 
INTRODUCTION TO PYTHON.pptx
INTRODUCTION TO PYTHON.pptxINTRODUCTION TO PYTHON.pptx
INTRODUCTION TO PYTHON.pptx
Nimrahafzal1
 
Learn C LANGUAGE at ASIT
Learn C LANGUAGE at ASITLearn C LANGUAGE at ASIT
Learn C LANGUAGE at ASIT
ASIT
 
Chapter 2: Elementary Programming
Chapter 2: Elementary ProgrammingChapter 2: Elementary Programming
Chapter 2: Elementary Programming
Eric Chou
 
Brixton Library Technology Initiative Week0 Recap
Brixton Library Technology Initiative Week0 RecapBrixton Library Technology Initiative Week0 Recap
Brixton Library Technology Initiative Week0 Recap
Basil Bibi
 
c-programming
c-programmingc-programming
c-programming
Zulhazmi Harith
 
Python Basics by Akanksha Bali
Python Basics by Akanksha BaliPython Basics by Akanksha Bali
Python Basics by Akanksha Bali
Akanksha Bali
 
modul-python-all.pptx
modul-python-all.pptxmodul-python-all.pptx
modul-python-all.pptx
Yusuf Ayuba
 
Review of C programming language.pptx...
Review of C programming language.pptx...Review of C programming language.pptx...
Review of C programming language.pptx...
SthitaprajnaLenka1
 
Functions, List and String methods
Functions, List and String methodsFunctions, List and String methods
Functions, List and String methods
PranavSB
 
Q-Step_WS_02102019_Practical_introduction_to_Python.pdf
Q-Step_WS_02102019_Practical_introduction_to_Python.pdfQ-Step_WS_02102019_Practical_introduction_to_Python.pdf
Q-Step_WS_02102019_Practical_introduction_to_Python.pdf
Michpice
 
Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02
Fariz Darari
 
Lec2_cont.pptx galgotias University questions
Lec2_cont.pptx galgotias University questionsLec2_cont.pptx galgotias University questions
Lec2_cont.pptx galgotias University questions
YashJain47002
 
introduction to python
 introduction to python introduction to python
introduction to python
Jincy Nelson
 
ACM init() Spring 2015 Day 1
ACM init() Spring 2015 Day 1ACM init() Spring 2015 Day 1
ACM init() Spring 2015 Day 1
UCLA Association of Computing Machinery
 
Python- Basic. pptx with lists, tuples dictionaries and data types
Python- Basic. pptx with lists, tuples dictionaries and data typesPython- Basic. pptx with lists, tuples dictionaries and data types
Python- Basic. pptx with lists, tuples dictionaries and data types
harinithiyagarajan4
 
Python- Basic.pptx with data types, lists, and tuples with dictionary
Python- Basic.pptx with data types, lists, and tuples with dictionaryPython- Basic.pptx with data types, lists, and tuples with dictionary
Python- Basic.pptx with data types, lists, and tuples with dictionary
harinithiyagarajan4
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developers
Jim Roepcke
 
Python for beginner, learn python from scratch.pptx
Python for beginner,  learn python from scratch.pptxPython for beginner,  learn python from scratch.pptx
Python for beginner, learn python from scratch.pptx
olieee2023
 
An Introduction : Python
An Introduction : PythonAn Introduction : Python
An Introduction : Python
Raghu Kumar
 
parts_of_python_programming_language.pptx
parts_of_python_programming_language.pptxparts_of_python_programming_language.pptx
parts_of_python_programming_language.pptx
Koteswari Kasireddy
 
INTRODUCTION TO PYTHON.pptx
INTRODUCTION TO PYTHON.pptxINTRODUCTION TO PYTHON.pptx
INTRODUCTION TO PYTHON.pptx
Nimrahafzal1
 
Learn C LANGUAGE at ASIT
Learn C LANGUAGE at ASITLearn C LANGUAGE at ASIT
Learn C LANGUAGE at ASIT
ASIT
 
Chapter 2: Elementary Programming
Chapter 2: Elementary ProgrammingChapter 2: Elementary Programming
Chapter 2: Elementary Programming
Eric Chou
 
Brixton Library Technology Initiative Week0 Recap
Brixton Library Technology Initiative Week0 RecapBrixton Library Technology Initiative Week0 Recap
Brixton Library Technology Initiative Week0 Recap
Basil Bibi
 
Python Basics by Akanksha Bali
Python Basics by Akanksha BaliPython Basics by Akanksha Bali
Python Basics by Akanksha Bali
Akanksha Bali
 
modul-python-all.pptx
modul-python-all.pptxmodul-python-all.pptx
modul-python-all.pptx
Yusuf Ayuba
 
Review of C programming language.pptx...
Review of C programming language.pptx...Review of C programming language.pptx...
Review of C programming language.pptx...
SthitaprajnaLenka1
 
Functions, List and String methods
Functions, List and String methodsFunctions, List and String methods
Functions, List and String methods
PranavSB
 
Q-Step_WS_02102019_Practical_introduction_to_Python.pdf
Q-Step_WS_02102019_Practical_introduction_to_Python.pdfQ-Step_WS_02102019_Practical_introduction_to_Python.pdf
Q-Step_WS_02102019_Practical_introduction_to_Python.pdf
Michpice
 
Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02
Fariz Darari
 
Lec2_cont.pptx galgotias University questions
Lec2_cont.pptx galgotias University questionsLec2_cont.pptx galgotias University questions
Lec2_cont.pptx galgotias University questions
YashJain47002
 
introduction to python
 introduction to python introduction to python
introduction to python
Jincy Nelson
 
Python- Basic. pptx with lists, tuples dictionaries and data types
Python- Basic. pptx with lists, tuples dictionaries and data typesPython- Basic. pptx with lists, tuples dictionaries and data types
Python- Basic. pptx with lists, tuples dictionaries and data types
harinithiyagarajan4
 
Python- Basic.pptx with data types, lists, and tuples with dictionary
Python- Basic.pptx with data types, lists, and tuples with dictionaryPython- Basic.pptx with data types, lists, and tuples with dictionary
Python- Basic.pptx with data types, lists, and tuples with dictionary
harinithiyagarajan4
 

Recently uploaded (20)

How to create and manage blogs in odoo 18
How to create and manage blogs in odoo 18How to create and manage blogs in odoo 18
How to create and manage blogs in odoo 18
Celine George
 
Unit 4 Reverse Engineering Tools Functionalities & Use-Cases.pdf
Unit 4  Reverse Engineering Tools  Functionalities & Use-Cases.pdfUnit 4  Reverse Engineering Tools  Functionalities & Use-Cases.pdf
Unit 4 Reverse Engineering Tools Functionalities & Use-Cases.pdf
ChatanBawankar
 
EVALUATION AND MANAGEMENT OF OPEN FRACTURE
EVALUATION AND MANAGEMENT OF OPEN FRACTUREEVALUATION AND MANAGEMENT OF OPEN FRACTURE
EVALUATION AND MANAGEMENT OF OPEN FRACTURE
BipulBorthakur
 
How to Configure Subcontracting in Odoo 18 Manufacturing
How to Configure Subcontracting in Odoo 18 ManufacturingHow to Configure Subcontracting in Odoo 18 Manufacturing
How to Configure Subcontracting in Odoo 18 Manufacturing
Celine George
 
the dynastic history of the Gahadwals of Early Medieval Period
the dynastic history of the Gahadwals of Early Medieval Periodthe dynastic history of the Gahadwals of Early Medieval Period
the dynastic history of the Gahadwals of Early Medieval Period
PrachiSontakke5
 
Quiz-E-Mataram (Under 20 Quiz Set) .pptx
Quiz-E-Mataram (Under 20 Quiz Set) .pptxQuiz-E-Mataram (Under 20 Quiz Set) .pptx
Quiz-E-Mataram (Under 20 Quiz Set) .pptx
SouptikUkil
 
How to Use Owl Slots in Odoo 17 - Odoo Slides
How to Use Owl Slots in Odoo 17 - Odoo SlidesHow to Use Owl Slots in Odoo 17 - Odoo Slides
How to Use Owl Slots in Odoo 17 - Odoo Slides
Celine George
 
Paper 110A | Shadows and Light: Exploring Expressionism in ‘The Cabinet of Dr...
Paper 110A | Shadows and Light: Exploring Expressionism in ‘The Cabinet of Dr...Paper 110A | Shadows and Light: Exploring Expressionism in ‘The Cabinet of Dr...
Paper 110A | Shadows and Light: Exploring Expressionism in ‘The Cabinet of Dr...
Rajdeep Bavaliya
 
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
siemaillard
 
What are the Features & Functions of Odoo 18 SMS Marketing
What are the Features & Functions of Odoo 18 SMS MarketingWhat are the Features & Functions of Odoo 18 SMS Marketing
What are the Features & Functions of Odoo 18 SMS Marketing
Celine George
 
QUIZ-O-FORCE 3.0 FINAL SET BY SOURAV .pptx
QUIZ-O-FORCE 3.0 FINAL SET BY SOURAV .pptxQUIZ-O-FORCE 3.0 FINAL SET BY SOURAV .pptx
QUIZ-O-FORCE 3.0 FINAL SET BY SOURAV .pptx
Sourav Kr Podder
 
How to Add a Custom Menu, List view and FIlters in the Customer Portal Odoo 18
How to Add a Custom Menu, List view and FIlters in the Customer Portal Odoo 18How to Add a Custom Menu, List view and FIlters in the Customer Portal Odoo 18
How to Add a Custom Menu, List view and FIlters in the Customer Portal Odoo 18
Celine George
 
New syllabus entomology (Lession plan 121).pdf
New syllabus entomology (Lession plan 121).pdfNew syllabus entomology (Lession plan 121).pdf
New syllabus entomology (Lession plan 121).pdf
Arshad Shaikh
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-25-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 5-25-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 5-25-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-25-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
The Splitting of the Moon (Shaqq al-Qamar).pdf
The Splitting of the Moon (Shaqq al-Qamar).pdfThe Splitting of the Moon (Shaqq al-Qamar).pdf
The Splitting of the Moon (Shaqq al-Qamar).pdf
Mirza Gazanfar Ali Baig
 
Patent Law in Bangladesh Addressing Challenges in Pharmaceutical Innovation a...
Patent Law in Bangladesh Addressing Challenges in Pharmaceutical Innovation a...Patent Law in Bangladesh Addressing Challenges in Pharmaceutical Innovation a...
Patent Law in Bangladesh Addressing Challenges in Pharmaceutical Innovation a...
Ibrahim Tareq
 
Flower Identification Class-10 by Kushal Lamichhane.pdf
Flower Identification Class-10 by Kushal Lamichhane.pdfFlower Identification Class-10 by Kushal Lamichhane.pdf
Flower Identification Class-10 by Kushal Lamichhane.pdf
kushallamichhame
 
Unit 1 Tools Beneficial for Monitoring the Debugging Process.pdf
Unit 1 Tools Beneficial for Monitoring the Debugging Process.pdfUnit 1 Tools Beneficial for Monitoring the Debugging Process.pdf
Unit 1 Tools Beneficial for Monitoring the Debugging Process.pdf
ChatanBawankar
 
New-Beginnings-Cities-and-States.pdf/7th class social/4th chapterFor online c...
New-Beginnings-Cities-and-States.pdf/7th class social/4th chapterFor online c...New-Beginnings-Cities-and-States.pdf/7th class social/4th chapterFor online c...
New-Beginnings-Cities-and-States.pdf/7th class social/4th chapterFor online c...
Sandeep Swamy
 
Education Funding Equity in North Carolina: Looking Beyond Income
Education Funding Equity in North Carolina: Looking Beyond IncomeEducation Funding Equity in North Carolina: Looking Beyond Income
Education Funding Equity in North Carolina: Looking Beyond Income
EducationNC
 
How to create and manage blogs in odoo 18
How to create and manage blogs in odoo 18How to create and manage blogs in odoo 18
How to create and manage blogs in odoo 18
Celine George
 
Unit 4 Reverse Engineering Tools Functionalities & Use-Cases.pdf
Unit 4  Reverse Engineering Tools  Functionalities & Use-Cases.pdfUnit 4  Reverse Engineering Tools  Functionalities & Use-Cases.pdf
Unit 4 Reverse Engineering Tools Functionalities & Use-Cases.pdf
ChatanBawankar
 
EVALUATION AND MANAGEMENT OF OPEN FRACTURE
EVALUATION AND MANAGEMENT OF OPEN FRACTUREEVALUATION AND MANAGEMENT OF OPEN FRACTURE
EVALUATION AND MANAGEMENT OF OPEN FRACTURE
BipulBorthakur
 
How to Configure Subcontracting in Odoo 18 Manufacturing
How to Configure Subcontracting in Odoo 18 ManufacturingHow to Configure Subcontracting in Odoo 18 Manufacturing
How to Configure Subcontracting in Odoo 18 Manufacturing
Celine George
 
the dynastic history of the Gahadwals of Early Medieval Period
the dynastic history of the Gahadwals of Early Medieval Periodthe dynastic history of the Gahadwals of Early Medieval Period
the dynastic history of the Gahadwals of Early Medieval Period
PrachiSontakke5
 
Quiz-E-Mataram (Under 20 Quiz Set) .pptx
Quiz-E-Mataram (Under 20 Quiz Set) .pptxQuiz-E-Mataram (Under 20 Quiz Set) .pptx
Quiz-E-Mataram (Under 20 Quiz Set) .pptx
SouptikUkil
 
How to Use Owl Slots in Odoo 17 - Odoo Slides
How to Use Owl Slots in Odoo 17 - Odoo SlidesHow to Use Owl Slots in Odoo 17 - Odoo Slides
How to Use Owl Slots in Odoo 17 - Odoo Slides
Celine George
 
Paper 110A | Shadows and Light: Exploring Expressionism in ‘The Cabinet of Dr...
Paper 110A | Shadows and Light: Exploring Expressionism in ‘The Cabinet of Dr...Paper 110A | Shadows and Light: Exploring Expressionism in ‘The Cabinet of Dr...
Paper 110A | Shadows and Light: Exploring Expressionism in ‘The Cabinet of Dr...
Rajdeep Bavaliya
 
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
siemaillard
 
What are the Features & Functions of Odoo 18 SMS Marketing
What are the Features & Functions of Odoo 18 SMS MarketingWhat are the Features & Functions of Odoo 18 SMS Marketing
What are the Features & Functions of Odoo 18 SMS Marketing
Celine George
 
QUIZ-O-FORCE 3.0 FINAL SET BY SOURAV .pptx
QUIZ-O-FORCE 3.0 FINAL SET BY SOURAV .pptxQUIZ-O-FORCE 3.0 FINAL SET BY SOURAV .pptx
QUIZ-O-FORCE 3.0 FINAL SET BY SOURAV .pptx
Sourav Kr Podder
 
How to Add a Custom Menu, List view and FIlters in the Customer Portal Odoo 18
How to Add a Custom Menu, List view and FIlters in the Customer Portal Odoo 18How to Add a Custom Menu, List view and FIlters in the Customer Portal Odoo 18
How to Add a Custom Menu, List view and FIlters in the Customer Portal Odoo 18
Celine George
 
New syllabus entomology (Lession plan 121).pdf
New syllabus entomology (Lession plan 121).pdfNew syllabus entomology (Lession plan 121).pdf
New syllabus entomology (Lession plan 121).pdf
Arshad Shaikh
 
The Splitting of the Moon (Shaqq al-Qamar).pdf
The Splitting of the Moon (Shaqq al-Qamar).pdfThe Splitting of the Moon (Shaqq al-Qamar).pdf
The Splitting of the Moon (Shaqq al-Qamar).pdf
Mirza Gazanfar Ali Baig
 
Patent Law in Bangladesh Addressing Challenges in Pharmaceutical Innovation a...
Patent Law in Bangladesh Addressing Challenges in Pharmaceutical Innovation a...Patent Law in Bangladesh Addressing Challenges in Pharmaceutical Innovation a...
Patent Law in Bangladesh Addressing Challenges in Pharmaceutical Innovation a...
Ibrahim Tareq
 
Flower Identification Class-10 by Kushal Lamichhane.pdf
Flower Identification Class-10 by Kushal Lamichhane.pdfFlower Identification Class-10 by Kushal Lamichhane.pdf
Flower Identification Class-10 by Kushal Lamichhane.pdf
kushallamichhame
 
Unit 1 Tools Beneficial for Monitoring the Debugging Process.pdf
Unit 1 Tools Beneficial for Monitoring the Debugging Process.pdfUnit 1 Tools Beneficial for Monitoring the Debugging Process.pdf
Unit 1 Tools Beneficial for Monitoring the Debugging Process.pdf
ChatanBawankar
 
New-Beginnings-Cities-and-States.pdf/7th class social/4th chapterFor online c...
New-Beginnings-Cities-and-States.pdf/7th class social/4th chapterFor online c...New-Beginnings-Cities-and-States.pdf/7th class social/4th chapterFor online c...
New-Beginnings-Cities-and-States.pdf/7th class social/4th chapterFor online c...
Sandeep Swamy
 
Education Funding Equity in North Carolina: Looking Beyond Income
Education Funding Equity in North Carolina: Looking Beyond IncomeEducation Funding Equity in North Carolina: Looking Beyond Income
Education Funding Equity in North Carolina: Looking Beyond Income
EducationNC
 

Review old Pygame made using python programming.pptx

  • 1. Final Review By: Raj and Kendrick
  • 2. Structure of final exam • Multiple-choice Questions (20 mark) • 2 marks. 10 questions • True/False(10 mark) • 1 marks. 10 questions • Write the missing statement (15 mark) • 3 marks. 5 questions • Write programs.(20 mark) • 10 mark. 2 questions • Write Outputs.(20 marks) • 4 marks. 5 questions • Q&A.(15 marks) • 15 marks. 1 question. Closed Book. 120min
  • 4. How does it work? • So our question was “ How does a Computer work? ” • If we talk about latest computers; • These machines(Hardware) work with Software. • Who design and develop these Hardware and Software? • Engineers!!! • What does a software engineer do? • Write programs!
  • 5. What is a Program? • In computer sicence, a program is a specific set of “ordered operations” for a computer to perform. • What is set of “ordered operations”
  • 6. Ordered Operations! • To understand ordered operation, • Let’s talk about “How to go out of this classroom?” • What are the possible ways?
  • 8. Name: • What’s your name? • Name: James • Code: 007 • Address: MI3 • What are these things? • Do we need to use such things in programming language too? • ?????
  • 9. Variable! • What is Variable? • Variables are containers for storing data values. • So In python we can write code=007 • Now again, What is variable? • Can I write code=700? • So now code is 007 or 700?, and why? • Variable= “vary + able” • Vary means “can change”
  • 10. Variables: • Can I write? Name = 007 • Code=James • Are they same? • Can I write a=10 • b=20 • C=a+b • We will learn more about it in next class.
  • 12. Try Python Programs: • Let’s try declaring an Integer variable first. • a=10 • b=5 • print(a+b) • We can also do a+b directly, but it’s not same as print(a+b) • We can also try 10+5 without using variables, python is very user friendly. • By the way “ Do you have a Question What is Integer?” • It is Data type, we will learn about it later.
  • 13. Data Types in Python • Text Type: str • Numeric Types: int, float, complex • Sequence Types: list, tuple, range • Mapping Type: dict • Set Types: set, frozenset • Boolean Type: bool • Binary Types: bytes, bytearray, memoryview
  • 14. Integer • Python could deal with any size of Integer, including negative integer. • The expressions in the program are exactly the same as those in mathematics, for example: 1100, -8080, 0, and so on. • Because computers use binary, it is sometimes convenient to use hexadecimal to represent integers. Hexadecimal is represented by 0x prefix and 0-9, A-F, such as 0xff00, 0xa5b4c3d2, etc. • For large numbers, such as 100000000, it is difficult to count the number of zeros. Python allows the middle of numbers to be_ Separate, therefore, write 10_ 000_ 000_ 000 and 1000000000 are exactly the same. Hexadecimal numbers can also be written as 0xa1b2_ c3d4 。
  • 15. Integer • Try to type the following code in your computer: • a = 2 • b = 3 • a*b • a**b • a/b • print(type(a/b)) • print(type(a)) ▪ Try to type the following code in your computer: ▪ x = 16 ▪ y = - 16 ▪ z = 0x10 ▪ t = 1_6 ▪ x + y ▪ x – y ▪ x – z ▪ t - x
  • 16. Float • Floating point numbers, that is, decimals, are called floating-point numbers because when expressed in scientific notation, the decimal point position of a floating-point number is variable. For example, 1.23x and 12.3x are completely equal. • Floating point numbers can be written mathematically, such as 1.23, 3.14, - 9.01, and so on. However, for large or small floating-point numbers, they must be represented by scientific counting. Replace 10 with e, 1.23x is 1.23e9, or 12.3e8, 0.000012 can be written as 1.2e-5, etc. • Integer and floating-point numbers are stored in different ways in the computer.
  • 17. Float • Try to type the following code in your computer: • a = 2.0 • b = 3.0 • a*b • a**b • a/b • print(type(a/b)) • print(type(a)) ▪ Try to type the following code in your computer: ▪ x = 1.0 ▪ y = -2.0 ▪ x + y ▪ x – y ▪ z = x + y ▪ (Is there any output for the expression above? Why?)
  • 19. Python - Variable Names • A variable can have a short name (like x and y) or a more descriptive name (age, yourname, total_amount). • Rules for Python variables: • A variable name must start with a letter or the _ underscore character • A variable name cannot start with a number • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ) • Variable names are case-sensitive (age, Age and AGE are three different variables)
  • 20. Expressions • Python Expressions are sequence of operands(objects) and operators. • 3+5*8 #here 3,5,8 are operands and +, * are operators • a,b = 10,20 • c = a + b • d = a + b * c / a • a = a + b + c • f = f + a + b + c # are you getting an error? • del a # deleting a variable • a = a + b
  • 21. Python Comments • Comments can be used to explain Python code. • Comments can be used to make the code more readable. • Comments can be used to prevent execution when testing code. • #This is a comment print("Hello, World!") • print("Hello, World!") #This is a comment • #print("Hello, World!") print("Cheers, NUIT!")
  • 22. Python Numbers • There are three numeric types in Python: • int • float • complex • Variables of numeric types are created when you assign a value to them: • x = 1 # int y = 2.8 # float z = 1j # complex • To verify the type of any object in Python, use the type() function: • print(type(x)) • print(type(y)) • print(type(z))
  • 23. Type Conversion You can convert from one type to another with the int(), float(), and complex() methods: • x = 1 # int y = 2.8 # float z = 1j # complex #convert from int to float: a = float(x) #convert from float to int: b = int(y) #convert from int to complex: c = complex(x) • print(a) print(b) print(c) print(type(a)) print(type(b)) print(type(c))
  • 24. Bool • Please run the following code: • 3 > 2 • 2 > 3 • 1+3>2 • 0.001 >2 • True – True • False + True • 0==False • type(True) ▪ Please run the following code: ▪ a = 2 > 3 ▪ print(a) ▪ b = 3 > 2 ▪ print(b) ▪ c = True < False ▪ print(c) ▪ d = True – False
  • 25. None • Null value is a special value in Python, represented by None. • None cannot be understood as 0. Because 0 is meaningful and None is a special null value. Please run the following code: • print(None) • a = None • None – None • None + True • type(a)
  • 27. Strings • We already know what is string and what is use of it; Today we will try more examples with strings. • Strings in python are surrounded by either single quotation marks, or double quotation marks. • ‘Neusoft' is the same as “Neusoft“ • Assign String to a Variable: • Assigning a string to a variable is done with the variable name followed by an equal sign and the string: • a = “Neusoft" print(a)
  • 28. Strings are Arrays • Get the character at position 1 (remember that the first character has the position 0): • What is I just want to print one letter from the given string? • a = "Hello, World!" print(a[1]) • The len() function returns the length of a string: • print(len(a)) • To check if a certain phrase or character is present in a string, we can use the keyword in. • txt = "The Coffee in the Library is free!" print("free" in txt) ▪ Try this one; print("Milk" not in txt)
  • 29. Python - Slicing Strings • What if I want to print ello from the above given string? • You can return a range of characters by using the slice syntax. • Specify the start index and the end index, separated by a colon, to return a part of the string. • b = "Hello, World!" print(b[1:5]) • Note: The first character has index 0.
  • 30. ▪ Slice From the Start ▪ b = "Hello, World!" print(b[:5]) ▪ Slice To the End ▪ print(b[2:]) ▪ Negative Indexing ▪ Get the characters: ▪ From: "o" in "World!" (position -5) ▪ To, but not included: "d" in "World!" (position -2) ▪ b = "Hello, World!" print(b[-5:-2])
  • 31. ▪ String[start : end : step] ▪ nums = “0123456789" print(nums[0:10:1]) ▪ print(nums[0:10:2]) ▪ String[ start : end : step] ▪ String slicing can accept a third parameter in addition to two index numbers. The third parameter specifies the stride, which refers to how many characters to move forward after the first character is retrieved from the string.
  • 32. Python - Escape Characters • Can we use?: txt = "We are the Students of "Neusoft" from China. " • To fix this problem, use the escape character ": r ": Code Result ' Single Quote Backslash n New Line r Carriage Return t Tab b Backspace f Form Feed ooo Octal value xhh Hex value
  • 34. ▪ Python Arithmetic Operators ▪ Arithmetic operators are used with numeric values to perform common mathematical operations: Operator Name Example + Addition x + y - Subtraction x - y * Multiplication x * y / Division x / y % Modulus x % y ** Exponentiation x ** y // Floor division x // y
  • 35. ▪ Python Assignment Operators ▪ Assignment operators are used to assign values to variables: Operator Example Same As = x = 5 x = 5 += x += 3 x = x + 3 -= x -= 3 x = x - 3 *= x *= 3 x = x * 3 /= x /= 3 x = x / 3 %= x %= 3 x = x % 3
  • 36. ▪ Python Assignment Operators ▪ Assignment operators are used to assign values to variables: ▪ We will try some of them. Operator Example Same As //= x //= 3 x = x // 3 **= x **= 3 x = x ** 3 &= x &= 3 x = x & 3 |= x |= 3 x = x | 3 ^= x ^= 3 x = x ^ 3 >>= x >>= 3 x = x >> 3
  • 37. ▪ Python Comparison Operators ▪ Comparison operators are used to compare two values: Operator Name Example == Equal x == y != Not equal x != y > Greater than x > y < Less than x < y >= Greater than or equal to x >= y <= Less than or equal to x <= y
  • 38. ▪ Python Logical Operators ▪ Logical operators are used to combine conditional statements Operator Description Example and Returns True if both statements are true x < 5 and x < 10 or Returns True if one of the statements is true x < 5 or x < 4 not Reverse the result, returns False if the result is true not(x < 5 and x < 10)
  • 39. ▪ Python Identity Operators ▪ Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location: Operator Description Example is Returns True if both variables are the same object x is y is not Returns True if both variables are not the same object x is not y
  • 40. ▪ Python Bitwise Operators ▪ Bitwise operators are used to compare (binary) numbers: ▪ We will not practice Examples of bitwise operators. Operat or Name Description & AND Sets each bit to 1 if both bits are 1 | OR Sets each bit to 1 if one of two bits is 1 ^ XOR Sets each bit to 1 if only one of two bits is 1 ~ NOT Inverts all the bits << Zero fill left shift Shift left by pushing zeros in from the right and let the leftmost bits fall off >> Signed right shift Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off
  • 42. Branching programs • Do you remember the problem of opening a door? • The simplest branching statement is a conditional. • A test(expression that evaluates to True or False) • A block of code to execute if the test is True • An optional block of code to execute if the test is False Code True Block False Block Test Code
  • 43. Python Conditions and If statements • Python supports the usual logical conditions from mathematics: • Equals: a == b • Not Equals: a != b • Less than: a < b • Less than or equal to: a <= b • Greater than: a > b • Greater than or equal to: a >= b
  • 44. Example: • An "if statement" is written by using the if keyword. • Example: If statement: • a = 33 b = 200 if b > a: print ("b is greater than a")
  • 45. Indentation • Python relies on indentation (whitespace at the beginning of a line) to define scope in the code. Each indented set of expressions denotes a block of instructions. • Other programming languages often use curly-brackets for this purpose. • Example: If statement, without indentation (will raise an error): • a = 33 b = 200 if b > a: print ("b is greater than a") # you will get an error Indent expected !!
  • 46. Python User Input • Python allows for user input. • That means we are able to ask the user for input. • name = input("Enter your name:") print(“Your name is: " + name) • Can you write a program to calculate a+b using input? • a=input(“Enter value of a:”) • b=input(“Enter value of b:”) • print(“The sum of a+b is:”, a+b) #Does this work?
  • 47. If - else • Question time: Given the following code, which part of it is the True block? Which part of it is the False block? Code True Block False Block Test Code a = int(input(“Enter first number:”)) b = int(input(“Enter second number:”)) if a>b: print("The bigger number: ”, a ) else: print("The bigger number: ”, b ) print('Done with conditional')
  • 48. Example of Branching programs (elif) • The elif keyword is python way of saying "if the previous conditions were not true, then try this condition". a = int(input(“Enter first number:”)) b = int(input(“Enter second number:”)) if b > a: print("b is greater than a") elif a == b: print("a and b are equal") else: print("b is smaller than a")
  • 49. The pass Statement • if statements cannot be empty, but if you for some reason have an if statement with no content, put in the pass statement to avoid getting an error. • a = 33 b = 200 if b > a: pass
  • 51. Iteration • Concept of iteration let us extend simple branching algorithms to be able to write programs of arbitrary complexity • Strat with a test • If evaluates to True , then execute loop body once, and go back to reevaluate the test. • Repeat until the test is False, after which code following iteration statement is executed. Code Loop body Test Code True False
  • 52. An example of while loop x = int(input("Please input an integer: ")) ans = 0 iterLeft = x while iterLeft != 0: ans = ans + x iterLeft = iterLeft - 1 print(str(x) + '*' + str(x) + '=' + str(ans)) This program square the value of x by addition.
  • 53. Python For Loops • A for loop is used for iterating over a sequence. •Looping Through a String • Even strings are iterable objects, they contain a sequence of characters • Example: • for x in "Neusoft": print(x)
  • 54. The range() Function • To loop through a set of code a specified number of times, we can use the range() function, • The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number. • Example: • for x in range(6): print(x) • Note that range(6) is not the values of 0 to 6, but the values 0 to 5.
  • 55. The break Statement • With the break statement we can stop the loop before it has looped through all the items: • Exit the loop when x is "banana": • fruits = ["apple", "banana", "cherry" ] for x in fruits: print(x) if x == "banana": break • Exit the loop when x is "banana", but this time the break comes before the print: • fruits = ["apple", "banana", "cherry "] for x in fruits: if x == "banana": break print(x)
  • 56. The continue Statement • With the continue statement we can stop the current iteration of the loop, and continue with the next: • Example: • Do not print banana: • fruits = ["apple", "banana", "cherry"] for x in fruits: if x == "banana": continue print(x)
  • 57. Else in For Loop • The else keyword in a for loop specifies a block of code to be executed when the loop is finished: • Print all numbers from 0 to 5, and print a message when the loop has ended: • for x in range(6): print(x) else: print(“For Loop finished!") • Note: The else block will NOT be executed if the loop is stopped by a break statement.
  • 59. Python Lists • Ordered • When we say that lists are ordered, it means that the items have a defined order, and that order will not change. • If you add new items to a list, the new items will be placed at the end of the list. • Changeable • The list is changeable, meaning that we can change, add, and remove items in a list after it has been created. • Allow Duplicates • Since lists are indexed, lists can have items with the same value:
  • 60. Allow Duplicates • Example: • Lists allow duplicate values: • list1 = ["apple", "banana", "cherry", "apple", "cherry"] print(list1) • List Length • To determine how many items a list has, use the len() function: • list1 = ["apple", "banana", "cherry"] print(len(list1))
  • 61. List Items - Data Types • List items can be of any data type: • Example: • list1 = ["apple", "banana", "cherry"] list2 = [1, 5, 7, 9, 3] list3 = [True, False, False] • A list can contain different data types: • list1 = ["abc", 34, True, 40, "male"] • Check type: • print(type(list1))
  • 63. Tuple Items • Tuple items are ordered, unchangeable, and allow duplicate values. • Tuple items are indexed, the first item has index [0], the second item has index [1] etc. • Ordered: When we say that tuples are ordered, it means that the items have a defined order, and that order will not change. • Unchangeable: Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple has been created. • Allow Duplicates: Since tuples are indexed, they can have items with the same value:
  • 64. Create Tuple With One Item • To create a tuple with only one item, you have to add a comma after the item, otherwise Python will not recognize it as a tuple. • tuple1 = ("apple",) print(type(tuple1)) #NOT a tuple tuple2 = ("apple") print(type(tuple2))
  • 65. Tuple Items - Data Types • Tuple items can be of any data type: • tuple1 = ("apple", "banana", "cherry") tuple2 = (1, 5, 7, 9, 3) tuple3 = (True, False, False) • A tuple can contain different data types: • tuple1 = ("abc", 34, True, 40, "male") • The tuple() Constructor • tuple3 = tuple(("apple", "banana", "cherry")) # note the double round-brackets print(tuple3)
  • 67. Python Functions • A function is a block of code which only runs when it is called. • You can pass data, known as parameters, into a function. • A function can return data as a result. • In Python a function is defined using the def keyword: • def my_function(): print("Hello from a function")
  • 68. Why use Python functions? • Functions provide a way to compartmentalize your code into small tasks that can be called from multiple places within a program • This is especially useful if the code in question will be used several times in different parts of your program. • You can think of functions as mini-programs within your bigger program that implement specific tasks. • If you have a block of code that gets called more than once, put it in a function. • Functions may take optional inputs to work with and may optionally return a value or values.
  • 69. User-defined function • As the name suggests, these are functions that are written by the user, to aid them in achieving a specific goal. • The main use of functions is to help us organize our programs into logical fragments that work together to solve a specific part of our problem. • General structure of Python function (Syntax) • The structure of a function is very simple but very important. def {FunctionName}[(parameters)]: # Function Header Indented code..... # Code begins here return
  • 70. Syntax: • Use the def keyword, followed by the function name. • The function name must follow the same naming rules for variables (Single word, No spaces, must start with either a letter or an underscore, etc). • Add parameters (if any) to the function within the parentheses. End the function definition with a full colon. • Write the logic of the function. All code for the function must be indented. • Finally, use the return keyword to return the output of the function. This is optional, and if it is not included, the function automatically returns None. def {FunctionName}[(parameters)]: # Function Header Indented code..... # Code begins here return
  • 72. Python Classes/Objects • Everything in Python is an object and has a type • Objects are a data abstraction that capture: • Internal representation through data attributes • Interface for interacting with object through methods(procedures), defines behaviors but hides implementation • Can create new instances of objects • Can destroy objects • Explicitly using del or just forget about them • Python system will reclaim destroyed or inaccessible objects – called ‘garbage collection’
  • 73. Create a Class • To create a class, use the keyword class: • We can say a class is a user defined data type. • And class can have • Attributes = variables • Behavior = Methods(Functions) class Coordinate(object): """ define attributes here. """
  • 74. Create a Class • Similar to def, it needs indentation to indicate which statements are part of the class definition • The word object means that Coordinate is a Python object and inherits all its attributes (Recommend to inherit object) • Coordinate is a subclass of object • Object is a superclass of Coordinate. class Coordinate(object): """ define attributes here. """
  • 75. What are attributes? • The data and procedures that “belong” to the class • Data attributes • Think of the data as other objects that make up the class • For example, a coordinate is made up of two numbers • Procedure attributes(methods or functions) • Methods that only work with this class • For example, define a distance between two coordinate instances. class Coordinate(object): """ define attributes here. """
  • 76. Creating a class • First have to define how to create an instance of object • Use a special method called __init__() to initialize some data attributes • In python when something starts with “__” it means it’s special • But the __init__() is being called by default(automatically) in python. • Self is the parameter which refer to the instance of the class. class Coordinate(object): def __init__(self, x, y): self.x = x self.y = y
  • 77. Creating a class • About the x, y(data attribute) • When we invokes the creation of an instance, this will bind the variables x and y within that instance to the supplied values. • For every instance of Coordinate, it will have two data attribute, x and y. class Coordinate(object): def __init__(self, x, y): self.x = x self.y = y
  • 79. Main Concepts of Object-Oriented Programming (OOPs) •Class •Objects •Inheritance •Polymorphism •Encapsulation
  • 80. Structured Programming & 3 characteristic of OOP •Structured Programming: •Structured programming adopts the top-down and gradual refinement design method. Each module is connected through the control structure of "sequence, iteration, branching structure and loop", and there is only one entrance and one exit
  • 81. Structured Programming & 3 characteristic of OOP • 3 characteristic of OOP : • Encapsulation(1 mark): that is to encapsulate objective things into abstract classes, and classes can only allow trusted classes or objects to operate their own data and methods, and hide information from untrusted ones.(3 marks) • Inheritance(1 mark): refers to the ability to use all the functions of existing classes and extend them without rewriting the original classes. (3 marks) • Polymorphism(1 mark) is a technology that allows you to set the parent object equal to one or more of its child objects. After assignment, the parent object can operate in different ways according to the characteristics of the child object currently assigned to it. (3 marks)

Editor's Notes

  • #4: 介绍硬件和软件。 What’s program?.
  • #5: 问他们什么是ordered operations?
  • #42: We are going to learn how to make a decision based on test. Branching programs allow us to make different choices and do different things. But still. The program get executed once.
  • #72: For now, we know we have a general idea of what is object. To make this more concrete, Let’s take an example of a built-in data type.