Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
Python Unit 1
1.1 – 1.3
1 . 1 : O P E R AT O R S , E X P R E S S I O N S , A N D
VA R I A B L E S
1.2: STRINGS, FUNCTIONS, CASE
S E N S I T I V I T Y, E T C .
1 . 3 : O U R F I R S T T E X T- B A S E D G A M E
Python – Section 1
Text Book for Python Module
Invent Your Own Computer Games With Python
By Al Swiegert
Easily found on the Internet:
http://inventwithpython.com/chapters/
Python - 1.1
Hint For Slides in This Class
Code is typically in Courier New font.
For Example:
print(‘Hello Everybody’)
This is a common font to represent computer
code within textbooks.
You can access the slides on the Intranet.
Python - 1.1
Python – 1.1
OPERATORS,
EXPRESSIONS, AND
VARIABLES
Python - 1.1
Objectives
By the end of this unit, you will be able to:
Work in IDLE
Define an Interpreter and describe its role Python
Define Integers and Floating Point Numbers
Work with Operators and Expressions
Work with Values
Store Values in Variables
Python - 1.1
Python Interpreter and IDLE
Interpreter – A program that processes each statement in a
program. Three step process:
1.
2.
3.
Evaluate (Does this statement look valid)
Translate (Convert from Python to machine code)
Execute (Make the machine perform this statement)
IDLE – Integrated Development Environment
Text editor for writing and testing Python programs.
Cross-platform (Unix, Linux and PC)
Ships with all versions of Python
Python - 1.1
IDLE – Development Environment
• IDLE helps you program in Python by:
– color-coding your program code
– debugging
– auto-indent
• The example above demonstrates the “Python Shell”.
• >>> Python Command Goes Here
• The Python Shell executes your command when you press enter.
Python - 1.1
Hello World – In IDLE (Students Follow Along)
>>> print('hello world')
hello world
>>>
Enter your command to the right of the >>> symbols:
>>> print('hello world')
The Python Interpreter prints the result of the command
on a line without the greater than signs:
hello world
Python - 1.1
Operators and Expressions
Operators and Operations
Basic Operators:
+ - / *
Expressions
Calculations performed by
combining values and
operators.
Python - 1.1
Math in IDLE
Practice doing mathematical expressions in IDLE
Do some math (guided practice)
Demonstrate a few basic math calculations
<Alt><P> to bring up previous commands
Students practice entering mathematical expressions in IDLE
Addition
Subtraction
Division
Multiplication
Combinations of the above
Python - 1.1
Order of precedence
Precedence - The order in which operations are
computed
Order of Precedence:
1.
Items surrounded by parenthesis (5 / 4)
2.
Exponentiation 5**4
3.
Multiplication 5*4
4.
Division 5/4
5.
Addition 5+4
6.
Subtraction 5-4
There are significantly more rules of precedence
Python - 1.1
Language Syntax
Syntax – the structure of a program and the rules about
that structure.
The commands and the way they are formatted in a program.
Other special characters like {} [] () ; \
Human readable
Python Interpreter converts into machine code upon execution
Syntax Error – Python doesn’t understand your command.
Demonstrate a syntax error.
Python - 1.1
Variables
Variable – Temporary storage for a value.
birthYear = 1964
Upon execution, the Python Interpreter creates the variable
named birthYear and assigns it the value 1964.
Variable values are set from right to left
You can modify the value of birthYear by assigning a
new value to it.
birthYear = 1940
#Chuck Norris’ birth
#
Python - 1.1
year.
Variables in Other Languages
In most other languages you must explicitly create the
variable named birthYear. Java Example:
int birthYear;
birthYear = 1964;
Data Type - The int identifies the type of data that
may be placed into the birthYear variable.
Python does this for you based upon the type of value
assigned to the variable.
Python - 1.1
Data Types
Data Type – The way variables are stored and utilized
within the computer. Types:
Integer (Whole number) -
myAge = 47
Float (Decimal) - myWeight
String - myName
= ‘Mr. Teacher’
Boolean - isTeacher
Python - 1.1
= 221.34
= True
Demonstration of variables (in IDLE)
>>> age = 47
>>> Age
Returns the value 47
>>> age + 5
Returns the value 52
>>> age = age + 10
>>> Age
Returns: 57
>>> teacherName = 'Mr. Sweigart'
Creates a string variable named teacherName and sets its
value to: Mr. Sweigart
>>> teacherName Returns: 'Mr. Sweigart'
Python - 1.1
Variable Demo (Continued)
>>> goodTextbook = True
Creates a Boolean variable named goodTextbook and sets it to: True
>>> weight = 175.09
Creates a float (decimal) variable named weight and sets it to: 175.09
>>> weight = 167.5
Changes the value of weight to: 167.5 (Returns: 167.5)
>>> newWeight = Weight + 22
Creates a variable named newWeight and sets its value to 167.5 + 22
>>> newWeight + 22
>>> newWeight
Returns: 189.5
Python - 1.1
String (in IDLE)
teacherName = 'Mr. Sweigart‘
teacherName = 'Mr. Johnson‘
teacherName2 = 'Mr. Newbee‘
teacher3 = teacherName + teacherName2
What is the value of teacher3?
Python - 1.1
Boolean (in IDLE)
>>> goodTextbook = True
•
Creates a Boolean variable named
goodTextbook and sets it to: True
>>> goodTextBook
•
Returns: True
Python - 1.1
Float (in IDLE)
weight = 175.09
Creates a float (decimal) variable named weight and
sets it to: 175.09
weight = 167.5
weight
Returns: 167.5
newWeight = Weight + 22
newWeight
Python - 1.1
Returns: 189.5
Reading / Exercise(s)
Read CH 2 (The Interactive Shell) in the Invent Your Own
Games with Python book (PDF).
Complete the Python exercises identified on planbook:
Link goes here
Python - 1.1
Python – 1.2
STRINGS, FUNCTIONS,
AND CASE SENSITIVITY
Python - 1.1
Objectives
By the end of this unit you will be able to:
Work with data types (such as strings or integers)
Use IDLE to write source code.
Use the print() and input() functions.
Create comments in your programs
Demonstrate the importance Case-sensitivity in Python
Python - 1.1
Working with Strings (Text)
className = ‘Video Game Programming’
o
The single quotes (apostrophes) define this as a text string.
Try it in IDLE
String Concatenation
className = className + ‘ - and Animation’
Demonstrate in IDLE and display result.
Python - 1.1
Hello World
Create the hello_world.py program in IDLE
o Hello World Program - Typically the first program written when
learning a new language.
o Execute and describe the program
o Assist students in creating their own hello world
program.
Python - 1.1
Hello World
In Python:
print(‘Hello World!’)
In Java:
public class HelloWorld{
public static void main (String[] args){
System.out.println("Hello, world!");
}
}
Python - 1.1
Literals VS Variables
Placing the literal 'Hello World' in myVariable
myVariable = 'Hello World'
Print using a literal string (has quotes)
print('Hello World')
Print using the value within a variable (no quotes)
print(myVariable)
Strings inside variables are easily reused / manipulated.
Python - 1.1
Comments
Only for programmers to read
Used to describe what the code does (very useful for complex code)
You will lose points on your program if you don’t have
comments
o
Your comments need to be unique to your program
Single Line Comments (#)
# Comments are not recognized by the interpreter.
Multi-Line Comments (''')
'''
Multiple lines of comments can go in the middle
'''
Python - 1.1
Function
Function – A mini program that you can call to do
something. Examples Include:
print() Displays a message in the Interpreter.
input() Allows a user to enter data.
Both functions are used in the hello_world.py program.
Calling a function and executing a function are
synonymous.
Python - 1.1
The print() Function
Displays a message to the user.
print ('My name is Peter J. Newbee.')
The following message is displayed
My name is Peter J. Newbee.
Python - 1.1
The input() Function
Most basic form of input() function:
print ('Please enter your name')
playerName = input()
print(playerName)
A more compact form of the input() function:
playerName = input('Please enter your name')
print(playerName)
Python - 1.1
Advanced Hello World
# This program says hello and asks for my name.
print('Hello world!')
print('What is your name?')
myName = input()
print(‘Good to meet you, ' + myName)
Question: Is myName a good name for this variable
Python - 1.1
Advanced Hello World
print (‘Hello World’)
Displays Hello World on the screen when executed.
print (‘what is your name?’)
Displays “What is your name?” when executed.
myName = input ()
Places the user’s response into a variable named myName.
print(‘It is good to meet you, ’ + myName)
Displays It is good to meet you, and the name entered by the user.
Python - 1.1
Concatenation
Concatenation – merging two or more strings together.
print(‘It is good to meet you, ’ + myName)
Displays It is good to meet you, xxx where xxx is the
value entered when the user entered their name.
The plus sign merges the string ‘It is good to meet you,
‘ with the value of the myName variable.
Python - 1.1
Case-Sensitivity
Case – Capitalization or lack of capitalization of a letter.
Case-Sensitive - Declaring different capitalizations of a
name to mean different things.
Python is a case-sensitive language
score, Score, and SCORE are three different variables.
Python - 1.1
Case Sensitivity
Variable names must be referenced in the exact case as
when created
For example:
myName = ‘Pete’
Cannot
be referenced like this:
print(myname)
The
Python - 1.1
‘N’ in myName must be capitalized.
Syntax Rules for Naming Variables
Variable names in Python:
o Can contain letters, numbers, or underscores
o Must begin with a letter or underscore.
Functions names follow the same rules.
The next slide discusses classroom coding standards.
o
Differences between Syntax Rules and Coding Standards???
Python - 1.1
Standards for Variable Names
Why are standards important?
Our standards for naming variables:
o
o
Start with a lowercase letter
Capitalize every word after the first (Camel case).
Example:
o
userFirstName
The F and N must be capitalized to meet our standards.
Must conform to the Python syntax rules
See previous slide for syntax rules
Python - 1.1
Conventions for Working with Strings
Use apostrophes (single quotes) for string
values:
•
Our Standard (single quotes)
o
print(‘Hello World’)
Not our Standard (double quotes)
print(“Hello World”)
Python - 1.1
1.2 Reading / Exercise
See Intranet for reading and exercises.
Exercises 1-2-1 through 1-2-3
Python - 1.1
Python – 1.3
OUR FIRST TEXT
BASED GAME
Python – Unit 1
Objectives
In this unit, we will discuss the following:
o Modules and Import statements
o Arguments
o while statements
o Blocks
o Comparison Operators
o Difference between = and ==
o if statements and conditions
o The break keyword
o The str() and int() functions
o The random.randint() function
Python - 1.1
Modules and the Import Statement
Module – A Python program that contains useful
functions.
import statement – Imports functions from another
module so they can be used.
import random
Makes the functions in the random.py module available within our
current module.
Python - 1.1
The randint() function
import random
randomNumber = random.randint(1, 100)
The above statement generates a random number
between 1 and 100 and places the number in the
randomNumber variable.
The randint function resides in the random module,
which is copied in by the import statement.
Python - 1.1
Arguments and Functions
Function arguments are passed inside the parenthesis of the function
call:
print(‘Hello World’)
The argument is ‘Hello World’
yourName = input(‘Please enter your name’)
Asks the user to enter their name and places the result in the yourName
variable. The argument is the text between the apostrophes.
Python - 1.1
Arguments and Functions
Functions require that you enter the correct number of arguments:
randomNumber = random.randint(1)
o
Generates a syntax error because the randint function requires two
arguments.
Python - 1.1
Loops
Loop – Programming logic that is executed over and
over again until a specific condition(s) is met.
Two types of loops:
while boolean_expression:
Executes as long as the expression evaluates
to True
for
Executes a set number of times
Python - 1.1
Extremely useful
Covered later in course
while Loop
while boolean_expression (evaluates to
true):
# Perform block action
# Perform block action
…
while guessesTaken < 6:
# Ask the user to guess again
# Accept user’s guess
# Evaluate the guess
# Increment guessesTaken variable by 1.
Python - 1.1
Blocks
Block - one or more lines of code grouped together with the
same minimum amount of indentation.
while guessesTaken < 6:
Execute block
o
The colon after the 6 indicates that a block will follow.
o Indented by four spaces (all lines of the block).
o The block ends when return to previous indentation.
Python - 1.1
Block Example (while loop)
while guessesTaken < 6:
----print('Take a guess.')
----guess = input()
----guess = int(guess)
----guessesTaken = guessesTaken + 1
----if guess < number:
--------print('Your guess is too low.')
----if guess > number:
--------print('Your guess is too high.')
if guess == number:
----guessesTaken = str(guessesTaken)
Python - 1.1
Conditions (Boolean Expressions)
Conditions – Expressions that evaluate to
True or False (Boolean Expressions)
myAge = 50
if myAge > 49:
print (‘You are old’)
myAge > 49 evaluates to True (the message prints)
The following use Conditions:
if statements
while Loops
for Loops
Python - 1.1
Comparison Operators (Conditions Continued)
while guessesTaken < 6:
Execute block
The
< sign is the comparison operator
When guessesTaken becomes 6, the while loop ends
and the block of code is no longer executed.
Python - 1.1
== Versus = (Conditions Continued)
Use = to assign a value to a variable
a = b
Use == in a conditional (while, if , or for)
if a == b:
print (‘a has the same value as b’)
Python - 1.1
if Statements
if guess < randomNumber:
print('Your guess is too low')
If the user guessed a number less than randomNumber
“Your guess is too low” is displayed.
Python - 1.1
The if Statement (Equals and Not)
if name = = 'Pete Newbee':
print('Pete is the name')
if name != 'Chuck Norris':
print('Sorry, I am not your hero')
Python - 1.1
Compound Conditionals
Using And
if a < b and a < c:
print ("a is less than b and c")
Using Or
if a < b or a < c:
print ("a is less than either b or c")
This will not work!
if a < b or < c:
Python - 1.1
else and elif
Decision logic where the variable x is an integer.
if x <= 10:
print('X is less than 11')
elif x <= 20:
print ('X is between 11 and 20')
else:
print('X is greater than 20')
elif (like saying “otherwise if”)
else: (Default action if the if/elif conditions do
not evaluate to True)
Python - 1.1
if Versus while
If rupees < 50:
If
keyword
while
while
keyword
Python - 1.1
condition (Boolean Expression)
rupees > 50:
condition (Boolean Expression)
Booleans and Conditionals
isInjured = True
if isInjured:
print(‘The dragon is injured’)
True
The following values evaluate to False:
Any non-zero value evaluates to
The number 0
Empty strings
Python - 1.1
(In a numeric data type)
(Example: myString = '')
The int() Function
guess = input(‘Take a guess‘)
guess = int(guess)
Converts the text from guess into an integer value for
evaluation purposes.
Note: The getInt() function of the game_dev module
does the same as the two commands above.
Python - 1.1
Nested Functions
The following code converts the string that is returned
from the input function into an integer value.
age =
int(input(‘Enter
your age?‘)
)
The input() function receives the age and passes it
to the int() function which converts the value into an
integer.
What would happen if the user entered a non-integer
value?
Note: Same as game_dev.getInt() function
Python - 1.1
Incrementing Variables
Common to most languages:
guessesTaken = guessesTaken + 1
Increments guessesTaken by one.
Python Shortcut:
guessesTaken += 1
Python - 1.1
The break Statement
break – a statement that tells the program to immediately
jump out of the while-block to the first line after the end of the
while-block.
while True:
# Code to generate number would go here.
# Code to retrieve guess would go here.
if guess == number:
break
Breaks out of the while loop if the values of the guess and
number variables are equal.
Python - 1.1
Reading / Exercises
See Intranet
Python - 1.1
Unit Exam
You will be required to write sample code for the exam.
Python - 1.1