SlideShare a Scribd company logo
IWD 2021:
Building an Arcade Game
Using Python Workshop
By
Eng. Mahdi AlFaraj
Mariam AlMahdi
0
Before we start learning let’s
Download
“Python” & “Pycharm”
1
Environment
Website: python.org/downloads/
2
For Mac OS
Environment
3
1. From Downloads file choose python-3.9.2 file
2. Click continue
3. Click agree.
4. Insert your password then click install.
For windows
4
Environment
Downloading PyCharm
code editor
The Python IDE Integrated development environment
Website:
https://www.jetbrains.com/pycharm/do
wnload/#section=mac
5
Download PyCharm (Cont.)
1. Click on “Download” 2. Choose “Community” edition click “Download.
6
Mac users
3. Go to downloads and click on
PyCharm folder.
4. Drag PyCharm icon to
Applications folder.
5. This window will appear because it is
downloaded from the internet.
7
Windows users
3. Click on the downloaded PyCharm folder then click “next”.
4. Click “next”.
5. Check the 64-bit launcher then press ”next”.
8
6. Click ”install”
Windows users
7. Click on “finish”.
8. Click “Accept”.
9. Check ”OK”.
9
10. Click ”Don’t send”
• Choose the first choice then click next , next, next and next again.
• Finally, this is the main page of PyCharm. Click on create new
project.
10
Basics
11
What are we going to learn?
• Basic programming terminologies.
• Variables, String Numbers.
• print function.
• Writing comments.
• If/else statement.
• Loops.
• Range function.
• Modules and modules’ methods.
• Object-oriented programming.
• Functions as parameters.
12
Basic Programming terms
• code or source code: The sequence of instructions in a program.
• syntax: The set of legal structures and commands that can be used in
a particular programming language.
• output: The messages printed to the user by a program.
• console: The text box onto which output is printed.
13
Variables
• Rules for naming variables in Python:
• Variable name cannot be a Python keyword
• Variable name cannot contain spaces
• First character must be a letter or an underscore
• After first character may use letters, digits, or underscores
• Variable names are case sensitive
• Variable name should reflect its use
14
• Defining a variable:
• variable = expression
• Example: age = 29
Strings
• Strings (str)
• Must be enclosed in single (‘) or double (“) quote marks
• For example:
15
my_string = "This is a double-quoted string."
my_string = 'This is a single-quoted string.’
my_string= ‘ This is a “single-quoted” string.’
my_string= “ This is a ‘double-quoted’ string.”
Numbers
• Numbers in Python can be in a form of:
• Integer, for example:
Age = 37
• Float, for example:
GPA = 3.67
• You can do all of the basic operations
with numbers.
• + for addition
• - for subtraction
• * for multiplication
• / for division
• ** for exponent
• () for parenthesis
16
• Example: Output:
print(3+4)
print(1.6-9.5)
print(2**2)
print(5.5/2)
result= 2+ 3*4
print(result)
result= (2+ 3)*4
print(result)
7
-7.9
4
2.75
14
20
Variables, Strings, and Numbers
• Example:
• Calculate the following formula:
𝑎2
+ 𝑏3
× 𝑐
where a= 5, b=4, c=8
save the values in variables.
17
Comments
• Comments: notes of explanation within a program
• Ignored by Python interpreter
• Intended for a person reading the program’s code
• Begin with a # character
• Example:
• Output
# This line is a comment.
print("This line is not a comment, it is
code.")
This line is not a comment, it is code.
18
If statement
Making Decisions – Controlling Program Flow
• To make interesting programs, you must be able to make decisions about
data and take different actions based upon those decisions.
• if statement: Executes a group of statements only if a certain condition
is true. Otherwise, the statements are skipped.
• Syntax of the If statement:
if condition:
Statement
Statement
• First line known as the if clause
• Includes the keyword “if” followed by “condition”
• The condition can be true or false
• When the if statement executes, the condition is tested, and if it is true the block statements
are executed. otherwise, block statements are skipped.
19
if/ else statements
• The syntax of the if statement is as follows:
if boolean expression :
STATEMENT
STATEMENT
• Boolean expression: expression tested by if statement to determine if
it is true or false
• Example: a > b
• true if a is greater than b; false otherwise
• Relational operator: determines whether a specific relationship exists
between two values
• Example: greater than (>)
20
if/ else statements
• Boolean expressions use relational operators:
• Boolean expressions can be combined with logical operators:
21
If statement
• Example:
• Output:
• The indented block of code following an if statement is executed if
the Boolean expression is true, otherwise it is skipped.
22
gpa = 3.4
if gpa > 2.0:
print ("Your application is accepted.”)
Your application is accepted.
if/else Statements
• Dual alternative decision structure:
• two possible paths of execution
• One is taken if the condition is true, and the other if the condition is False
• If you have two mutually exclusive choices and want to guarantee that only
one of them is executed, you can use an if/else statement.
• The else statement adds a second block of code that is executed if the
Boolean expression is False.
• Syntax:
if condition:
statements
else:
other statements
• Rules of if/else statments
• if clause and else clause must be aligned
• Statements must be consistently indented
23
if/else statements
• Syntax:
if boolean expression :
STATEMENT
STATEMENT
else:
STATEMENT
STATEMENT
24
if/else
• if/else statement: Executes one block of statements if a certain
condition is True, and a second block of statements if it is False.
• Example:
25
gpa = 1.4
if gpa > 2.0:
print("Welcome to University!")
else:
print("Your application is denied.")
print(“Good luck”)
Loops
• A loop statement allows us to execute a
statement or group of statements
multiple times.
• Two types of loops:
• for loop:
Executes a sequence of statements multiple
times and abbreviates the code that manages
the loop variable.
• while loop:
Repeats a statement or group of statements
while a given condition is TRUE. It tests the
condition before executing the loop body.
26
range function
• The range function specifies a range of integers:
range (stop) - the integers between 0 (inclusive) and
stop (exclusive)
• Syntax:
for var in range(stop):
statements
• Repeats for values 0 (inclusive) to stop (exclusive)
for i in range(5):
... print(i)
0
1
2
3
4 27
for Loop
• for loop: Repeats a set of statements over a group of values.
• Syntax:
• Rules of loops:
• We indent the statements to be repeated with tabs or spaces.
• VariableName gives a name to each value, so you can refer to it in the statements.
• GroupOfValues can be a range of integers, specified with the range function.
• Example: Output:
for < var > in <sequence or group of valuse>:
<statements>
28
for x in range(1, 6):
print( x, ” squared is ", x * x )
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25
Deference between “for” and “range” function
• Example:
• Output:
• Example:
• Output:
for x in (1 , 5):
print(x," Hello")
1 Hello
5 Hello
for x in range(1 , 5):
print(x," Hello")
1 Hello
2 Hello
3 Hello
4 Hello 29
Loop control statements
break Jumps out of the closest enclosing loop
continue Jumps to the top of the closest enclosing loop
pass Does nothing, empty statement placeholder
30
Nested Loop
• Loops defined within another loop is called Nested loop. When an outer loop contains an inner loop
in its body it is called Nested looping.
• Syntax:
for <expression>:
for <expression>:
body
• for example:
Stops summing at 4
because it is grater than
5 and does not count 5
as an output
2+1 =3
3+1=4
4+1=5 it will give
output 4 and
ends the output
result as 4
31
for a in range (1,5):
for b in range (1,a+1):
print(a)
while
• while loop: Executes a group of statements as long as a condition is
True.
• good for indefinite loops (repeat an unknown number of times)
• Syntax:
while condition:
statements
• Example: Output:
32
number = 1
while number < 200:
print (number)
number = number * 2
1
2
4
8
16
32
64
128
Modules & Modules’ methods
• The highest-level structure of Python
• Each file with the py suffix is a module
• Each module has its own namespace
• Example:
• import mymodule Brings all elements of mymodule in, but must refer to
as mymodule.
• Modules:
• Turtle Module
• Random Module
• Math Module
33
Turtle Module
• turtle is a pre-installed Python library that enables users to create
pictures and shapes by providing them with a virtual canvas. It is very
user friendly and easy to use.
• We use it in our game to generate the game window and the player,
enemies and bullet objects.
• To use it, we must import it at the start of our code using the
command:
34
Examples of turtle methods
• Methods:
• .color
• .shape
• .bgpic
• .penup
• For example:
bullet = turtle.Turtle()
bullet.color("yellow")
bullet.shape("triangle")
bullet.penup()
bullet.speed(0)
35
Random Module
• Python has a built-in module that you can use to create random numbers
called random.
• We will use it to generate a random number for enemy positions in the
game.
• We use this command to import the random module:
• For example:
x = random.randint(-200, 200)
y = random.randint(100, 250)
36
Random Module
Syntax example:
import random
random.random() # returns a float between 0 to 1
random.randint(1, 6) # returns an int between 1 to 6
members = [‘John’, ‘Bob’, ‘Mary’]
leader = random.choice(members) # randomly picks an item
37
Math Module
• Python has a built-in module that you can use for mathematical tasks
called math.
• The math module offers a set of methods and constants that we can use.
Think of functions like cosine, sine, square root and powers. Constants
include the number pi and Euler’s number.
• We use this command to import the math module:
• Example:
distance = math.sqrt(math.pow(t1.xcor()-t2.xcor(),2)+math.pow(t1.ycor()-
t2.ycor(),2))
38
Basics of math module
• Python has useful commands for performing calculations.
To use many of these commands, you must write the following at the top of your Python
program:
from math import *
39
Object-Oriented Programming
• Everything is an object
• Everything means everything, including functions and classes (more
on this later!)
• Data type is a property of the object and not of the variable
40
Functions are objects
• Can be assigned to a variable
• Can be passed as a parameter
• Can be returned from a function
• Functions are treated like any other variable in Python, the def
statement simply assigns a function to a variable
• Function names are like any variable
• The same reference rules hold for them as for other objects
41
Function as parameters
def foo(f, a) :
return f(a)
def bar(x) :
return x * x
from funcasparam import *
foo(bar, 3)
Output:
9
• Note that the function foo takes
two parameters and applies the
first as a function with the
second as its parameter
42
Functions
def max(x,y) :
if x < y :
return x
else :
return y
43
Global and local variables
• A global variable is a variable declared outside of a function
• Scope: this variable can be used in the entire program
• A local variable us a
variable declared inside
of a function.
• Scope: this variable is used
only in the function it
is declared in.
44
num1= 0
num2= num1+6
c=9
def my_function(a,b):
global c
c=0
c+=1
a=b+c
num3=num1*num2
(num1,num2) are global variables
(num1,num2,num3)
are global variables
(a,b,c) are local variables because
they are inside a defined function
Global c will refer to c variable outside the
function and will change its value to 0
Let’s try to develop an arcade game using
what we’ve learned so far 
45
References
• http://bit.ly/2Gp80s6
• Ms. Fatimah Al-Rashed – Python lab
46

More Related Content

What's hot (20)

PPT
conditional statements
James Brotsos
 
PPTX
06.Loops
Intro C# Book
 
PPT
Ch02 primitive-data-definite-loops
James Brotsos
 
PPT
Parameters
James Brotsos
 
PPTX
10. Recursion
Intro C# Book
 
PPTX
02. Data Types and variables
Intro C# Book
 
PPTX
20.5 Java polymorphism
Intro C# Book
 
PPTX
tick cross game
sanobersheir
 
PDF
Acm aleppo cpc training fifth session
Ahmad Bashar Eter
 
PDF
Introduction to python
Marian Marinov
 
PDF
Acm aleppo cpc training introduction 1
Ahmad Bashar Eter
 
PPTX
GE8151 Problem Solving and Python Programming
Muthu Vinayagam
 
PPTX
02. Primitive Data Types and Variables
Intro C# Book
 
PPTX
19. Data Structures and Algorithm Complexity
Intro C# Book
 
DOCX
Simulado java se 7 programmer
Miguel Vilaca
 
PPTX
Java Tutorial: Part 1. Getting Started
Svetlin Nakov
 
PDF
Oracle Certified Associate (OCA) Java SE 8 Programmer II (1Z0-809) - Practice...
Udayan Khattry
 
PDF
Cheat Sheet java
arkslideshareacc
 
PDF
The Ring programming language version 1.5.1 book - Part 18 of 180
Mahmoud Samir Fayed
 
DOCX
Python unit 3 and Unit 4
Anandh Arumugakan
 
conditional statements
James Brotsos
 
06.Loops
Intro C# Book
 
Ch02 primitive-data-definite-loops
James Brotsos
 
Parameters
James Brotsos
 
10. Recursion
Intro C# Book
 
02. Data Types and variables
Intro C# Book
 
20.5 Java polymorphism
Intro C# Book
 
tick cross game
sanobersheir
 
Acm aleppo cpc training fifth session
Ahmad Bashar Eter
 
Introduction to python
Marian Marinov
 
Acm aleppo cpc training introduction 1
Ahmad Bashar Eter
 
GE8151 Problem Solving and Python Programming
Muthu Vinayagam
 
02. Primitive Data Types and Variables
Intro C# Book
 
19. Data Structures and Algorithm Complexity
Intro C# Book
 
Simulado java se 7 programmer
Miguel Vilaca
 
Java Tutorial: Part 1. Getting Started
Svetlin Nakov
 
Oracle Certified Associate (OCA) Java SE 8 Programmer II (1Z0-809) - Practice...
Udayan Khattry
 
Cheat Sheet java
arkslideshareacc
 
The Ring programming language version 1.5.1 book - Part 18 of 180
Mahmoud Samir Fayed
 
Python unit 3 and Unit 4
Anandh Arumugakan
 

Similar to Building arcade game using python workshop (20)

PPTX
Python programing
hamzagame
 
PPTX
made it easy: python quick reference for beginners
SumanMadan4
 
PPTX
Bikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa Thapa
 
PDF
pythonQuick.pdf
PhanMinhLinhAnxM0190
 
PDF
python 34💭.pdf
AkashdeepBhattacharj1
 
PDF
python notes.pdf
RohitSindhu10
 
PPTX
PYTHON PROGRAMMING
indupps
 
PDF
Python unit 2 M.sc cs
KALAISELVI P
 
PPTX
Python
MeHak Gulati
 
PPTX
lecture 2.pptx
Anonymous9etQKwW
 
PPT
Help with Pyhon Programming Homework
Helpmeinhomework
 
PPT
python fundamental for beginner course .ppt
samuelmegerssa1
 
PPTX
Dr.C S Prasanth-Physics ppt.pptx computer
kavitamittal18
 
PDF
Introduction To Programming with Python
Sushant Mane
 
PPTX
Python Basics
primeteacher32
 
PPTX
Programming with python
sarogarage
 
PPTX
Introduction to Python Part-1
Devashish Kumar
 
PPTX
python-presentationpython-presentationpython-presentation.pptx
rkameshwaran50
 
DOCX
A Introduction Book of python For Beginners.docx
kumarrabinderkumar77
 
PPTX
module 2.pptx
mahendranaik18
 
Python programing
hamzagame
 
made it easy: python quick reference for beginners
SumanMadan4
 
Bikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa Thapa
 
pythonQuick.pdf
PhanMinhLinhAnxM0190
 
python 34💭.pdf
AkashdeepBhattacharj1
 
python notes.pdf
RohitSindhu10
 
PYTHON PROGRAMMING
indupps
 
Python unit 2 M.sc cs
KALAISELVI P
 
Python
MeHak Gulati
 
lecture 2.pptx
Anonymous9etQKwW
 
Help with Pyhon Programming Homework
Helpmeinhomework
 
python fundamental for beginner course .ppt
samuelmegerssa1
 
Dr.C S Prasanth-Physics ppt.pptx computer
kavitamittal18
 
Introduction To Programming with Python
Sushant Mane
 
Python Basics
primeteacher32
 
Programming with python
sarogarage
 
Introduction to Python Part-1
Devashish Kumar
 
python-presentationpython-presentationpython-presentation.pptx
rkameshwaran50
 
A Introduction Book of python For Beginners.docx
kumarrabinderkumar77
 
module 2.pptx
mahendranaik18
 
Ad

More from GDGKuwaitGoogleDevel (11)

PDF
معسكر أساسيات البرمجة في لغة بايثون.pdf
GDGKuwaitGoogleDevel
 
PPTX
#Code2 create c++ for beginners
GDGKuwaitGoogleDevel
 
PPTX
i/o extended: Intro to <UX> Design
GDGKuwaitGoogleDevel
 
PDF
#Code2Create:: Introduction to App Development in Flutter with Dart
GDGKuwaitGoogleDevel
 
PPTX
#Code2Create: Python Basics
GDGKuwaitGoogleDevel
 
PDF
Wordpress website development workshop by Seham Abdlnaeem
GDGKuwaitGoogleDevel
 
PPTX
WTM/IWD 202: Introduction to digital accessibility by Dr. Zainab AlMeraj
GDGKuwaitGoogleDevel
 
PPTX
GDG Kuwait - Modern android development
GDGKuwaitGoogleDevel
 
PDF
DevFest Kuwait 2020 - Building (Progressive) Web Apps
GDGKuwaitGoogleDevel
 
PPTX
DevFest Kuwait 2020- Cloud Study Jam: Kubernetes on Google Cloud
GDGKuwaitGoogleDevel
 
PPTX
DevFest Kuwait 2020 - GDG Kuwait
GDGKuwaitGoogleDevel
 
معسكر أساسيات البرمجة في لغة بايثون.pdf
GDGKuwaitGoogleDevel
 
#Code2 create c++ for beginners
GDGKuwaitGoogleDevel
 
i/o extended: Intro to <UX> Design
GDGKuwaitGoogleDevel
 
#Code2Create:: Introduction to App Development in Flutter with Dart
GDGKuwaitGoogleDevel
 
#Code2Create: Python Basics
GDGKuwaitGoogleDevel
 
Wordpress website development workshop by Seham Abdlnaeem
GDGKuwaitGoogleDevel
 
WTM/IWD 202: Introduction to digital accessibility by Dr. Zainab AlMeraj
GDGKuwaitGoogleDevel
 
GDG Kuwait - Modern android development
GDGKuwaitGoogleDevel
 
DevFest Kuwait 2020 - Building (Progressive) Web Apps
GDGKuwaitGoogleDevel
 
DevFest Kuwait 2020- Cloud Study Jam: Kubernetes on Google Cloud
GDGKuwaitGoogleDevel
 
DevFest Kuwait 2020 - GDG Kuwait
GDGKuwaitGoogleDevel
 
Ad

Recently uploaded (20)

PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PDF
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 

Building arcade game using python workshop

  • 1. IWD 2021: Building an Arcade Game Using Python Workshop By Eng. Mahdi AlFaraj Mariam AlMahdi 0
  • 2. Before we start learning let’s Download “Python” & “Pycharm” 1
  • 4. For Mac OS Environment 3 1. From Downloads file choose python-3.9.2 file 2. Click continue 3. Click agree. 4. Insert your password then click install.
  • 6. Downloading PyCharm code editor The Python IDE Integrated development environment Website: https://www.jetbrains.com/pycharm/do wnload/#section=mac 5
  • 7. Download PyCharm (Cont.) 1. Click on “Download” 2. Choose “Community” edition click “Download. 6
  • 8. Mac users 3. Go to downloads and click on PyCharm folder. 4. Drag PyCharm icon to Applications folder. 5. This window will appear because it is downloaded from the internet. 7
  • 9. Windows users 3. Click on the downloaded PyCharm folder then click “next”. 4. Click “next”. 5. Check the 64-bit launcher then press ”next”. 8 6. Click ”install”
  • 10. Windows users 7. Click on “finish”. 8. Click “Accept”. 9. Check ”OK”. 9 10. Click ”Don’t send”
  • 11. • Choose the first choice then click next , next, next and next again. • Finally, this is the main page of PyCharm. Click on create new project. 10
  • 13. What are we going to learn? • Basic programming terminologies. • Variables, String Numbers. • print function. • Writing comments. • If/else statement. • Loops. • Range function. • Modules and modules’ methods. • Object-oriented programming. • Functions as parameters. 12
  • 14. Basic Programming terms • code or source code: The sequence of instructions in a program. • syntax: The set of legal structures and commands that can be used in a particular programming language. • output: The messages printed to the user by a program. • console: The text box onto which output is printed. 13
  • 15. Variables • Rules for naming variables in Python: • Variable name cannot be a Python keyword • Variable name cannot contain spaces • First character must be a letter or an underscore • After first character may use letters, digits, or underscores • Variable names are case sensitive • Variable name should reflect its use 14 • Defining a variable: • variable = expression • Example: age = 29
  • 16. Strings • Strings (str) • Must be enclosed in single (‘) or double (“) quote marks • For example: 15 my_string = "This is a double-quoted string." my_string = 'This is a single-quoted string.’ my_string= ‘ This is a “single-quoted” string.’ my_string= “ This is a ‘double-quoted’ string.”
  • 17. Numbers • Numbers in Python can be in a form of: • Integer, for example: Age = 37 • Float, for example: GPA = 3.67 • You can do all of the basic operations with numbers. • + for addition • - for subtraction • * for multiplication • / for division • ** for exponent • () for parenthesis 16 • Example: Output: print(3+4) print(1.6-9.5) print(2**2) print(5.5/2) result= 2+ 3*4 print(result) result= (2+ 3)*4 print(result) 7 -7.9 4 2.75 14 20
  • 18. Variables, Strings, and Numbers • Example: • Calculate the following formula: 𝑎2 + 𝑏3 × 𝑐 where a= 5, b=4, c=8 save the values in variables. 17
  • 19. Comments • Comments: notes of explanation within a program • Ignored by Python interpreter • Intended for a person reading the program’s code • Begin with a # character • Example: • Output # This line is a comment. print("This line is not a comment, it is code.") This line is not a comment, it is code. 18
  • 20. If statement Making Decisions – Controlling Program Flow • To make interesting programs, you must be able to make decisions about data and take different actions based upon those decisions. • if statement: Executes a group of statements only if a certain condition is true. Otherwise, the statements are skipped. • Syntax of the If statement: if condition: Statement Statement • First line known as the if clause • Includes the keyword “if” followed by “condition” • The condition can be true or false • When the if statement executes, the condition is tested, and if it is true the block statements are executed. otherwise, block statements are skipped. 19
  • 21. if/ else statements • The syntax of the if statement is as follows: if boolean expression : STATEMENT STATEMENT • Boolean expression: expression tested by if statement to determine if it is true or false • Example: a > b • true if a is greater than b; false otherwise • Relational operator: determines whether a specific relationship exists between two values • Example: greater than (>) 20
  • 22. if/ else statements • Boolean expressions use relational operators: • Boolean expressions can be combined with logical operators: 21
  • 23. If statement • Example: • Output: • The indented block of code following an if statement is executed if the Boolean expression is true, otherwise it is skipped. 22 gpa = 3.4 if gpa > 2.0: print ("Your application is accepted.”) Your application is accepted.
  • 24. if/else Statements • Dual alternative decision structure: • two possible paths of execution • One is taken if the condition is true, and the other if the condition is False • If you have two mutually exclusive choices and want to guarantee that only one of them is executed, you can use an if/else statement. • The else statement adds a second block of code that is executed if the Boolean expression is False. • Syntax: if condition: statements else: other statements • Rules of if/else statments • if clause and else clause must be aligned • Statements must be consistently indented 23
  • 25. if/else statements • Syntax: if boolean expression : STATEMENT STATEMENT else: STATEMENT STATEMENT 24
  • 26. if/else • if/else statement: Executes one block of statements if a certain condition is True, and a second block of statements if it is False. • Example: 25 gpa = 1.4 if gpa > 2.0: print("Welcome to University!") else: print("Your application is denied.") print(“Good luck”)
  • 27. Loops • A loop statement allows us to execute a statement or group of statements multiple times. • Two types of loops: • for loop: Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable. • while loop: Repeats a statement or group of statements while a given condition is TRUE. It tests the condition before executing the loop body. 26
  • 28. range function • The range function specifies a range of integers: range (stop) - the integers between 0 (inclusive) and stop (exclusive) • Syntax: for var in range(stop): statements • Repeats for values 0 (inclusive) to stop (exclusive) for i in range(5): ... print(i) 0 1 2 3 4 27
  • 29. for Loop • for loop: Repeats a set of statements over a group of values. • Syntax: • Rules of loops: • We indent the statements to be repeated with tabs or spaces. • VariableName gives a name to each value, so you can refer to it in the statements. • GroupOfValues can be a range of integers, specified with the range function. • Example: Output: for < var > in <sequence or group of valuse>: <statements> 28 for x in range(1, 6): print( x, ” squared is ", x * x ) 1 squared is 1 2 squared is 4 3 squared is 9 4 squared is 16 5 squared is 25
  • 30. Deference between “for” and “range” function • Example: • Output: • Example: • Output: for x in (1 , 5): print(x," Hello") 1 Hello 5 Hello for x in range(1 , 5): print(x," Hello") 1 Hello 2 Hello 3 Hello 4 Hello 29
  • 31. Loop control statements break Jumps out of the closest enclosing loop continue Jumps to the top of the closest enclosing loop pass Does nothing, empty statement placeholder 30
  • 32. Nested Loop • Loops defined within another loop is called Nested loop. When an outer loop contains an inner loop in its body it is called Nested looping. • Syntax: for <expression>: for <expression>: body • for example: Stops summing at 4 because it is grater than 5 and does not count 5 as an output 2+1 =3 3+1=4 4+1=5 it will give output 4 and ends the output result as 4 31 for a in range (1,5): for b in range (1,a+1): print(a)
  • 33. while • while loop: Executes a group of statements as long as a condition is True. • good for indefinite loops (repeat an unknown number of times) • Syntax: while condition: statements • Example: Output: 32 number = 1 while number < 200: print (number) number = number * 2 1 2 4 8 16 32 64 128
  • 34. Modules & Modules’ methods • The highest-level structure of Python • Each file with the py suffix is a module • Each module has its own namespace • Example: • import mymodule Brings all elements of mymodule in, but must refer to as mymodule. • Modules: • Turtle Module • Random Module • Math Module 33
  • 35. Turtle Module • turtle is a pre-installed Python library that enables users to create pictures and shapes by providing them with a virtual canvas. It is very user friendly and easy to use. • We use it in our game to generate the game window and the player, enemies and bullet objects. • To use it, we must import it at the start of our code using the command: 34
  • 36. Examples of turtle methods • Methods: • .color • .shape • .bgpic • .penup • For example: bullet = turtle.Turtle() bullet.color("yellow") bullet.shape("triangle") bullet.penup() bullet.speed(0) 35
  • 37. Random Module • Python has a built-in module that you can use to create random numbers called random. • We will use it to generate a random number for enemy positions in the game. • We use this command to import the random module: • For example: x = random.randint(-200, 200) y = random.randint(100, 250) 36
  • 38. Random Module Syntax example: import random random.random() # returns a float between 0 to 1 random.randint(1, 6) # returns an int between 1 to 6 members = [‘John’, ‘Bob’, ‘Mary’] leader = random.choice(members) # randomly picks an item 37
  • 39. Math Module • Python has a built-in module that you can use for mathematical tasks called math. • The math module offers a set of methods and constants that we can use. Think of functions like cosine, sine, square root and powers. Constants include the number pi and Euler’s number. • We use this command to import the math module: • Example: distance = math.sqrt(math.pow(t1.xcor()-t2.xcor(),2)+math.pow(t1.ycor()- t2.ycor(),2)) 38
  • 40. Basics of math module • Python has useful commands for performing calculations. To use many of these commands, you must write the following at the top of your Python program: from math import * 39
  • 41. Object-Oriented Programming • Everything is an object • Everything means everything, including functions and classes (more on this later!) • Data type is a property of the object and not of the variable 40
  • 42. Functions are objects • Can be assigned to a variable • Can be passed as a parameter • Can be returned from a function • Functions are treated like any other variable in Python, the def statement simply assigns a function to a variable • Function names are like any variable • The same reference rules hold for them as for other objects 41
  • 43. Function as parameters def foo(f, a) : return f(a) def bar(x) : return x * x from funcasparam import * foo(bar, 3) Output: 9 • Note that the function foo takes two parameters and applies the first as a function with the second as its parameter 42
  • 44. Functions def max(x,y) : if x < y : return x else : return y 43
  • 45. Global and local variables • A global variable is a variable declared outside of a function • Scope: this variable can be used in the entire program • A local variable us a variable declared inside of a function. • Scope: this variable is used only in the function it is declared in. 44 num1= 0 num2= num1+6 c=9 def my_function(a,b): global c c=0 c+=1 a=b+c num3=num1*num2 (num1,num2) are global variables (num1,num2,num3) are global variables (a,b,c) are local variables because they are inside a defined function Global c will refer to c variable outside the function and will change its value to 0
  • 46. Let’s try to develop an arcade game using what we’ve learned so far  45