Python Crash Course Functions, Modules 3 rd year Bachelors V1.0 dd 03-09-2013 Hour 5.

Slides:



Advertisements
Similar presentations
Exception Handling Genome 559. Review - classes 1) Class constructors - class myClass: def __init__(self, arg1, arg2): self.var1 = arg1 self.var2 = arg2.
Advertisements

Lilian Blot PART V: FUNCTIONS Core elements Autumn 2013 TPOP 1.
Lilian Blot CORE ELEMENTS PART V: FUNCTIONS PARAMETERS & VARIABLES SCOPE Lecture 5 Autumn 2014 TPOP 1.
15. Python - Modules A module allows you to logically organize your Python code. Grouping related code into a module makes the code easier to understand.
Python Mini-Course University of Oklahoma Department of Psychology Day 1 – Lesson 4 Beginning Functions 4/5/09 Python Mini-Course: Day 1 - Lesson 4 1.
Chapter Modules CSC1310 Fall Modules Modules Modules are the highest level program organization unit, usually correspond to source files and.
Setting the PYTHONPATH PYTHONPATH is where Python looks for modules it is told to import List of paths Add new path to the end with: setenv PYTHONPATH.
Python for Science Shane Grigsby. What is python? Why python? Interpreted, object oriented language Free and open source Focus is on readability Fast.
Perkovic, Chapter 7 Functions revisited Python Namespaces
Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
Getting started with ML ML is a functional programming language. ML is statically typed: The types of literals, values, expressions and functions in a.
A Crash Course Python. Python? Isn’t that a snake? Yes, but it is also a...
BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming.
Bash Shell Scripting 10 Second Guide Common environment variables PATH - Sets the search path for any executable command. Similar to the PATH variable.
Python.
Intermediate PHP (2) File Input/Output & User Defined Functions.
Python Programming Fundamentals
4. Python - Basic Operators
By Zeng Sheng Liu. os - provides dozens of functions for interacting with the operating system >>> import os >>> os.system('time 0:02') 0 >>> os.getcwd()
Introduction to Python Basics of the Language. Install Python Find the most recent distribution for your computer at:
Builtins, namespaces, functions. There are objects that are predefined in Python Python built-ins When you use something without defining it, it means.
Python Crash Course Functions, Modules Bachelors V1.0 dd Hour 1.
By: Joshua O’Donoghue. Operating System Interface In order to interact with the operating system in python you will want to become familiar with the OS.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 6 Value- Returning Functions and Modules.
Introduction to Computational Linguistics Programming I.
Python Modules An Introduction. Introduction A module is a file containing Python definitions and statements. The file name is the module name with the.
1 CSC 221: Introduction to Programming Fall 2012 Functions & Modules  standard modules: math, random  Python documentation, help  user-defined functions,
H3D API Training  Part 3.1: Python – Quick overview.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 5 Functions.
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
By James Braunsberg. What are Modules? Modules are files containing Python definitions and statements (ex. name.py) A module’s definitions can be imported.
Overview Intro to functions What are functions? Why use functions? Defining functions Calling functions Documenting functions Top-down design Variable.
C463 / B551 Artificial Intelligence Dana Vrajitoru Python.
Python Functions.
Exam 1 Review Instructor – Gokcen Cilingir Cpt S 111, Sections 6-7 (Sept 19, 2011) Washington State University.
An Introduction. What is Python? Interpreted language Created by Guido Van Rossum – early 90s Named after Monty Python
Copyright © 2003 ProsoftTraining. All rights reserved. Perl Fundamentals.
Department of Electrical and Computer Engineering Introduction to Perl By Hector M Lugo-Cordero August 26, 2008.
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.
Python Let’s get started!.
Python Basics  Functions  Loops  Recursion. Built-in functions >>> type (32) >>> int(‘32’) 32  From math >>>import math >>> degrees = 45 >>> radians.
12. MODULES Rocky K. C. Chang November 6, 2015 (Based on from Charles Dierbach. Introduction to Computer Science Using Python and William F. Punch and.
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.
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.
Linux Administration Working with the BASH Shell.
Lecture III Syntax ● Statements ● Output ● Variables ● Conditions ● Loops ● List Comprehension ● Function Calls ● Modules.
Python’s Modules Noah Black.
Topics Introduction to Functions Defining and Calling a Void Function
G. Pullaiah College of Engineering and Technology
Ruby: An Introduction Created by Yukihiro Matsumoto in 1993 (named after his birthstone) Pure OO language (even the number 1 is an instance of a class)
Lecture 2 Python Basics.
Python Let’s get started!.
Introduction to Python
Variables, Expressions, and IO
Functions CIS 40 – Introduction to Programming in Python
CSC113: Computer Programming (Theory = 03, Lab = 01)
PH2150 Scientific Computing Skills
CHAPTER FOUR Functions.
Python’s Standard library part I
Rocky K. C. Chang 15 November 2018 (Based on Dierbach)
Topics Introduction to Value-returning Functions: Generating Random Numbers Writing Your Own Value-Returning Functions The math Module Storing Functions.
Introduction to Value-Returning Functions: Generating Random Numbers
G. Pullaiah College of Engineering and Technology
Boolean Expressions to Make Comparisons
COMPUTER PROGRAMMING SKILLS
 A function is a named sequence of statement(s) that performs a computation. It contains  line of code(s) that are executed sequentially from top.
Functions John R. Woodward.
Python Modules.
Presentation transcript:

Python Crash Course Functions, Modules 3 rd year Bachelors V1.0 dd Hour 5

Introduction to language - functions >>> def my_func(x, y=0.0, z=1.0):... a = x + y... b = a * z... return b... >>> my_func(1.0, 3.0, 2.0) 8.0 >>> my_func(1.0, 3.0) 4.0 >>> my_func(1.0, y=3.0) 4.0 >>> my_func(5.0) 5.0 >>> my_func(2.0, z=3.0) 6.0 >>> my_func(x=2.0, z=3.0) 6.0 Here are simple rules to define a function in Python: Function blocks begin with the keyword def followed by the function name and parentheses ( ). Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses. The code block within every function starts with a colon : and is indented. The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.

Introduction to language - functions >>> def fact(n):... if(n==0): return 1;... m = 1;... k = 1;... while(n >= k):... m = m * k;... k = k + 1;... return m; Recursion: >>> def fact(n):... if n > 0:... return n * fact(n-1) # Recursive call... return 1# exits function returning 1 >>> print fact(100) >>> print fact(1000)

Introduction to language - functions The Anonymous Functions: You can use the lambda keyword to create small anonymous functions. These functions are called anonymous because they are not declared by using the def keyword. Lambda forms can take any number of arguments but return just one value in the form of an expression. They cannot contain commands or multiple expressions. An anonymous function cannot be a direct call to print because lambda requires an expression. Lambda functions have their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace. #!/usr/bin/python # Function definition is here sum = lambda arg1, arg2: arg1 + arg2; # Now you can call sum as a function print "Value of total : ", sum( 10, 20 ) print "Value of total : ", sum( 20, 20 ) Value of total : 30 Value of total : 40

Introduction to language - scope Variables defined within the function are local to the function. For variables referenced (by which we mean “used” i.e. on right hand side of assignment statement) in the function, interpreter looks first in the local symbol table, then outside (globally). >>> def fib(n):... # write Fibonacci series up to n... """Print a Fibonacci series up to n.""“... a, b = 0, 1... while a < n:... print a,... a, b = b, a+b... print x >>> x = “Hi there” >>> a = 11 >>> print a 11 >>> fib(2000) Hi there >>> print a 11

Introduction to language - arguments e.g. Arguments with default values: >>> def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):... ”””Demonstrate default values”””... while True:... ok = raw_input(prompt)... if ok in ('y', 'ye', 'yes'):... return True... if ok in ('n', 'no', 'nop', 'nope'):... return False... retries = retries if retries < 0:... raise IOError('refusenik user')... print complaint

List comprehensions A neat way of creating lists (and arrays) without writing a loop a = [ x**2 for x in range(10)] my_fav_num = [3, 17, 22, 46, 71, 8] even_squared = [] for n in my_fav_num: if n%2 == 0: even_squared.append(n**2) # in one line: even_better = [n**2 for n in my_fav_num if n%2 == 0] # both produce [484, 2116, 64 freshfruit = [' banana', ' loganberry ', 'passion fruit '] stripped = [weapon.strip() for weapon in freshfruit] print(stripped) ['banana', 'loganberry', 'passion fruit']

Introduction to language - Modules def print_func( par ): print "Hello : ", par return #!/usr/bin/python # Import module hello import hello # Now you can call defined function that module as follows hello.print_func(“Earth") Hello : Earth from modname import name1[, name1[, … nameN]] from modname import * Importing into the current namespace should be done with care due to name clashes

Introduction to languge - Modules When you import a module, the Python interpreter searches for the module in the following sequences: The current directory. If the module isn't found, Python then searches each directory in the shell variable PYTHONPATH. If all else fails, Python checks the default path. On UNIX, this default path is normally /usr/local/lib/python/. The module search path is stored in the system module sys as the sys.path variable. The sys.path variable contains the current directory, PYTHONPATH, and the installation- dependent default. PYTHONPATH is an environment variable, consisting of a list of directories. The syntax of PYTHONPATH is the same as that of the shell variable PATH. /software/local/lib64/python2.7/site-packages

Introduction to language - modules Frequently used modules sys Information about Python itself (path, etc.) os Operating system functions os.path Portable pathname tools shutil Utilities for copying files and directory trees cmp Utilities for comparing files and directories glob Finds files matching wildcard pattern re Regular expression string matching time Time and date handling datetime Fast implementation of date and time handling doctest, unittest Modules that facilitate unit test

Introduction to language - modules More frequently used modules pdb Debugger hotshot Code profiling pickle, cpickle, marshal, shelve Used to save objects and code to files getopt, optparse Utilities to handle shell-level argument parsing math, cmath Math functions (real and complex) faster for scalars random Random generators (likewise) gzip read and write gzipped files struct Functions to pack and unpack binary data structures StringIO, cStringIO String-like objects that can be read and written as files (e.g., in-memory files) types Names for all the standard Python type

Introduction to language - modules Modules are searched for in the following places: the current working directory (for interactive sessions) the directory of the top-level script file (for script files) the directories defined in PYTHONPATH Standard library directories >>> # Get the complete module search path: >>> import sys >>> print sys.path

Introduction to language - modules Modules can contain any code Classes, functions, definitions, immediately executed code Can be imported in own namespace, or into the global namespace >>> import math >>> math.cos(math.pi) >>> math.cos(pi) Traceback (most recent call last): File " ", line 1, in NameError: name 'pi' is not defined >>> from math import cos, pi >>> cos(pi) >>> from math import *

Introduction to language - modules Use from...import and import...as with care. Both make your code harder to understand. Do not sacrifice code clearness for some keystrokes! In some cases, the use is acceptable: –In interactive work ( import math as m ) –If things are absolutely clear (e.g. all functions of an imported module obey a clear naming convention; cfits_xyz) import.. as : As last resort in case of name clashes between module names >>> from math import sin >>> print sin(1.0) >>> print cos(1.0) # won’t work >>> from math import * >>> # All attributes copied to global namespace Extremely dangerous >>> print tan(1.0)

Introduction to language - modules >>> import numpy >>> dir(numpy) ['ALLOW_THREADS', 'BUFSIZE', 'CLIP', 'ComplexWarning', 'DataSource', 'ERR_CALL', 'ERR_DEFAULT', 'ERR_DEFAULT2', 'ERR_IGNORE', 'ERR_LOG', 'ERR_PRINT', 'ERR_RAISE', 'ERR_WARN', 'FLOATING_POINT_SUPPORT', 'FPE_DIVIDEBYZERO', 'FPE_INVALID', 'FPE_OVERFLOW', 'FPE_UNDERFLOW', 'False_', 'Inf', 'Infinity', 'MAXDIMS', 'MachAr', 'NAN', 'NINF', 'NZERO', 'NaN', 'PINF', 'PZERO', 'PackageLoader', 'RAISE', 'RankWarning', 'SHIFT_DIVIDEBYZERO', 'SHIFT_INVALID', 'SHIFT_OVERFLOW', 'SHIFT_UNDERFLOW', 'ScalarType', 'Tester', 'True_', 'UFUNC_BUFSIZE_DEFAULT', 'UFUNC_PYVALS_NAME', 'WRAP', '__NUMPY_SETUP__', '__all__', '__builtins__', '__config__', '__doc__', '__file__', '__git_revision__', '__name__', '__package__', '__path__', '__version__', '_import_tools', '_mat', 'abs', 'absolute', 'add', 'add_docstring', 'add_newdoc', 'add_newdocs', 'alen', 'all', 'allclose', 'alltrue', 'alterdot', 'amax', 'amin', 'angle', 'any', 'append', 'apply_along_axis',... 'typeNA', 'typecodes', 'typename', 'ubyte', 'ufunc', 'uint', 'uint0', 'uint16', 'uint32', 'uint64', 'uint8', 'uintc', 'uintp', 'ulonglong', 'unicode', 'unicode0', 'unicode_', 'union1d', 'unique', 'unpackbits', 'unravel_index', 'unsignedinteger', 'unwrap', 'ushort', 'vander', 'var', 'vdot', 'vectorize', 'version', 'void', 'void0', 'vsplit', 'vstack', 'where', 'who', 'zeros', 'zeros_like'] Inspecting module methods

Introduction to language - modules >>> import numpy >>> numpy.random # Submodule >>> numpy.random.randn() # Function in submodule (Restart Python) >>> import numpy.random # Import submodule only >>> numpy.random.randn() (Restart Python) >>> from numpy import random # Alternative form >>> random.randn() (Restart Python) >>> from numpy.random import * # Previous warnings >>> randn() # apply here as well! Importing submodules

Your own package myMath/ __init__.py adv/ __init__.py sqrt.py add.py subtract.py multiply.py divide.py # outer __init__.py from add import add from divide import division from multiply import multiply from subtract import subtract from adv.sqrt import squareroot import mymath print mymath.add(4,5) print mymath.division(4, 2) print mymath.multiply(10, 5) print mymath.squareroot(48)) # add.py def add(x, y): """""" return x + y The main difference between a module and a package is that a package is a collection of modules AND it has an __init__.py file. # sqrt.py import math def squareroot(n): """""" return math.sqrt(n)

Introduction to language End