Python Unit – : Operators, Expressions, and Variables

Slides:



Advertisements
Similar presentations
Programming in Visual Basic
Advertisements

Introduction to C Programming
Μαθαίνοντας Python [Κ4] ‘Guess the Number’
1 Outline 13.1Introduction 13.2A Simple Program: Printing a Line of Text in a Web Page 13.3Another JavaScript Program: Adding Integers 13.4Memory Concepts.
CS31: Introduction to Computer Science I Discussion 1A 4/2/2010 Sungwon Yang
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
JavaScript, Fourth Edition
JavaScript, Third Edition
Introduction to C Programming
Fundamentals of Python: From First Programs Through Data Structures
Week #2 Java Programming. Enable Line Numbering in Eclipse Open Eclipse, then go to: Window -> Preferences -> General -> Editors -> Text Editors -> Check.
Lecture 2 - Variables, program execution, calculations, print() COMPSCI 101 Principles of Programming.
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
Python Programming Fundamentals
Fundamentals of Python: First Programs
An Introduction to Textual Programming
Line Continuation, Output Formatting, and Decision Structures CS303E: Elements of Computers and Programming.
Introduction to Python
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
2440: 211 Interactive Web Programming Expressions & Operators.
PYTHON: PART 2 Catherine and Annie. VARIABLES  That last program was a little simple. You probably want something a little more challenging.  Let’s.
Sep 12, 2007Sprenkle - CS1111 Objectives Review  Linux  Why programming languages? Compiled vs. Interpreted Languages Programming in Python  Data types.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
CSE 1301 Lecture 2 Data Types Figures from Lewis, “C# Software Solutions”, Addison Wesley Richard Gesick.
Input, Output, and Processing
CPS120: Introduction to Computer Science
20-753: Fundamentals of Web Programming 1 Lecture 12: Javascript I Fundamentals of Web Programming Lecture 12: Introduction to Javascript.
Module 3 Fraser High School. Module 3 – Loops and Booleans import statements - random use the random.randint() function use while loop write conditional.
5 BASIC CONCEPTS OF ANY PROGRAMMING LANGUAGE Let’s get started …
Conditions. Objectives  Understanding what altering the flow of control does on programs and being able to apply thee to design code  Look at why indentation.
Variables and Expressions CMSC 201 Chang (rev )
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
PROGRAMMING In Lesson 2. STARTER ACTIVITY Complete the starter activity in your python folder – lesson 2 Now we will see how you got on and update your.
Variables, Expressions and Statements
Variables and Data Types Data (information we're going to store) – Numbers – Text – Dates What types of data can JavaScript process? How do we store it?
 2000 Deitel & Associates, Inc. All rights reserved. Outline 8.1Introduction 8.2A Simple Program: Printing a Line of Text in a Web Page 8.3Another JavaScript.
Introduction to Python Dr. José M. Reyes Álamo. 2 Three Rules of Programming Rule 1: Think before you program Rule 2: A program is a human-readable set.
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
Python Let’s get started!.
PROGRAMMING IN PYTHON LETS LEARN SOME CODE TOGETHER!
Data Manipulation Variables, Data Types & Math. Aug Variables A variable is a name (identifier) that points to a value. They are useful to store.
Controlling Program Flow with Decision Structures.
Python Basics  Values, Types, Variables, Expressions  Assignments  I/O  Control Structures.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
1 Lecture 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line of Text 2.3Another Simple C Program: Adding.
CMSC201 Computer Science I for Majors Lecture 03 – Variables
Fundamentals of Programming I Overview of Programming
Topics Designing a Program Input, Processing, and Output
Chapter 2 Basic Computation
Python Let’s get started!.
Introduction to Python
Line Continuation, Output Formatting, and Decision Structures
IF statements.
Variables, Expressions, and IO
IDENTIFIERS CSC 111.
Line Continuation, Output Formatting, and Decision Structures
Introduction to C++ Programming
Variables ICS2O.
Topics Designing a Program Input, Processing, and Output
Topics Designing a Program Input, Processing, and Output
Variables, Data Types & Math
Topics Designing a Program Input, Processing, and Output
Topics Designing a Program Input, Processing, and Output
Fundamental OOP Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
In this class, we will cover:
PYTHON - VARIABLES AND OPERATORS
Presentation transcript:

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

Operators, Expressions, and Variables 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: 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: The Python Interpreter prints the result of the command on a line without the greater than signs: 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: Items surrounded by parenthesis (5 / 4) Exponentiation 5**4 Multiplication 5*4 Division 5/4 Addition 5+4 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 # year. Python - 1.1

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 = 221.34 String - myName = ‘Mr. Teacher’ Boolean - isTeacher = True Python - 1.1

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) teacher3 = teacherName + teacherName2 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 Returns: 189.5 Python - 1.1

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

Strings, Functions, and Case Sensitivity 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’ 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 Execute and describe the program Create the hello_world.py program in IDLE Hello World Program - Typically the first program written when learning a new language. Execute and describe the program 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 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 print ('My name is Peter J. Newbee.') 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') Python - 1.1

Advanced Hello World print('Hello world!') print('What is your name?') # 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 ‘N’ in myName must be capitalized. Python - 1.1

Syntax Rules for Naming Variables Variable names in Python: 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. Differences between Syntax Rules and Coding Standards??? Python - 1.1

Standards for Variable Names Why are standards important? Our standards for naming variables: Start with a lowercase letter Capitalize every word after the first (Camel case). Example: 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) 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

Our First Text Based Game Python – 1.3 Our First Text Based Game Python – Unit 1

Objectives In this unit, we will discuss the following: Modules and Import statements Arguments while statements Blocks Comparison Operators Difference between = and == if statements and conditions The break keyword The str() and int() functions 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) Generates a syntax error because the randint function requires two arguments. Python - 1.1

Loops while boolean_expression: 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 Python - 1.1

while Loop # Ask the user to guess again 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 Indented by four spaces (all lines of the block). Block - one or more lines of code grouped together with the same minimum amount of indentation. while guessesTaken < 6: Execute block The colon after the 6 indicates that a block will follow. Indented by four spaces (all lines of the block). 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 rupees < 50: while rupees > 50: if Versus while If condition (Boolean Expression) keyword while rupees > 50: while condition (Boolean Expression) Python - 1.1

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 = '') Python - 1.1

guess = input(‘Take a guess‘) guess = int(guess) 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