1.1: operators, expressions, and variables 1.2: strings, functions, case sensitivity, etc. 1.3: our...

Post on 18-Jan-2016

235 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

1.1: OPERATORS, EXPRESSIONS, AND VARIABLES

1.2: STRINGS, FUNCTIONS, CASE SENSITIVITY, ETC.

1.3: OUR FIRST TEXT-BASED GAME

Python – Section 1

Python Unit 11.1 – 1.3

Text Book for Python Module

Python - 1.1

Invent Your Own Computer Games With Python By Al Swiegert

Easily found on the Internet: http://inventwithpython.com/chapters/

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

OPERATORS, EXPRESSIONS, AND

VARIABLES

Python - 1.1

Python – 1.1

Objectives

Python - 1.1

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 Interpreter and IDLE

Python - 1.1

Interpreter – A program that processes each statement in a program. Three step process:1. Evaluate (Does this statement look valid)

2. Translate (Convert from Python to machine code)

3. 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

IDLE – Development Environment

Python - 1.1

• 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

Operators and Expressions

Python - 1.1

Operators and Operations Basic Operators:

+ - / *

Expressions Calculations performed by

combining values and operators.

Math in IDLE

Python - 1.1

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

Order of precedence

Python - 1.1

Precedence - The order in which operations are computed

Order of Precedence:1. Items surrounded by parenthesis (5 / 4)2. Exponentiation 5**43. Multiplication 5*44. Division 5/45. Addition 5+4

6. Subtraction 5-4There are significantly more rules of precedence

Language Syntax

Python - 1.1

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.

Variables

Python - 1.1

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 # year.

Variables in Other Languages

Python - 1.1

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.

Data Types

Python - 1.1

Data Type – The way variables are stored and utilized within the computer. Types:

Integer (Whole number) - myAge = 47Float (Decimal) - myWeight = 221.34

String - myName = ‘Mr. Teacher’

Boolean - isTeacher = True

Demonstration of variables (in IDLE)

Python - 1.1

>>> 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'

Variable Demo (Continued)

Python - 1.1

>>> 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

String (in IDLE)

Python - 1.1

teacherName = 'Mr. Sweigart‘

teacherName = 'Mr. Johnson‘

teacherName2 = 'Mr. Newbee‘

teacher3 = teacherName + teacherName2What is the value of teacher3?

Boolean (in IDLE)

Python - 1.1

>>> goodTextbook = True

• Creates a Boolean variable named goodTextbook and sets it to: True

>>> goodTextBook

• Returns: True

Float (in IDLE)

Python - 1.1

weight = 175.09 Creates a float (decimal) variable named weight and

sets it to: 175.09

weight = 167.5weight Returns: 167.5

newWeight = Weight + 22

newWeight Returns: 189.5

Reading / Exercise(s)

Python - 1.1

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

STRINGS, FUNCTIONS, AND CASE SENSITIVITY

Python - 1.1

Python – 1.2

Objectives

Python - 1.1

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

Working with Strings (Text)

Python - 1.1

className = ‘Video Game Programming’o The single quotes (apostrophes) define this as a text string.

Try it in IDLE

String ConcatenationclassName = className + ‘ - and Animation’

Demonstrate in IDLE and display result.

Hello World

Python - 1.1

Create the hello_world.py program in IDLEo Hello World Program - Typically the first program written when

learning a new language.

o Execute and describe the programo Assist students in creating their own hello world

program.

Hello World

Python - 1.1

In Python:print(‘Hello World!’)

In Java:public class HelloWorld{ public static void main (String[] args){ System.out.println("Hello, world!"); }}

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

Python - 1.1

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

commentso 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'''

Function

Python - 1.1

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.

The print() Function

Python - 1.1

Displays a message to the user.

print ('My name is Peter J. Newbee.')

The following message is displayed

My name is Peter J. Newbee.

The input() Function

Python - 1.1

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)

Advanced Hello World

Python - 1.1

# 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

Advanced Hello World

Python - 1.1

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.

Concatenation

Python - 1.1

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.

Case-Sensitivity

Python - 1.1

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.

Case Sensitivity

Python - 1.1

Variable names must be referenced in the exact case as when created

For example:myName = ‘Pete’

Cannot be referenced like this:

print(myname)

The ‘N’ in myName must be capitalized.

Syntax Rules for Naming Variables

Python - 1.1

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???

Standards for Variable Names

Python - 1.1

Why are standards important? Our standards for naming variables:

o Start with a lowercase lettero Capitalize every word after the first (Camel case).

Example: userFirstName The F and N must be capitalized to meet our standards.

o Must conform to the Python syntax rules See previous slide for syntax rules

Conventions for Working with Strings

Python - 1.1

Use apostrophes (single quotes) for string values:• Our Standard (single quotes)

print(‘Hello World’)

o Not our Standard (double quotes) print(“Hello World”)

1.2 Reading / Exercise

Python - 1.1

See Intranet for reading and exercises.Exercises 1-2-1 through 1-2-3

OUR FIRST TEXT BASED GAME

Python – Unit 1

Python – 1.3

Objectives

Python - 1.1

In this unit, we will discuss the following:o Modules and Import statementso Argumentso while statementso Blockso Comparison Operatorso Difference between = and ==o if statements and conditionso The break keywordo The str() and int() functionso The random.randint() function

Modules and the Import Statement

Python - 1.1

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.

The randint() function

Python - 1.1

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.

Arguments and Functions

Python - 1.1

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.

Arguments and Functions

Python - 1.1

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.

Loops

Python - 1.1

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 Extremely useful Covered later in course

while Loop

Python - 1.1

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.

Blocks

Python - 1.1

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.

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)

Python - 1.1

Conditions – Expressions that evaluate to True or False (Boolean Expressions)

myAge = 50if myAge > 49: print (‘You are old’)

myAge > 49 evaluates to True (the message prints)

The following use Conditions: if statements while Loops for Loops

Comparison Operators (Conditions Continued)

Python - 1.1

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.

== Versus = (Conditions Continued)

Python - 1.1

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’)

if Statements

Python - 1.1

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.

The if Statement (Equals and Not)

Python - 1.1

if name = = 'Pete Newbee':

print('Pete is the name')

if name != 'Chuck Norris':

print('Sorry, I am not your hero')

Compound Conditionals

Python - 1.1

Using Andif a < b and a < c:

print ("a is less than b and c")

Using Orif a < b or a < c:

print ("a is less than either b or c")

This will not work!if a < b or < c:

else and elif

Python - 1.1

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)

if Versus while

Python - 1.1

If rupees < 50:

If condition (Boolean Expression)

keyword

while rupees > 50:

while condition (Boolean Expression)

keyword

Booleans and Conditionals

Python - 1.1

isInjured = True

if isInjured:

print(‘The dragon is injured’)

Any non-zero value evaluates to TrueThe following values evaluate to False:

The number 0 (In a numeric data type) Empty strings (Example: myString = '')

The int() Function

Python - 1.1

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.

Nested Functions

Python - 1.1

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

Incrementing Variables

Python - 1.1

Common to most languages:

guessesTaken = guessesTaken + 1

Increments guessesTaken by one.

Python Shortcut:

guessesTaken += 1

The break Statement

Python - 1.1

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:

breakBreaks out of the while loop if the values of the guess and number variables are equal.

Reading / Exercises

Python - 1.1

See Intranet

Unit Exam

Python - 1.1

You will be required to write sample code for the exam.

top related