Python Basics: Statements Expressions Loops Strings Functions.

Slides:



Advertisements
Similar presentations
Today’s lecture Review of Chapter 1 Go over homework exercises for chapter 1.
Advertisements

Adapted from John Zelle’s Book Slides
Python Programming: An Introduction to Computer Science
CSC 110 Writing simple programs [Reading: chapter 2] CSC 110 C 1.
Vahé Karamian Python Programming CS-110 CHAPTER 2 Writing Simple Programs.
Computer Science 1620 Variables and Memory. Review Examples: write a program that calculates and displays the average of the numbers 45, 69, and 106.
Intro to Robots Robots are Everywhere. Intro to Robots Various robots in use today lawnmower pet baby seal for convalescents gutter cleaner home security.
Introduction to Python
Chapter 2 Writing Simple Programs
CS 1 with Robots Variables, Data Types & Math Institute for Personal Robots in Education (IPRE)‏
Python. What is Python? A programming language we can use to communicate with the computer and solve problems We give the computer instructions that it.
Chapter 1 Beginnings.
Python.
Introduction to Functions Intro to Computer Science CS1510 Dr. Sarah Diesburg.
A Variable is symbolic name that can be given different values. Variables are stored in particular places in the computer ‘s memory. When a variable is.
CIS Computer Programming Logic
Introduction to Python
General Computer Science for Engineers CISC 106 Lecture 02 Dr. John Cavazos Computer and Information Sciences 09/03/2010.
Python Programming, 2/e1 Python Programming: An Introduction to Computer Science Chapter 2.
A First Program CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington Credits: a significant part of.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 6 Value- Returning Functions and Modules.
PYTHON. Python is a high-level, interpreted, interactive and object- oriented scripting language. Python was designed to be highly readable which uses.
Chapter 6 Functions -- QuickStart. "The Practice of Computing Using Python", Punch & Enbody, Copyright © 2013 Pearson Education, Inc. What is a function?
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 5 Functions.
PYTHON: PART 2 Catherine and Annie. VARIABLES  That last program was a little simple. You probably want something a little more challenging.  Let’s.
Input, Output, and Processing
Strings The Basics. Strings can refer to a string variable as one variable or as many different components (characters) string values are delimited by.
Computer Science 101 Introduction to Programming.
Outline  Why should we use Python?  How to start the interpreter on a Mac?  Working with Strings.  Receiving parameters from the command line.  Receiving.
Functions, Procedures, and Abstraction Dr. José M. Reyes Álamo.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
CMP 131 Introduction to Computer Programming Violetta Cavalli-Sforza Week 5, Lecture 1 (Monday)
Exam 1 Review Instructor – Gokcen Cilingir Cpt S 111, Sections 6-7 (Sept 19, 2011) Washington State University.
Variables, Expressions and Statements
CS 1 with Robots Variables, Data Types & Math Institute for Personal Robots in Education (IPRE)‏ Sec 9-7 Web Design.
Introduction to Strings Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg 1.
Variables and Assignment CSIS 1595: Fundamentals of Programming and Problem Solving 1.
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.
FUNCTIONS. Topics Introduction to Functions Defining and Calling a Void Function Designing a Program to Use Functions Local Variables Passing Arguments.
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
1 Printing in Python Every program needs to do some output This is usually to the screen (shell window) Later we’ll see graphics windows and external files.
A First Program CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington Credits: a significant part of.
2. WRITING SIMPLE PROGRAMS Rocky K. C. Chang September 10, 2015 (Adapted from John Zelle’s slides)
More on Functions Intro to Computer Science CS1510 Dr. Sarah Diesburg.
Python Let’s get started!.
CS201 Introduction to Sabancı University 1 Chapter 2 Writing and Understanding C++ l Writing programs in any language requires understanding.
1. COMPUTERS AND PROGRAMS Rocky K. C. Chang September 6, 2015 (Adapted from John Zelle’s slides)
Python Programming, 2/e1 Python Programming: An Introduction to Computer Science Chapter 2.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
More on Functions Intro to Computer Science CS1510 Dr. Sarah Diesburg.
CS 100 Introduction to Computing Seminar September 12/14, 2016.
Chapter 2 Writing Simple Programs
Python: Experiencing IDLE, writing simple programs
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Presented By S.Yamuna AP/IT
Variables, Expressions, and IO
Introduction to Strings
Introduction to Strings
Functions, Procedures, and Abstraction
T. Jumana Abu Shmais – AOU - Riyadh
Variables, Data Types & Math
Introduction to Strings
Topics Introduction to Value-returning Functions: Generating Random Numbers Writing Your Own Value-Returning Functions The math Module Storing Functions.
Introduction to Strings
Chopin’s Nocturne.
Class code for pythonroom.com cchsp2cs
Introduction to Strings
Functions, Procedures, and Abstraction
PYTHON - VARIABLES AND OPERATORS
Presentation transcript:

Python Basics: Statements Expressions Loops Strings Functions

Program A program is a sequence of instructions or statements. To run a program is to: create the sequence of instructions according to your design and the language rules turn that program into the binary commands the processor understands give the binary code to the OS, so it can give it to the processor OS tells the processor to run the program when finished (or it dies :-), OS cleans up.

Example Code Listing # 1. prompt user for the radius, # 2. apply the area formula # 3. print the results import math radiusString = input("Enter the radius of your circle:") radiusFloat = float(radiusString) circumference = 2 * math.pi * radiusFloat area = math.pi * radiusFloat * radiusFloat print() print("The cirumference of your circle is:",circumference,\ ", and the area is:",area)

Getting Input The function: input(“Give me a value”) prints “Give me a value” on the screen and waits until the user types something (anything), ending with [Enter] key Warning! Input() returns a string (sequence of characters), no matter what is given. (‘1’ is not the same as 1, different types) Convert from string to integer Python requires that you must convert a sequence of characters to an integer Once converted, we can do math on the integers

Import of Math One thing we did was to import the math module with import math This brought in python statements to support math (try it in the python window) We precede all operations of math with math.xxx math.pi, for example, is pi. math.pow(x,y) raises x to the yth power.

Assignment Statement The = sign is the assignment symbol The value on the right is associated with the variable name on the left A variable is a named location that can store values (information). A variable is somewhat like a file, but is in memory not on the HD. = Does not stand for equality here! What “assignment” means is: evaluate all the “stuff” on the rhs (right-hand-side) of the = and take the resulting value and associate it with the name on the lhs (left-h-s)

Printing Output myVar = 12 print(‘My var has a value of:’,myVar) print() function takes a list of elements to print, separated by commas if the element is a string, prints it as is if the element is a variable, prints the value associated with the variable after printing, moves on to a new line of output

Syntax Lexical components. A Python program is (like a hierarchy):. A module (perhaps more than one) A module is just a file of python commands Each module has python statements Statements may have expressions Statements are commands in Python. They perform some action, often called a side effect, but do not return any values Expressions perform some operation and return a value

Side Effects and Returns Make sure you understand the difference. What is the difference between a side effect and a return? 1 + 2 returns a value (it’s an expression). You can “catch” the return value. However, nothing else changed as a result print “hello” doesn’t return anything, but something else - the side effect - did happen. Something printed!

Whitespace white space are characters that don’t print (blanks, tabs, carriage returns etc. For the most part, you can place “white space” (spaces) anywhere in your program use it to make a program more readable However, python is sensitive to end of line stuff. To make a line continue, use the \ print “this is a test”, \ “ of continuation” prints this is a test of continuation

Python Tokens Reserved operators in Python (expressions): Keywords: and del from not while as elif global or with assert else if pass yield break except import print class exec in raise continue finally is return def for lambda try Keywords: You are prevented from using them in a variable name Reserved operators in Python (expressions): + - * ** / // % << >> & | ^ ~ < > <= >= == != <>

Python Punctuators Python punctuation/delimiters ($ and ? not allowed). ‘ “ # \ ( ) [ ] { } @ , : . ` = ; += -= *= /= //= %= &= |= ^= >>= <<= **=

Operators Integer Floating point addition and subtraction: +, - multiplication: * division quotient: // remainder: % Floating point add, subtract, multiply, divide: +, -, *, /

Loops: Repeating Statements Draw Square: Repeat the following steps 4 times: Draw a line Turn left from turtle import * forward(100) left(90) from turtle import * for count in range(4): forward(100) left(90)

While and For Statements from turtle import * for count in range(4): forward(100) left(90) The for statement is useful for iteration, moving through all the elements of data structure, one at a time. The while statement is the more general repetition construct. It repeats a set of statements while some condition is True. from turtle import * count=1 while count<=4: forward(100) left(90) count=count+1

Range Function The range function generates a sequence of integers assumed to start at 0 goes up to, but does not include, the provided number argument. range(3,10) => [3, 4, 5, 6, 7, 8, 9] first argument is the number to begin with second argument is the end limit (not included!)

Iterating Through the Sequence for num in range(1,5): print(num) range generates the sequence [1, 2, 3, 4] for loop assigns num each of the values in the sequence, one at a time in sequence prints each number (one number per line) list(range(-5,5)) # in shell to show range

Sequence of Characters We’ve talked about strings being a sequence of characters. A string is indicated between ‘ ‘ or “ “ The exact sequence of characters is maintained, including spaces. Does NOT include multiple lines Use backslash \ for line continuation

And Then There is “““ ””” Triple quotes preserve both vertical and horizontal formatting of the string Allow you to type tables, paragraphs, whatever and preserve the formatting (like <pre> tag in html) “““this is a test of multiple lines”””

Strings Can use single or double quotes: Just don’t mix them! S = “spam” s = ‘spam’ Just don’t mix them! myStr = ‘hi mom”  ERROR Inserting an apostrophe: A = “knight’s” # mix up the quotes B = ‘knight\’s’ # escape single quote

The Index Because the elements of a string are a sequence, we can associate each element with an index, a location in the sequence: positive values count up from the left, beginning with index 0

Accessing an Element A particular element of the string is accessed by the index of the element surrounded by square brackets [ ] helloStr = ‘Hello World’ print helloStr[1] => prints ‘e’ print helloStr[-1] => prints ‘d’ print helloStr[11] => ERROR

Basic String Operations + is concatenation newStr = ‘spam’ + ‘-’ + ‘spam-’ print newStr  spam-spam- * is repeat, the number is how many times newStr * 3  spam-spam-spam-spam-spam-spam-

String Function: len The len function takes as an argument a string and returns an integer, the length of a string. myStr = ‘Hello World’ len(myStr)  11 # space counts

Example A method represents a special program (function) that is applied in the context of a particular object. upper is the name of a string method. It generates a new string of all upper case characters of the string it was called with. myStr = ‘Python Rules!’ myStr.upper()  ‘PYTHON RULES!’ The string myStr called the upper() method, indicated by the dot between them.

Functions From mathematics we know that functions perform some operation and return one value. Why to use them? Support divide-and-conquer strategy Abstraction of an operation Reuse: once written, use again Sharing: if tested, others can use Security: if well tested, then secure for reuse Simplify code: more readable

Python Invocation Math: f(C) = C*1.8 + 32.0 Python Consider a function which converts temps. in Celsius to temperatures in Fahrenheit: Formula: F = C * 1.8 + 32.0 Math: f(C) = C*1.8 + 32.0 Python def celsius2Fahrenheit (C): return C*1.8 + 32.0 Terminology: “C” is an argument to the function

Return Statement Functions can have input (also called arguments) and output (optional) The return statement indicates the value that is returned by the function. The return statement is optional (a function can return nothing). If no return, the function may be called a procedure.

from turtle import * def draw_square (size): for i in range (4): forward (size) right(90) draw_square(25) draw_square(125) draw_square(75) draw_square(55)