Python Unit

Similar documents
Python Games. Session 1 By Declan Fox

ENGR 101 Engineering Design Workshop

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Python Unit

Algorithms and Programming I. Lecture#12 Spring 2015

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

Object-Oriented Programming

Introduction to: Computers & Programming: Review prior to 1 st Midterm

PRG PROGRAMMING ESSENTIALS. Lecture 2 Program flow, Conditionals, Loops

Programming in Python 3

Text Input and Conditionals

Expressions and Variables

Python The way of a program. Srinidhi H Asst Professor Dept of CSE, MSRIT

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Introduction to Python (All the Basic Stuff)

SOFT 161. Class Meeting 1.6

Decisions, Decisions. Testing, testing C H A P T E R 7

Fundamentals of Programming (Teacher Pack)

CMSC 201 Computer Science I for Majors

COMP-202: Foundations of Programming. Lecture 2: Variables, and Data Types Sandeep Manjanna, Summer 2015

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

This summary is located here:

age = 23 age = age + 1 data types Integers Floating-point numbers Strings Booleans loosely typed age = In my 20s

Procedures, Parameters, Values and Variables. Steven R. Bagley

There are two ways to use the python interpreter: interactive mode and script mode. (a) open a terminal shell (terminal emulator in Applications Menu)

Welcome to Python 3. Some history

Lesson 3: Basic Programming Concepts

Professor: Sana Odeh Lecture 3 Python 3.1 Variables, Primitive Data Types & arithmetic operators

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

Review. Input, Processing and Output. Review. Review. Designing a Program. Typical Software Development cycle. Bonita Sharif

CS2900 Introductory Programming with Python and C++ Kevin Squire LtCol Joel Young Fall 2007

There are two ways to use the python interpreter: interactive mode and script mode. (a) open a terminal shell (terminal emulator in Applications Menu)

Invent Your Own Computer Games with Python 3 rd Edition

NESTED IF STATEMENTS AND STRING/INTEGER CONVERSION

Basic Concepts. Computer Science. Programming history Algorithms Pseudo code. Computer - Science Andrew Case 2

Chapter 2 Working with Data Types and Operators

Software and Programming 1

Getting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an . Michigan State University CSE 231, Fall 2013

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

Computer Components. Software{ User Programs. Operating System. Hardware

Key Differences Between Python and Java

Invent Your Own Computer Games with Python

Lecture 2. COMP1406/1006 (the Java course) Fall M. Jason Hinek Carleton University

SAMS Programming A/B. Lecture #1 Introductions July 3, Mark Stehlik

Introduction to computers and Python. Matthieu Choplin

Hello, World! An Easy Intro to Python & Programming. Jack Rosenthal

Python Programming Exercises 1

Full file at

VARIABLES. Aim Understanding how computer programs store values, and how they are accessed and used in computer programs.

Programming with Python

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1

Chapter 2 Getting Started with Python

3. Java - Language Constructs I

Values and Variables 1 / 30

4 Programming Fundamentals. Introduction to Programming 1 1

Programming with Java

Programming. We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems.

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */

6.096 Introduction to C++ January (IAP) 2009

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

The current topic: Python. Announcements. Python. Python

Basics of Java Programming

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

COMS 469: Interactive Media II

6.S189 Homework 1. What to turn in. Exercise 1.1 Installing Python. Exercise 1.2 Hello, world!

RTL Reference 1. JVM. 2. Lexical Conventions

Scripting Languages. Python basics

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG

Introduction to Programming Using Java (98-388)

Course Outline. Introduction to java

CSCE 110 Programming I Basics of Python: Variables, Expressions, Input/Output

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Unit 6 - Software Design and Development LESSON 3 KEY FEATURES

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Python Input, output and variables

Honors Computer Science Python Mr. Clausen Programs 4A, 4B, 4C, 4D, 4E, 4F

Introduction to Java. Java Programs Classes, Methods, and Statements Comments Strings Escape Sequences Identifiers Keywords

Program Fundamentals

Introduction to Java Applications

Java Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Python Input, output and variables. Lecture 22 COMPSCI111/111G SS 2016

Introduction to programming with Python

CHAPTER 2: Introduction to Python COMPUTER PROGRAMMING SKILLS

CS11 Java. Fall Lecture 1

Computer and Programming: Lab 1

Introduction to Computer Programming CSCI-UA 2. Review Midterm Exam 1

MICROPROCESSOR SYSTEMS INTRODUCTION TO PYTHON

The Big Python Guide

CS1 Lecture 3 Jan. 22, 2018

Constants. Variables, Expressions, and Statements. Variables. x = 12.2 y = 14 x = 100. Chapter

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

Full file at C How to Program, 6/e Multiple Choice Test Bank

VLC : Language Reference Manual

Software and Programming 1

egrapher Language Reference Manual

Working with JavaScript

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

Hello, World and Variables

Transcription:

Python Unit 1 1.1 1.3 1.1: OPERATORS, EXPRESSIONS, AND VARIABLES 1.2: STRINGS, FUNCTIONS, CASE SENSITIVITY, ETC. 1.3: OUR FIRST TEXT- BASED GAME 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/

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

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

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 Operators and Operations Basic Operators: + - / * Expressions Calculations performed by combining values and operators.

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

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

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.

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

Data Types Data Type The way variables are stored and utilized within the computer. Types: Integer (Whole number) - myage = 47 Float (Decimal) - myweight = 221.34 String - myname = Mr. Teacher Boolean - isteacher = 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'

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

String (in IDLE) teachername = 'Mr. Sweigart teachername = 'Mr. Johnson teachername2 = 'Mr. Newbee teacher3 = teachername + teachername2 What is the value of teacher3?

Boolean (in IDLE) >>> goodtextbook = True Creates a Boolean variable named goodtextbook and sets it to: True >>> goodtextbook Returns: True

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 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.2 STRINGS, FUNCTIONS, AND CASE SENSITIVITY

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

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.

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.

Hello World 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.

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

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.

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.

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)

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

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.

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.

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.

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 N in myname must be capitalized.

Syntax Rules for Naming Variables Variable names in Python: o o Can contain letters, numbers, or underscores 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 Why are standards important? Our standards for naming variables: o Start with a lowercase letter o 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 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 See Intranet for reading and exercises. Exercises 1-2-1 through 1-2-3

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

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.

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.

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.

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.

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

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.

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)

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

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.

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

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.

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

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:

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)

if Versus while If rupees < 50: If keyword condition (Boolean Expression) while rupees > 50: while keyword condition (Boolean Expression)

Booleans and Conditionals isinjured = True if isinjured: print( The dragon is injured ) Any non-zero value evaluates to True The following values evaluate to False: The number 0 (In a numeric data type) Empty strings (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.

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

Incrementing Variables Common to most languages: guessestaken = guessestaken + 1 Increments guessestaken by one. Python Shortcut: guessestaken += 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.

Reading / Exercises See Intranet

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