Python Basics  Functions  Loops  Recursion. Built-in functions >>> type (32) >>> int(‘32’) 32  From math >>>import math >>> degrees = 45 >>> radians.

Slides:



Advertisements
Similar presentations
Overloading Having more than one method with the same name is known as overloading. Overloading is legal in Java as long as each version takes different.
Advertisements

Q and A for Chapter 3.4 – 3.14 CS 104 Victor Norman.
I210 review Fall 2011, IUB. Python is High-level programming –High-level versus machine language Interpreted Language –Interpreted versus compiled 2.
Computer Science 1620 Loops.
Python November 18, Unit 7. So Far We can get user input We can create variables We can convert values from one type to another using functions We can.
Chapter 2 Writing Simple Programs
Python Programming Chapter 3: Functions Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
COMP1170 Midterm Preparation (March 17 th 2009) Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education.
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.
Python.
Python – Part 4 Conditionals and Recursion. Modulus Operator Yields the remainder when first operand is divided by the second. >>>remainder=7%3 >>>print.
Introduction to Python
Programming for Linguists An Introduction to Python 24/11/2011.
Control Structures FOR Statement Looping.
FUNCTIONS. Function call: >>> type(32) The name of the function is type. The expression in parentheses is called the argument of the function. Built-in.
Python Mini-Course University of Oklahoma Department of Psychology Day 2 – Lesson 9 Iteration: Recursion 5/02/09 Python Mini-Course: Day 3 - Lesson 9 1.
Python – Part 3 Functions 1. Function Calls Function – A named sequence of statements that performs a computation – Name – Sequence of statements “call”
Introduction to Computing Using Python Straight-line code  In chapter 2, code was “straight-line”; the Python statements in a file (or entered into the.
Python Programming Chapter 6: Iteration Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
>>> # Fibonacci series:... # the sum of two elements defines the next... a, b = 0, 1 >>> while b < 10:... print b... a, b = b, a+b WHILE.
If statements while loop for loop
COMPSCI 101 Principles of Programming Lecture 25 – Nested loops, passing mutable objects as parameters.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
For loops in programming Assumes you have seen assignment statements and print statements.
Functions. Built-in functions You’ve used several functions already >>> len("ATGGTCA")‏ 7 >>> abs(-6)‏ 6 >>> float("3.1415")‏ >>>
C463 / B551 Artificial Intelligence Dana Vrajitoru Python.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
Python Functions.
CSC 110 Using Python [Reading: chapter 1] CSC 110 B 1.
Exam 1 Review Instructor – Gokcen Cilingir Cpt S 111, Sections 6-7 (Sept 19, 2011) Washington State University.
Python – Part 3 Functions 1. Getting help Start the Python interpreter and type help() to start the online help utility. Or you can type help(print) to.
CS105 Computer Programming PYTHON (based on CS 11 Python track: lecture 1, CALTECH)
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.
Jim Havrilla. Invoking Python Just type “python –m script.py [arg]” or “python –c command [arg]” To exit, quit() or Control-D is used To just use the.
By Austin Laudenslager AN INTRODUCTION TO PYTHON.
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.
Python Let’s get started!.
Python Mini-Course University of Oklahoma Department of Psychology Day 3 – Lesson 10 Iteration: Loops 05/02/09 Python Mini-Course: Day 3 - Lesson 10 1.
I NTRODUCTION TO PYTHON - GETTING STARTED ( CONT )
Introduction to Computing Using Python Repetition: the for loop  Execution control structures  for loop – iterating over a sequence  range() function.
CSx 4091 – Python Programming Spring 2013 Lecture L2 – Introduction to Python Page 1 Help: To get help, type in the following in the interpreter: Welcome.
Functions, Part 1 of 3 Topics  Using Predefined Functions  Programmer-Defined Functions  Using Input Parameters  Function Header Comments Reading 
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
LECTURE 2 Python Basics. MODULES So, we just put together our first real Python program. Let’s say we store this program in a file called fib.py. We have.
CMSC 104, Section 301, Fall Lecture 18, 11/11/02 Functions, Part 1 of 3 Topics Using Predefined Functions Programmer-Defined Functions Using Input.
Today… Python Keywords. Iteration (or “Loops”!) Winter 2016CISC101 - Prof. McLeod1.
 Python for-statements can be treated the same as for-each loops in Java Syntax: for variable in listOrstring: body statements Example) x = "string"
Python – Part 4 Conditionals and Recursion. Conditional execution If statement if x>0:# CONDITION print (‘x is positive’) Same structure as function definition.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 next week. See next slide. Both versions of assignment 3 are posted. Due today.
Today… Modularity, or Writing Functions. Winter 2016CISC101 - Prof. McLeod1.
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
Python Simple file reading Peter Wad Sackett. 2DTU Systems Biology, Technical University of Denmark Simple Pythonic file reading Python has a special.
More about Iteration Victor Norman CS104. Reading Quiz.
Chapter 2 Writing Simple Programs
Lesson #6 Modular Programming and Functions.
Lesson #6 Modular Programming and Functions.
Think What will be the output?
Functions.
Functions, Part 1 of 3 Topics Using Predefined Functions
CISC101 Reminders Assn 3 due tomorrow, 7pm.
Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon
Python programming exercise
CISC101 Reminders All assignments are now posted.
Functions, Part 1 of 3 Topics Using Predefined Functions
Topic: Loops Loops Idea While Loop Introduction to ranges For Loop
Functions, Part 1 of 3 Topics Using Predefined Functions
CISC101 Reminders Assignment 3 due today.
Presentation transcript:

Python Basics  Functions  Loops  Recursion

Built-in functions >>> type (32) >>> int(‘32’) 32  From math >>>import math >>> degrees = 45 >>> radians = degrees/360.0 * 2 * math.pi >>> math.sin(radians)  Composition >>>x = math.exp(math.log(x+1))

Adding functions  Specify the name of a new function and the sequence of statements def print_lyrics(): print (‘Twinkle, twinkle, little star,\n’) print (‘How I wonder what you are?\n’)  Note the header ends with a colon and the body is indented. ◦Convention is to indent 4 spaces btw.  If you’re in interactive mode, the interpreter prints ellipses to let you know you aren’t done. To end, enter an empty line.

More on functions  Defining a function creates a variable with same name >>> print print_lyrics >>> type (print_lyrics>  Syntax for calling them is same as built-in  Can call them in another function >>> def repeat_lyrics(): >>> print_lyrics()

Flow of execution  You can define a function in the middle of code ◦Just make sure you define a function before you use it ◦You might do this if you are writing scripts ◦Can do it in code you save – DON’T!!!

Parameters and Arguments  Arguments are in call statements  Parameters are in function headings  Pass arguments to parameters. ◦Pass values to parameters ◦Pass variables to parameters

Example def print_twice (s): print (s) print_twice(17) print_twice (‘Spam’) name = ‘Bruce’ print_twice (name) Outputs: Spam Spam Bruce Bruce  See anything interesting here?

Variables and parameters  Variables and parameters are local ◦Only exist inside function ◦Do not get a type, until you pass an argument to it ◦Be CAREFUL!!! ◦Implicit variable declarations can cause problems - violates security principle.  Arguments are passed neither by value nor by reference in Python- instead they are passed by assignment. The parameter passed in is actually a reference to an object, as opposed to reference to a fixed memory location but the reference is passed by value. ◦Immutable objects like integers, strings: passing acts like pass-by-value ◦Mutable objects: pass object reference (by value), so object can be changed

Fruitful and void functions  When a function yields results – it is called a fruitful function ◦If it doesn’t, it is a void function  Always do something with the result of fruitful function ◦Assign it to a variable ◦Use it in a condition  if you try to assign result of a void function to a variable, you get a value called None >>> result = print_twice(17) >>> print result None #note: not ‘None’

Importing with from  Can import two ways import math or from math import pi  Latter will allow you to refer to pi directly without dot notation >>>print pi  Can use star operator to import everything from the module from math import * ◦More concise code (advantage) ◦Naming conflicts (disadvantage)

Recursion  It is a legal for a function to call itself def countdown(n): if n <= 0: print (‘Blastoff!’) else: print (n) countdown(n-1) countdown(10)

range() function  range is a function to iterate over a sequence of numbers  range(n ) generates an iterator to progress from 0 to n-1  range(begin, end) generates an iterator to progress from begin to end-1  range(begin, end, step) generates an iterator to progress from begin to end-1, incrementing (or decrementing by the step) >>>range (4, 10) range(4,10) >>>list(range(4,10)) [4,5,6,7,8,9]

Simple Repetition  For loop for i in range(4): print (‘Hello!’)  while loop n = 10 while n > 0: print (‘Hello!’) n = n – 1 print (‘Blastoff!’)

Some questionable loop examples  Using a break while True: line = input (‘> ‘) if line == ‘done’: break print (line) print (‘Done!’)

Refactoring loop  Not using a break line = input (‘> ‘) while line != ‘done’: print (line) line = input (‘> ‘) print (‘Done!’)

Loop example fibonacci = [0,1,1,2,3,5,8,13,21] for i in range(len(fibonacci)): print(i,fibonacci[i]) print()  Output looks like this :

For-each loop with optional loop else edibles = ["ham", "spam","eggs","nuts"] for food in edibles: if food == "spam": print("No more spam please!") break print("Great, delicious " + food) #loop else, only executed if loop not broken else: print("I am so glad: No spam!") print("Finally, I finished stuffing myself") Demo – with spam in list and without