Laziness, trampolines, monoids and other functional amenities: this is not yo...Codemotion
by Mario Fusco - Lambdas are the main feature introduced with Java 8, but the biggest part of Java developers are still not very familliar with the most common functional idioms and patterns. The purpose of this talk is presenting with practical examples concepts like high-order functions, currying, functions composition, persistent data structures, lazy evaluation, recursion, trampolines and monoids showing how to implement them in Java and how thinking functionally can help us to design and develop more readable, reusable, performant, parallelizable and in a word better, code.
Gentle Introduction to Functional ProgrammingSaurabh Singh
This slide is basically aimed at professionals and students to introduce them with functional programming.
I haven't used much functional programming terminologies because I personally feel they could be overwhelming to people getting introduced to FP for the first time. For similar reasons I have deliberately avoided using any functional programming language and kept the discussions programming language agnostic as far as possible.
WHAT IS FUNCTION? WHY WE NEED FUNCTION.
TYPES OF FUNCTIONS
BUILT IN FUNCTIONS
int() , str(), float(), eval(), abs(),pow(), type() , round(),
modules in python,
Mat modules
pi, ceil(),pow(),floor(),sqrt(), sin(), cos() , tan()
Abstracting over Execution with Higher Kinded TypesPhilip Schwarz
(download for better quality) Abstracting over Execution with Higher Kinded Types, and how to remain Purely Functional, a study aid for the introductory chapter of the book "Functional Programming for Mortals with Scalaz" by Sam Halliday, supplemented with code from https://github.com/fommil/fpmortals
Errata Corrige:
From https://twitter.com/philderome: you are missing a Future in slide 8 for doAndThen of ExecutionFuture (right hand side of slide), parameter c: A should read as c: Future[A]
Laziness, trampolines, monoids and other functional amenities: this is not yo...Codemotion
by Mario Fusco - Lambdas are the main feature introduced with Java 8, but the biggest part of Java developers are still not very familliar with the most common functional idioms and patterns. The purpose of this talk is presenting with practical examples concepts like high-order functions, currying, functions composition, persistent data structures, lazy evaluation, recursion, trampolines and monoids showing how to implement them in Java and how thinking functionally can help us to design and develop more readable, reusable, performant, parallelizable and in a word better, code.
Gentle Introduction to Functional ProgrammingSaurabh Singh
This slide is basically aimed at professionals and students to introduce them with functional programming.
I haven't used much functional programming terminologies because I personally feel they could be overwhelming to people getting introduced to FP for the first time. For similar reasons I have deliberately avoided using any functional programming language and kept the discussions programming language agnostic as far as possible.
WHAT IS FUNCTION? WHY WE NEED FUNCTION.
TYPES OF FUNCTIONS
BUILT IN FUNCTIONS
int() , str(), float(), eval(), abs(),pow(), type() , round(),
modules in python,
Mat modules
pi, ceil(),pow(),floor(),sqrt(), sin(), cos() , tan()
Abstracting over Execution with Higher Kinded TypesPhilip Schwarz
(download for better quality) Abstracting over Execution with Higher Kinded Types, and how to remain Purely Functional, a study aid for the introductory chapter of the book "Functional Programming for Mortals with Scalaz" by Sam Halliday, supplemented with code from https://github.com/fommil/fpmortals
Errata Corrige:
From https://twitter.com/philderome: you are missing a Future in slide 8 for doAndThen of ExecutionFuture (right hand side of slide), parameter c: A should read as c: Future[A]
Programming Fundamentals Arrays and Strings imtiazalijoono
Programming Fundamentals
Arrays and Strings
• Arrays
• Initializing arrays
• Multidimensional arrays
• Arrays as arguments to functions
• Strings
• String functions
Accessing Individual Components
Declaring Arrays
Arrays: Example Garbage
Multidimensional Arrays
1) Write a C program using arrays that produces the multiplication of two 2x2 matrices.
3-Dimensional Array
Write a program of your own choice that makes use of arrays of more than 2 dimensions.
2-Dimensional Arrays
Slides for my Talk at PyConDE/PyData Berlin 2019 https://de.pycon.org/program/pydata-rrlryg-a-bayesian-workflow-with-pymc-and-arviz-corrie-bartelheimer/
Resources:
Richard McElreath "Statistical Rethinking": https://xcelab.net/rm/statistical-rethinking/
Statistical Rethinking Port to PyMC3: https://github.com/pymc-devs/resources/tree/master/Rethinking
Prior Recommendation by Stan Team: https://github.com/stan-dev/stan/wiki/Prior-Choice-Recommendations
Michael Betancourt Case Studies: https://betanalpha.github.io/writing/
Berlin Bayesian Meetup Group: https://www.meetup.com/de-DE/BerlinBayesians/
Code and Notebook:
https://github.com/corriebar/Bayesian-Workflow-with-PyMC
An introduction to functional programming with goEleanor McHugh
A crash course in functional programming concepts using Go. Heavy on code, light on theory.
You can find the examples at https://github.com/feyeleanor/intro_to_fp_in_go
Java Programming is the most desirable IT training courses in Nepal which is known for reliability, maintainability, and ease of development. Our Java training course comprises a practical method of learning in order to provide a real-time experience. This Java Training course will not only include all the fundamental concepts but also the advanced concepts like Method Overloading & Overriding, Inheritance, Interface, Database connectivity, etc.
I am Ben R. I am a Statistics Assignment Expert at statisticshomeworkhelper.com. I hold a Ph.D. in Statistics, from University of Denver, USA. I have been helping students with their homework for the past 5 years. I solve assignments related to Statistics.
Visit statisticshomeworkhelper.com or email info@statisticshomeworkhelper.com.
You can also call on +1 678 648 4277 for any assistance with Statistics Assignments.
Moore's Law may be dead, but CPUs acquire more cores every year. If you want to minimize response latency in your application, you need to use every last core - without wasting resources that would destroy performance and throughput. Traditional locks grind threads to a halt and are prone to deadlocks, and although actors provide a saner alternative, they compose poorly and are at best weakly-typed.
In this presentation, created exclusively for Scalar Conf, John reveals a new alternative to the horrors of traditional concurrency, directly comparing it to other leading approaches in Scala. Witness the beauty, simplicity, and power of declarative concurrency, as you discover how functional programming is the most practical solution to solving the tough challenges of concurrency.
Programming Fundamentals Arrays and Strings imtiazalijoono
Programming Fundamentals
Arrays and Strings
• Arrays
• Initializing arrays
• Multidimensional arrays
• Arrays as arguments to functions
• Strings
• String functions
Accessing Individual Components
Declaring Arrays
Arrays: Example Garbage
Multidimensional Arrays
1) Write a C program using arrays that produces the multiplication of two 2x2 matrices.
3-Dimensional Array
Write a program of your own choice that makes use of arrays of more than 2 dimensions.
2-Dimensional Arrays
Slides for my Talk at PyConDE/PyData Berlin 2019 https://de.pycon.org/program/pydata-rrlryg-a-bayesian-workflow-with-pymc-and-arviz-corrie-bartelheimer/
Resources:
Richard McElreath "Statistical Rethinking": https://xcelab.net/rm/statistical-rethinking/
Statistical Rethinking Port to PyMC3: https://github.com/pymc-devs/resources/tree/master/Rethinking
Prior Recommendation by Stan Team: https://github.com/stan-dev/stan/wiki/Prior-Choice-Recommendations
Michael Betancourt Case Studies: https://betanalpha.github.io/writing/
Berlin Bayesian Meetup Group: https://www.meetup.com/de-DE/BerlinBayesians/
Code and Notebook:
https://github.com/corriebar/Bayesian-Workflow-with-PyMC
An introduction to functional programming with goEleanor McHugh
A crash course in functional programming concepts using Go. Heavy on code, light on theory.
You can find the examples at https://github.com/feyeleanor/intro_to_fp_in_go
Java Programming is the most desirable IT training courses in Nepal which is known for reliability, maintainability, and ease of development. Our Java training course comprises a practical method of learning in order to provide a real-time experience. This Java Training course will not only include all the fundamental concepts but also the advanced concepts like Method Overloading & Overriding, Inheritance, Interface, Database connectivity, etc.
I am Ben R. I am a Statistics Assignment Expert at statisticshomeworkhelper.com. I hold a Ph.D. in Statistics, from University of Denver, USA. I have been helping students with their homework for the past 5 years. I solve assignments related to Statistics.
Visit statisticshomeworkhelper.com or email info@statisticshomeworkhelper.com.
You can also call on +1 678 648 4277 for any assistance with Statistics Assignments.
Moore's Law may be dead, but CPUs acquire more cores every year. If you want to minimize response latency in your application, you need to use every last core - without wasting resources that would destroy performance and throughput. Traditional locks grind threads to a halt and are prone to deadlocks, and although actors provide a saner alternative, they compose poorly and are at best weakly-typed.
In this presentation, created exclusively for Scalar Conf, John reveals a new alternative to the horrors of traditional concurrency, directly comparing it to other leading approaches in Scala. Witness the beauty, simplicity, and power of declarative concurrency, as you discover how functional programming is the most practical solution to solving the tough challenges of concurrency.
C program to find factorial of number using recursion as well as iteration ,
Calculate power of a number program in c using Recursion and Iteration, Write a C program to count digits of a number using Recursion and Iteration, Write a C program to find sum of first n natural numbers using Recursion, C program to print sum of digits of a given number using recursion ,Write a C program to find nth term in Fibonacci Series using Recursion, C program to find out the GCD (Greatest Common Divisor )of the two numbers using recursion,
Write a C program to find the first upper case letter in the given string using recursion, write C program to calculate length of the string using Recursion ,
Write a program in C to count number of divisors of a given number using recursion, Recursive program to check whether a given number is prime or composite,
C program to displays integers 100 through 1 using Recursion and Iteration, Write a program in C to convert a decimal number to binary using recursion,
Recursion Stack of factorial of 3 Recursion stack of 4th term of Fibonacci
Developer Experience i TypeScript. Najbardziej ikoniczne duoThe Software House
Wiktor Toporek: TypeScript bez wątpienia jest obecnie pewnym standardem wśród obecnych rozwiązań powstałych w JavaScripcie. Ale czy poza byciem dodatkiem który uzupełnia odrobinę dokumentacje i deklaruje kontrakt jakiego typu parametry przyjmują i zwracają np. funkcje jakiejś biblioteki, można wycisnąć z niego coś więcej? Podczas prezentacji wykorzystamy TypeScript do granic możliwości, używając zaawansowanych technik które sprawiają że interfejs naszego API będzie sam kierował używających go developerów na drogę poprawnego użycia, które jest zgodne z naszymi (twórców) założeniami, poprawiając tym samym ich doświadczenia.
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...Levi Shapiro
Letter from the Congress of the United States regarding Anti-Semitism sent June 3rd to MIT President Sally Kornbluth, MIT Corp Chair, Mark Gorenberg
Dear Dr. Kornbluth and Mr. Gorenberg,
The US House of Representatives is deeply concerned by ongoing and pervasive acts of antisemitic
harassment and intimidation at the Massachusetts Institute of Technology (MIT). Failing to act decisively to ensure a safe learning environment for all students would be a grave dereliction of your responsibilities as President of MIT and Chair of the MIT Corporation.
This Congress will not stand idly by and allow an environment hostile to Jewish students to persist. The House believes that your institution is in violation of Title VI of the Civil Rights Act, and the inability or
unwillingness to rectify this violation through action requires accountability.
Postsecondary education is a unique opportunity for students to learn and have their ideas and beliefs challenged. However, universities receiving hundreds of millions of federal funds annually have denied
students that opportunity and have been hijacked to become venues for the promotion of terrorism, antisemitic harassment and intimidation, unlawful encampments, and in some cases, assaults and riots.
The House of Representatives will not countenance the use of federal funds to indoctrinate students into hateful, antisemitic, anti-American supporters of terrorism. Investigations into campus antisemitism by the Committee on Education and the Workforce and the Committee on Ways and Means have been expanded into a Congress-wide probe across all relevant jurisdictions to address this national crisis. The undersigned Committees will conduct oversight into the use of federal funds at MIT and its learning environment under authorities granted to each Committee.
• The Committee on Education and the Workforce has been investigating your institution since December 7, 2023. The Committee has broad jurisdiction over postsecondary education, including its compliance with Title VI of the Civil Rights Act, campus safety concerns over disruptions to the learning environment, and the awarding of federal student aid under the Higher Education Act.
• The Committee on Oversight and Accountability is investigating the sources of funding and other support flowing to groups espousing pro-Hamas propaganda and engaged in antisemitic harassment and intimidation of students. The Committee on Oversight and Accountability is the principal oversight committee of the US House of Representatives and has broad authority to investigate “any matter” at “any time” under House Rule X.
• The Committee on Ways and Means has been investigating several universities since November 15, 2023, when the Committee held a hearing entitled From Ivory Towers to Dark Corners: Investigating the Nexus Between Antisemitism, Tax-Exempt Universities, and Terror Financing. The Committee followed the hearing with letters to those institutions on January 10, 202
MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...NelTorrente
In this research, it concludes that while the readiness of teachers in Caloocan City to implement the MATATAG Curriculum is generally positive, targeted efforts in professional development, resource distribution, support networks, and comprehensive preparation can address the existing gaps and ensure successful curriculum implementation.
This presentation includes basic of PCOS their pathology and treatment and also Ayurveda correlation of PCOS and Ayurvedic line of treatment mentioned in classics.
Biological screening of herbal drugs: Introduction and Need for
Phyto-Pharmacological Screening, New Strategies for evaluating
Natural Products, In vitro evaluation techniques for Antioxidants, Antimicrobial and Anticancer drugs. In vivo evaluation techniques
for Anti-inflammatory, Antiulcer, Anticancer, Wound healing, Antidiabetic, Hepatoprotective, Cardio protective, Diuretics and
Antifertility, Toxicity studies as per OECD guidelines
How to Build a Module in Odoo 17 Using the Scaffold MethodCeline George
Odoo provides an option for creating a module by using a single line command. By using this command the user can make a whole structure of a module. It is very easy for a beginner to make a module. There is no need to make each file manually. This slide will show how to create a module using the scaffold method.
Thinking of getting a dog? Be aware that breeds like Pit Bulls, Rottweilers, and German Shepherds can be loyal and dangerous. Proper training and socialization are crucial to preventing aggressive behaviors. Ensure safety by understanding their needs and always supervising interactions. Stay safe, and enjoy your furry friends!
Safalta Digital marketing institute in Noida, provide complete applications that encompass a huge range of virtual advertising and marketing additives, which includes search engine optimization, virtual communication advertising, pay-per-click on marketing, content material advertising, internet analytics, and greater. These university courses are designed for students who possess a comprehensive understanding of virtual marketing strategies and attributes.Safalta Digital Marketing Institute in Noida is a first choice for young individuals or students who are looking to start their careers in the field of digital advertising. The institute gives specialized courses designed and certification.
for beginners, providing thorough training in areas such as SEO, digital communication marketing, and PPC training in Noida. After finishing the program, students receive the certifications recognised by top different universitie, setting a strong foundation for a successful career in digital marketing.
A review of the growth of the Israel Genealogy Research Association Database Collection for the last 12 months. Our collection is now passed the 3 million mark and still growing. See which archives have contributed the most. See the different types of records we have, and which years have had records added. You can also see what we have for the future.
2. 2
Find the sum of integers from 1 to 10, from 20 to 37, and
from 35 to 49, respectively.
ARULKUMAR V AP/CSE SECE
3. 3
sum = 0
for i in range(1, 10):
sum += i
print("Sum from 1 to 10 is", sum)
sum = 0
for i in range(20, 37):
sum += i
print("Sum from 20 to 37 is", sum)
sum = 0
for i in range(35, 49):
sum += i
print("Sum from 35 to 49 is", sum)
ARULKUMAR V AP/CSE SECE
4. 4
sum = 0
for i in range(1, 10):
sum += i
print("Sum from 1 to 10 is", sum)
sum = 0
for i in range(20, 37):
sum += i
print("Sum from 20 to 37 is", sum)
sum = 0
for i in range(35, 49):
sum += i
print("Sum from 35 to 49 is", sum)
ARULKUMAR V AP/CSE SECE
5. 5
def sum(i1, i2):
result = 0
for i in range(i1, i2):
result += i
return result
def main():
print("Sum from 1 to 10 is", sum(1, 10))
print("Sum from 20 to 37 is", sum(20, 37))
print("Sum from 35 to 49 is", sum(35, 49))
main() # Call the main function
ARULKUMAR V AP/CSE SECE
6. To define functions (§6.2).
To invoke value-returning functions (§6.3).
To invoke functions that does not return a value (§6.4).
To pass arguments by values (§6.5).
To pass arguments by values (§6.6).
To develop reusable code that is modular, easy to read,
easy to debug, and easy to maintain (§6.7).
To create modules for reusing functions (§§6.7-6.8).
To determine the scope of variables (§6.9).
To define functions with default arguments (§6.10).
To return multiple values from a function (§6.11).
To apply the concept of function abstraction in
software development (§6.12).
To design and implement functions using stepwise
refinement (§6.13).
To simplify drawing programs using functions (§6.14).
6ARULKUMAR V AP/CSE SECE
7. 7
A function is a collection of statements that are
grouped together to perform an operation.
def max(num1, num2):
if num1 > num2:
result = num1
else:
result = num2
return result
function name formal parameters
return value
function
body
function
header
Define a function Invoke a function
z = max(x, y)
actual parameters
(arguments)
ARULKUMAR V AP/CSE SECE
8. def max(num1, num2):
if num1 > num2:
result = num1
else:
result = num2
return result
function name formal parameters
return value
function
body
function
header
Define a function Invoke a function
z = max(x, y)
actual parameters
(arguments)
8
A function contains a header and body. The header begins with the
def keyword, followed by function’s name and parameters,
followed by a colon.
ARULKUMAR V AP/CSE SECE
9. def max(num1, num2):
if num1 > num2:
result = num1
else:
result = num2
return result
function name formal parameters
return value
function
body
function
header
Define a function Invoke a function
z = max(x, y)
actual parameters
(arguments)
9
The variables defined in the function header are known as
formal parameters.
ARULKUMAR V AP/CSE SECE
10. def max(num1, num2):
if num1 > num2:
result = num1
else:
result = num2
return result
function name formal parameters
return value
function
body
function
header
Define a function Invoke a function
z = max(x, y)
actual parameters
(arguments)
10
When a function is invoked, you pass a value to the parameter. This
value is referred to as actual parameter or argument.
ARULKUMAR V AP/CSE SECE
11. def max(num1, num2):
if num1 > num2:
result = num1
else:
result = num2
return result
function name formal parameters
return value
function
body
function
header
Define a function Invoke a function
z = max(x, y)
actual parameters
(arguments)
11
A function may return a value using the return keyword.
ARULKUMAR V AP/CSE SECE
12. 12
Testing the max function
This program demonstrates calling a function
max to return the largest of the int values
TestMax Run
ARULKUMAR V AP/CSE SECE
13. 13
animation
def main():
i = 5
j = 2
k = max(i, j)
print("The maximum between",
i, "and", j, "is", k)
def max(num1, num2):
if num1 > num2:
result = num1
else:
result = num2
return result
pass int 5
pass int 2
main()
ARULKUMAR V AP/CSE SECE
14. def main():
i = 5
j = 2
k = max(i, j)
print("The maximum between",
i, "and", j, "is", k)
def max(num1, num2):
if num1 > num2:
result = num1
else:
result = num2
return result
pass int 5
pass int 2
main()
14
animation
Invoke the main function
ARULKUMAR V AP/CSE SECE
15. def main():
i = 5
j = 2
k = max(i, j)
print("The maximum between",
i, "and", j, "is", k)
def max(num1, num2):
if num1 > num2:
result = num1
else:
result = num2
return result
pass int 5
pass int 2
main()
15
animation
i is now 5
ARULKUMAR V AP/CSE SECE
16. def main():
i = 5
j = 2
k = max(i, j)
print("The maximum between",
i, "and", j, "is", k)
def max(num1, num2):
if num1 > num2:
result = num1
else:
result = num2
return result
pass int 5
pass int 2
main()
16
animation
j is now 2
ARULKUMAR V AP/CSE SECE
17. def main():
i = 5
j = 2
k = max(i, j)
print("The maximum between",
i, "and", j, "is", k)
def max(num1, num2):
if num1 > num2:
result = num1
else:
result = num2
return result
pass int 5
pass int 2
main()
17
animation
invoke max(i, j)
ARULKUMAR V AP/CSE SECE
18. def main():
i = 5
j = 2
k = max(i, j)
print("The maximum between",
i, "and", j, "is", k)
def max(num1, num2):
if num1 > num2:
result = num1
else:
result = num2
return result
pass int 5
pass int 2
main()
18
animation
invoke max(i, j)
Pass the value of i to num1
Pass the value of j to num2
ARULKUMAR V AP/CSE SECE
19. def main():
i = 5
j = 2
k = max(i, j)
print("The maximum between",
i, "and", j, "is", k)
def max(num1, num2):
if num1 > num2:
result = num1
else:
result = num2
return result
pass int 5
pass int 2
main()
19
animation
(num1 > num2) is true
since num1 is 5 and num2
is 2
ARULKUMAR V AP/CSE SECE
20. def main():
i = 5
j = 2
k = max(i, j)
print("The maximum between",
i, "and", j, "is", k)
def max(num1, num2):
if num1 > num2:
result = num1
else:
result = num2
return result
pass int 5
pass int 2
main()
20
animation
result is now 5
ARULKUMAR V AP/CSE SECE
21. def main():
i = 5
j = 2
k = max(i, j)
print("The maximum between",
i, "and", j, "is", k)
def max(num1, num2):
if num1 > num2:
result = num1
else:
result = num2
return result
pass int 5
pass int 2
main()
21
animation
return result, which is 5
ARULKUMAR V AP/CSE SECE
22. def main():
i = 5
j = 2
k = max(i, j)
print("The maximum between",
i, "and", j, "is", k)
def max(num1, num2):
if num1 > num2:
result = num1
else:
result = num2
return result
pass int 5
pass int 2
main()
22
animation
return max(i, j) and assign
the return value to k
ARULKUMAR V AP/CSE SECE
23. def main():
i = 5
j = 2
k = max(i, j)
print("The maximum between",
i, "and", j, "is", k)
def max(num1, num2):
if num1 > num2:
result = num1
else:
result = num2
return result
pass int 5
pass int 2
main()
23
animation
Execute the print
statement
ARULKUMAR V AP/CSE SECE
24. def main():
i = 5
j = 2
k = max(i, j)
print("The maximum between",
i, "and", j, "is", k)
def max(num1, num2):
if num1 > num2:
result = num1
else:
result = num2
return result
pass int 5
pass int 2
main()
24
animation
Return to the caller
ARULKUMAR V AP/CSE SECE
25. 25
(a) The main function
is invoked.
Space required for
the main function
j: 2
i: 5
(b) The max
function is invoked.
(c) The max function
is being executed.
Space required for
the main function
j:
i:
Space required for
the max function
num2:
num1:
int object
5
int object
2
This is a heap for
storing objects
stack stack
int object
5
int object
2
This is a heap for
storing objects
Space required for
the main function
j:
i:
Space required for
the max function
result:
num2:
num1:
stack
ARULKUMAR V AP/CSE SECE
26. 26
Space required for
the main function
k:
j: 2
i: 5
(e) The main
function is finished.
int object
5
int object
2
This is a heap for
storing objects
stack stack
(d) The max function is
finished and the return
value is sent to k.
Stack is
now empty
ARULKUMAR V AP/CSE SECE
27. 27
This type of function does not return a value. The
function performs some actions.
ReturnGradeFunction Run
PrintGradeFunction Run
ARULKUMAR V AP/CSE SECE
28. 28
A function that does not return a value is known as
a void function in other programming languages
such as Python, C++, and C#. In Python, such
function returns a special None.
def sum(number1, number2):
total = number1 + number2
print(sum(1, 2))
ARULKUMAR V AP/CSE SECE
29. def nPrintln(message, n):
for i in range(0, n):
print(message)
29
Suppose you invoke the function using
nPrintln(“Welcome to Python”, 5)
What is the output?
Suppose you invoke the function using
nPrintln(“Computer Science”, 15)
What is the output?
What is wrong
nPrintln(4, “Computer Science”)
ARULKUMAR V AP/CSE SECE
30. def nPrintln(message, n):
for i in range(0, n):
print(message)
30
What is wrong
nPrintln(4, “Computer Science”)
Is this OK?
nPrintln(n = 4, message = “Computer Science”)
ARULKUMAR V AP/CSE SECE
31. 31
In Python, all data are objects. A variable for an object is actually a
reference to the object. When you invoke a function with a
parameter, the reference value of the argument is passed to the
parameter. This is referred to as pass-by-value. For simplicity, we
say that the value of an argument is passed to a parameter when
invoking a function. Precisely, the value is actually a reference value
to the object.
Increment Run
If the argument is a number or a string, the argument is not affected,
regardless of the changes made to the parameter inside the function.
ARULKUMAR V AP/CSE SECE
32. Functions can be used to reduce redundant coding
and enable code reuse. Functions can also be used
to modularize code and improve the quality of the
program.
32
GCDFunction
Run
PrimeNumberFunction
Run
TestGCDFunction
ARULKUMAR V AP/CSE SECE
33. 33
Write a function that converts a decimal integer
to a hexadecimal.
Decimal2HexConversion RunDecimal2HexConversion Run
ARULKUMAR V AP/CSE SECE
34. Scope: the part of the program
where the variable can be
referenced.
34
A variable created inside a function is referred to as a
local variable. Local variables can only be
accessed inside a function. The scope of a local
variable starts from its creation and continues to
the end of the function that contains the variable.
In Python, you can also use global variables. They
are created outside all functions and are accessible
to all functions in their scope.
ARULKUMAR V AP/CSE SECE
35. globalVar = 1
def f1():
localVar = 2
print(globalVar)
print(localVar)
f1()
print(globalVar)
print(localVar) # Out of scope. This gives an error
35ARULKUMAR V AP/CSE SECE
36. x = 1
def f1():
x = 2
print(x) # Displays 2
f1()
print(x) # Displays 1
36ARULKUMAR V AP/CSE SECE
37. x = eval(input("Enter a number: "))
if (x > 0):
y = 4
print(y) # This gives an error if y is not created
37ARULKUMAR V AP/CSE SECE
38. sum = 0
for i in range(0, 5):
sum += i
print(i)
38ARULKUMAR V AP/CSE SECE
39. x = 1
def increase():
global x
x = x + 1
print(x) # Displays 2
increase()
print(x) # Displays 2
39ARULKUMAR V AP/CSE SECE
40. Python allows you to define functions with
default argument values. The default values are
passed to the parameters when a function is
invoked without the arguments.
40
DefaultArgumentDemo Run
ARULKUMAR V AP/CSE SECE
41. Python allows a function to return multiple
values. Listing 5.9 defines a function that takes
two numbers and returns them in non-
descending order.
41
MultipleReturnValueDemo
Run
ARULKUMAR V AP/CSE SECE
43. You can think of the function body as a black box
that contains the detailed implementation for the
function.
43
Function Header
Function Body
Black Box
Optional arguments
for input
Optional return
value
ARULKUMAR V AP/CSE SECE
44. 44
• Write a function once and reuse it anywhere.
• Information hiding. Hide the implementation
from the user.
• Reduce complexity.
ARULKUMAR V AP/CSE SECE
45. The concept of function abstraction can be
applied to the process of developing programs.
When writing a large program, you can use the
“divide and conquer” strategy, also known as
stepwise refinement, to decompose it into
subproblems. The subproblems can be further
decomposed into smaller, more manageable
problems.
45ARULKUMAR V AP/CSE SECE
46. Let us use the PrintCalendar example to
demonstrate the stepwise refinement
approach.
46
PrintCalendar Run
ARULKUMAR V AP/CSE SECE
53. 53
A Skeleton for printCalendar
Top-down approach is to implement one function in the
structure chart at a time from the top to the bottom. Stubs
can be used for the functions waiting to be implemented.
A stub is a simple but incomplete version of a function.
The use of stubs enables you to test invoking the function
from a caller. Implement the main function first and then
use a stub for the printMonth function. For example, let
printMonth display the year and the month in the stub.
Thus, your program may begin like this:
ARULKUMAR V AP/CSE SECE
54. 54
Bottom-up approach is to implement one function in the
structure chart at a time from the bottom to the top. For
each function implemented, write a test program to test it.
Both top-down and bottom-up functions are fine. Both
approaches implement the functions incrementally and
help to isolate programming errors and makes debugging
easy. Sometimes, they can be used together.
ARULKUMAR V AP/CSE SECE