Python Functions Part I Presented by : Sharmin Abdullah

Slides:



Advertisements
Similar presentations
Etter/Ingber Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions.
Advertisements

Introduction to Python
Genome Sciences 373 Genome Informatics Quiz Section 5 April 28, 2015.
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 Programming Fundamentals
C Functions Programmer-defined functions – Functions written by the programmer to define specific tasks. Functions are invoked by a function call. The.
Guide to Programming with Python Chapter Six Functions: The Tic-Tac-Toe Game.
Course A201: Introduction to Programming 11/04/2010.
Scheme & Functional Programming. ( ) >> 64 ( ) >> 666 (* ) >> 1200 (+ (* 3 5) (- 10 6)) >> 19.
CS 177 Week 4 Recitation Slides Variables, Files and Functions.
Chapter Function Basics CSC1310 Fall Function function (subroutine, procedure)a set of statements different inputs (parameters) outputs In.
Chapter 8 More On Functions. "The Practice of Computing Using Python", Punch & Enbody, Copyright © 2013 Pearson Education, Inc. First cut, scope.
Introducing Python CS 4320, SPRING Resources We will be following the Python tutorialPython tutorial These notes will cover the following sections.
Python Functions.
Introduction to Computing Using Python for loop / def- ining a new function  Execution control structures ( if, for, function call)  def -ining a new.
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.
1 Computer Science of Graphics and Games MONT 105S, Spring 2009 Lecture 17 Parameters, Scope, Return values.
Procedural Programming Criteria: P2 Task: 1.2 Thomas Jazwinski.
Passing Arguments, Local/Global Variables Writing Functions( ) (Part 2)
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.
INLS 560 – F UNCTIONS Instructor: Jason Carter.
More Python!. Lists, Variables with more than one value Variables can point to more than one value at a time. The simplest way to do this is with a List.
Function Basics. Function In this chapter, we will move on to explore a set of additional statements that create functions of our own function (subroutine,
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.
Introduction to Programming Oliver Hawkins. BACKGROUND TO PROGRAMMING LANGUAGES Introduction to Programming.
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
Lecture IV Functions & Scope ● Defining Functions ● Returning ● Parameters ● Docstrings ● Functions as Objects ● Scope ● Dealing with Globals ● Nesting.
Lecture III Syntax ● Statements ● Output ● Variables ● Conditions ● Loops ● List Comprehension ● Function Calls ● Modules.
Data Type and Function Prepared for CSB210 Pemrograman Berorientasi Objek By Indriani Noor Hapsari, ST, MT Source: study.
Chapter 7 User-Defined Methods.
Chapter 7: User-Defined Functions II
Lecture 2 Python Basics.
COMPSCI 107 Computer Science Fundamentals
Chapter 2 - Introduction to C Programming
Topic: Functions – Part 2
Variables, Expressions, and IO
Chapter 2 - Introduction to C Programming
User-Defined Functions
CHAPTER FOUR Functions.
Chapter 2 - Introduction to C Programming
Chapter 2 - Introduction to C Programming
CISC101 Reminders Quiz 1 grading underway Assn 1 due Today, 9pm.
Chapter 2 - Introduction to C Programming
CMSC201 Computer Science I for Majors Lecture 14 – Functions (Continued) Prof. Katherine Gibson Based on concepts from:
CISC101 Reminders Assn 3 due tomorrow, 7pm.
3 Control Statements:.
Type & Typeclass Syntax in function
Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon
Chapter 2 - Introduction to C Programming
5. Functions Rocky K. C. Chang 30 October 2018
Topics Introduction to Functions Defining and Calling a Void Function
Computer Science 111 Fundamentals of Programming I
G. Pullaiah College of Engineering and Technology
CISC101 Reminders All assignments are now posted.
Python Basics with Jupyter Notebook
The structure of programming
Chapter 2 - Introduction to C Programming
COMPUTER PROGRAMMING SKILLS
What is a Function? Takes one or more arguments, or perhaps none at all Performs an operation Returns one or more values, or perhaps none at all Similar.
CISC101 Reminders Assignment 3 due today.
Rules of evaluation The value of a number is itself.
Introduction to C Programming
def-ining a function A function as an execution control structure
 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.
Python Basics. Topics Features How does Python work Basic Features I/O in Python Operators Control Statements Function/Scope of variables OOP Concepts.
Functions John R. Woodward.
© Sangeeta M Chauhan, Gwalior
Presentation transcript:

Python Functions Part I Presented by : Sharmin Abdullah 1 Presented by : Sharmin Abdullah October 15th, 2018

What is function in Python? A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function. A function can return data as a result. Creating a function: Python uses def keyword to start a function: def greet(): print("Hello Everyone! Welcome to Python Learning!") Calling a function: Output greet() Hello Everyone! Welcome to Python Learning!

Creating and Calling functions Syntax of creating a function: Syntax of calling a function: def function_name(parameters): """docstring""" statement(s) function_name(input values) Docstring is the text that comes up when you type in help followed by the function name in the interpreter Example def bitcoin_to_usd(btc): ''' This function converts the bitcoin value to USD''' amount = btc*6000 print('Today', btc,'bitcoin is equivalent to $',amount) bitcoin_to_usd(1) help(bitcoin_to_usd)

The return statement The return statement is used to exit a function and go back to the place from where it was called. def absolute_value(num): if num >= 0: return num else: return -num print(absolute_value(2)) print(absolute_value(-4)) A function without any return statement in it will return the “None” object.

Scope and lifetime of variables Scope of a variable is the portion of a program where the variable is recognized. Parameters and variables defined inside a function are not visible from outside. Hence, they have a local scope. Lifetime of a variable is the period throughout which the variable exists in the memory. The lifetime of variables inside a function is as long as the function executes. They are destroyed once we return from the function. Hence, a function does not remember the value of a variable from its previous calls. def my_func(): x = 10 print("Value inside function:",x) x = 20 my_func() print("Value outside function:",x) Value inside function: 10 Value outside function: 20

Types of Functions 1. User-defined function 2. Built-in function Functions that we define ourselves to do certain specific task are referred to as user-defined functions. Functions that readily come with Python are called built-in functions. def absolute_value(num): """This function returns the absolute value of the entered number""" if num >= 0: return num else: return -num print(absolute_value(2)) print(absolute_value(-4)) In Python 3.6 (latest version), there are 68 built-in functions. abs() print() filter() map() len() sorted()

Function Arguments Default values for Arguments: Arguments are the parameters through which we pass values to a function. Default values for Arguments: Function arguments can have default values in Python. We can provide a default value to an argument by using the assignment operator (=) def Exam_Result(result='Result not published'): if result is 'P': result = "Congratulations! You have Passed!" elif result is 'F': result = "Sorry, better luck next time!" print(result) Exam_Result('P') Exam_Result('F’) Exam_Result() Congratulations! You have Passed! Sorry, better luck next time! Result not published

Passing Arguments in Python There are two ways to pass arguments to a function:  # Positional arguments  # Keyword arguments.  def my_func(a, b, c):     print(a, b, c) my_func(12, 13, 14) my_func(10, b=13, c=14) Positional Arguments: my_func(12, 13, 14) Output: (12, 13, 14) Keyword arguments: Keyword arguments allows you to pass each argument using name value pairs: name=value. For example: b=13 Output: my_func(b=13, a=10, c=14) (10, 13, 14) Mixing Positional and Keyword Arguments: my_func(12, b=13, c=14) Output: (12, 13, 14) my_func(12, c=20, b=14) Output: ? ALWAYS KEEP IN MIND: Having a positional argument after keyword arguments will result in errors. my_func(a=12, b=20, 14) Output: SyntaxError: non-keyword arg after keyword arg

Python Arbitrary Arguments When we do not know the number of arguments that will be passed into a function in advance , we can use an asterisk (*) before the parameter name to denote this kind of argument. def greet(*names): """This function greets all the person in the names tuple.""" # names is a tuple with arguments for name in names: print("Hello ",name) greet("Monica","Luke","Steve","John") Hello Monica Hello Luke Hello Steve Hello John

Recursion Python Recursive Function Recursion is the process of defining something in terms of itself. Python Recursive Function We know that in Python, a function can call other functions. It is even possible for the function to call itself. These type of constructs are termed as recursive function. Example: Calculating the factorial of a given number. 24 calc_factorial(4) def calc_factorial(x): """This is a recursive function to find the factorial of an integer""" if x == 1: return 1 else: return (x * calc_factorial(x-1)) num = 4 print("The factorial of", num, "is", calc_factorial(num)) 4 * calc_factorial(3) 4 * 6 3 * calc_factorial(2) 3 * 2 2 * calc_factorial(1) 2 * 1

Python anonymous/lambda function A lambda function is an anonymous function that can have more than one argument but only one expression. While normal functions are defined using the def keyword, in Python anonymous functions are defined using the lambda keyword. Syntax of Lambda Function in python: lambda arguments: expression # Lambda function example double = lambda x: x * 2 print(double(5)) Output: 10 # Program to filter out only the even items from a list my_list = [1, 5, 4, 6, 8, 11, 3, 12] new_list = list(filter(lambda x: (x%2 == 0) , my_list)) print(new_list) In Python, lambda functions are often used as arguments to other functions. Output: [4, 6, 8, 12]

Quiz Time Question 1: Which of the following is/are not the built-in function? print() abs() filter() absolute_value() Question 2: If return statement is not used inside the function, the function will return: None Object An arbitrary value Error!

Question 3: What will be the output of the following function: def nam(name='sharmin',adjective='awesome'): print(name+' is '+ adjective) nam('awesome', adjective='sharmin') sharmin is awesome awesome is sharmin SyntaxError: non-keyword arg after keyword arg Question 4: What is the output of the following program? result = lambda x: x * x print(result(5)) 5 5*5 25 125

Question 5: What is the output of the following program? def Foo(x): if (x==1): return 1 else: return x+Foo(x-1) print(Foo(4)) 7 9 10 1 Question 6: What is the output of the following program? def func(*name): print('Goodbye', name) func('Class','Everyone') a. Goodbye Class Goodbye Everyone b. Goodbye ('Class', 'Everyone') c. Goodbye Class d. Goodbye Everyone

Thank You ! Any Questions?