JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docxvrickens
JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition pg. 25
An Introduction to
Computer Science with Java, Python and C++
Community College of Philadelphia edition
Copyright 2017 by C.W. Herbert, all rights reserved.
Last edited October 8, 28, 2019 by C. W. Herbert
This document is a draft of a chapter from An Introduction to Computer Science with Java, Python and C++, written by Charles Herbert. It is available free of charge for students in Computer Science courses at Community College of Philadelphia during the Fall 2019 semester. It may not be reproduced or distributed for any other purposes without proper prior permission.
Please report any typos, other errors, or suggestions for improving the text to [email protected]
Chapter 5 – Python Functions and Modular Programming
Contents
Lesson 5.1User Created Functions in Python2
Python Function Parameters2
Value returning functions3
Example – Methods and Parameter Passing5
9
Lesson 5.2Top-Down Design and Modular Development10
Chapter Exercises13
User Created Functions in Python
So far we have only created software with one continuous Python script. We have used functions from other python modules, such as the square root method from the math class math.sqrt(n). Now we will begin to create our own functions of our own.
A Python function is a block of code that can be used to perform a specific task within a larger computer program. It can be called as needed from other Python software. Most programming languages have similar features, such as methods in Java or subroutines in system software.
The code for user-defined functions in Python is contained in a function definition. A Python function definition is a software unit with a header and a block of Python statements. The header starts with the keyword def followed by the name of the function, then a set parenthesis with any parameters for the function. A colon is used after the parentheses to indicate a block of code follows, just as with the if and while statements. The block of code to be included within the function is indented.
Here is an example of a Python function:
# firstFunction.py
# first demonstration of the use of a function for CSCI 111
# last edited 10/08/2o19 by C. Herbert
function
definition
def myFunction():
print ( "This line being printed by the function MyFunction.\n")
# end myFunction()
### main program ###
function used by the main part of the script
print("Beginning\n")
myFunction()
print("End\n")
# end main program
Functions can used for code that will be repeated within a program, or for modular development, in which long programs are broken into parts and the parts are developed independently. The parts can be developed as Python functions, then integrated to work together by being called from other software.
Python Function Parameters
Data can be passed to a Python function as a parameter of the function. Function parameters are variables listed in parentheses foll ...
JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docxvrickens
JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition pg. 25
An Introduction to
Computer Science with Java, Python and C++
Community College of Philadelphia edition
Copyright 2017 by C.W. Herbert, all rights reserved.
Last edited October 8, 28, 2019 by C. W. Herbert
This document is a draft of a chapter from An Introduction to Computer Science with Java, Python and C++, written by Charles Herbert. It is available free of charge for students in Computer Science courses at Community College of Philadelphia during the Fall 2019 semester. It may not be reproduced or distributed for any other purposes without proper prior permission.
Please report any typos, other errors, or suggestions for improving the text to [email protected]
Chapter 5 – Python Functions and Modular Programming
Contents
Lesson 5.1User Created Functions in Python2
Python Function Parameters2
Value returning functions3
Example – Methods and Parameter Passing5
9
Lesson 5.2Top-Down Design and Modular Development10
Chapter Exercises13
User Created Functions in Python
So far we have only created software with one continuous Python script. We have used functions from other python modules, such as the square root method from the math class math.sqrt(n). Now we will begin to create our own functions of our own.
A Python function is a block of code that can be used to perform a specific task within a larger computer program. It can be called as needed from other Python software. Most programming languages have similar features, such as methods in Java or subroutines in system software.
The code for user-defined functions in Python is contained in a function definition. A Python function definition is a software unit with a header and a block of Python statements. The header starts with the keyword def followed by the name of the function, then a set parenthesis with any parameters for the function. A colon is used after the parentheses to indicate a block of code follows, just as with the if and while statements. The block of code to be included within the function is indented.
Here is an example of a Python function:
# firstFunction.py
# first demonstration of the use of a function for CSCI 111
# last edited 10/08/2o19 by C. Herbert
function
definition
def myFunction():
print ( "This line being printed by the function MyFunction.\n")
# end myFunction()
### main program ###
function used by the main part of the script
print("Beginning\n")
myFunction()
print("End\n")
# end main program
Functions can used for code that will be repeated within a program, or for modular development, in which long programs are broken into parts and the parts are developed independently. The parts can be developed as Python functions, then integrated to work together by being called from other software.
Python Function Parameters
Data can be passed to a Python function as a parameter of the function. Function parameters are variables listed in parentheses foll ...
I am Justin R. I am a Python Homework Expert at pythonhomeworkhelp.com. I hold a Master's in Python Programming from, Durham University, UK. I have been helping students with their homework for the past 12 years. I solve homework related to Python.
Visit pythonhomeworkhelp.com or email support@pythonhomeworkhelp.com.
You can also call on +1 678 648 4277 for any assistance with Python Homework.
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()
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Anthony Dahanne
Les Buildpacks existent depuis plus de 10 ans ! D’abord, ils étaient utilisés pour détecter et construire une application avant de la déployer sur certains PaaS. Ensuite, nous avons pu créer des images Docker (OCI) avec leur dernière génération, les Cloud Native Buildpacks (CNCF en incubation). Sont-ils une bonne alternative au Dockerfile ? Que sont les buildpacks Paketo ? Quelles communautés les soutiennent et comment ?
Venez le découvrir lors de cette session ignite
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?XfilesPro
Worried about document security while sharing them in Salesforce? Fret no more! Here are the top-notch security standards XfilesPro upholds to ensure strong security for your Salesforce documents while sharing with internal or external people.
To learn more, read the blog: https://www.xfilespro.com/how-does-xfilespro-make-document-sharing-secure-and-seamless-in-salesforce/
More Related Content
Similar to Updated Week 06 and 07 Functions In Python.pptx
I am Justin R. I am a Python Homework Expert at pythonhomeworkhelp.com. I hold a Master's in Python Programming from, Durham University, UK. I have been helping students with their homework for the past 12 years. I solve homework related to Python.
Visit pythonhomeworkhelp.com or email support@pythonhomeworkhelp.com.
You can also call on +1 678 648 4277 for any assistance with Python Homework.
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()
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Anthony Dahanne
Les Buildpacks existent depuis plus de 10 ans ! D’abord, ils étaient utilisés pour détecter et construire une application avant de la déployer sur certains PaaS. Ensuite, nous avons pu créer des images Docker (OCI) avec leur dernière génération, les Cloud Native Buildpacks (CNCF en incubation). Sont-ils une bonne alternative au Dockerfile ? Que sont les buildpacks Paketo ? Quelles communautés les soutiennent et comment ?
Venez le découvrir lors de cette session ignite
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?XfilesPro
Worried about document security while sharing them in Salesforce? Fret no more! Here are the top-notch security standards XfilesPro upholds to ensure strong security for your Salesforce documents while sharing with internal or external people.
To learn more, read the blog: https://www.xfilespro.com/how-does-xfilespro-make-document-sharing-secure-and-seamless-in-salesforce/
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Shahin Sheidaei
Games are powerful teaching tools, fostering hands-on engagement and fun. But they require careful consideration to succeed. Join me to explore factors in running and selecting games, ensuring they serve as effective teaching tools. Learn to maintain focus on learning objectives while playing, and how to measure the ROI of gaming in education. Discover strategies for pitching gaming to leadership. This session offers insights, tips, and examples for coaches, team leads, and enterprise leaders seeking to teach from simple to complex concepts.
Enhancing Research Orchestration Capabilities at ORNL.pdfGlobus
Cross-facility research orchestration comes with ever-changing constraints regarding the availability and suitability of various compute and data resources. In short, a flexible data and processing fabric is needed to enable the dynamic redirection of data and compute tasks throughout the lifecycle of an experiment. In this talk, we illustrate how we easily leveraged Globus services to instrument the ACE research testbed at the Oak Ridge Leadership Computing Facility with flexible data and task orchestration capabilities.
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTier1 app
Even though at surface level ‘java.lang.OutOfMemoryError’ appears as one single error; underlyingly there are 9 types of OutOfMemoryError. Each type of OutOfMemoryError has different causes, diagnosis approaches and solutions. This session equips you with the knowledge, tools, and techniques needed to troubleshoot and conquer OutOfMemoryError in all its forms, ensuring smoother, more efficient Java applications.
Modern design is crucial in today's digital environment, and this is especially true for SharePoint intranets. The design of these digital hubs is critical to user engagement and productivity enhancement. They are the cornerstone of internal collaboration and interaction within enterprises.
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...informapgpstrackings
Keep tabs on your field staff effortlessly with Informap Technology Centre LLC. Real-time tracking, task assignment, and smart features for efficient management. Request a live demo today!
For more details, visit us : https://informapuae.com/field-staff-tracking/
Into the Box Keynote Day 2: Unveiling amazing updates and announcements for modern CFML developers! Get ready for exciting releases and updates on Ortus tools and products. Stay tuned for cutting-edge innovations designed to boost your productivity.
Strategies for Successful Data Migration Tools.pptxvarshanayak241
Data migration is a complex but essential task for organizations aiming to modernize their IT infrastructure and leverage new technologies. By understanding common challenges and implementing these strategies, businesses can achieve a successful migration with minimal disruption. Data Migration Tool like Ask On Data play a pivotal role in this journey, offering features that streamline the process, ensure data integrity, and maintain security. With the right approach and tools, organizations can turn the challenge of data migration into an opportunity for growth and innovation.
Code reviews are vital for ensuring good code quality. They serve as one of our last lines of defense against bugs and subpar code reaching production.
Yet, they often turn into annoying tasks riddled with frustration, hostility, unclear feedback and lack of standards. How can we improve this crucial process?
In this session we will cover:
- The Art of Effective Code Reviews
- Streamlining the Review Process
- Elevating Reviews with Automated Tools
By the end of this presentation, you'll have the knowledge on how to organize and improve your code review proces
Software Engineering, Software Consulting, Tech Lead.
Spring Boot, Spring Cloud, Spring Core, Spring JDBC, Spring Security,
Spring Transaction, Spring MVC,
Log4j, REST/SOAP WEB-SERVICES.
Your Digital Assistant.
Making complex approach simple. Straightforward process saves time. No more waiting to connect with people that matter to you. Safety first is not a cliché - Securely protect information in cloud storage to prevent any third party from accessing data.
Would you rather make your visitors feel burdened by making them wait? Or choose VizMan for a stress-free experience? VizMan is an automated visitor management system that works for any industries not limited to factories, societies, government institutes, and warehouses. A new age contactless way of logging information of visitors, employees, packages, and vehicles. VizMan is a digital logbook so it deters unnecessary use of paper or space since there is no requirement of bundles of registers that is left to collect dust in a corner of a room. Visitor’s essential details, helps in scheduling meetings for visitors and employees, and assists in supervising the attendance of the employees. With VizMan, visitors don’t need to wait for hours in long queues. VizMan handles visitors with the value they deserve because we know time is important to you.
Feasible Features
One Subscription, Four Modules – Admin, Employee, Receptionist, and Gatekeeper ensures confidentiality and prevents data from being manipulated
User Friendly – can be easily used on Android, iOS, and Web Interface
Multiple Accessibility – Log in through any device from any place at any time
One app for all industries – a Visitor Management System that works for any organisation.
Stress-free Sign-up
Visitor is registered and checked-in by the Receptionist
Host gets a notification, where they opt to Approve the meeting
Host notifies the Receptionist of the end of the meeting
Visitor is checked-out by the Receptionist
Host enters notes and remarks of the meeting
Customizable Components
Scheduling Meetings – Host can invite visitors for meetings and also approve, reject and reschedule meetings
Single/Bulk invites – Invitations can be sent individually to a visitor or collectively to many visitors
VIP Visitors – Additional security of data for VIP visitors to avoid misuse of information
Courier Management – Keeps a check on deliveries like commodities being delivered in and out of establishments
Alerts & Notifications – Get notified on SMS, email, and application
Parking Management – Manage availability of parking space
Individual log-in – Every user has their own log-in id
Visitor/Meeting Analytics – Evaluate notes and remarks of the meeting stored in the system
Visitor Management System is a secure and user friendly database manager that records, filters, tracks the visitors to your organization.
"Secure Your Premises with VizMan (VMS) – Get It Now"
How Recreation Management Software Can Streamline Your Operations.pptxwottaspaceseo
Recreation management software streamlines operations by automating key tasks such as scheduling, registration, and payment processing, reducing manual workload and errors. It provides centralized management of facilities, classes, and events, ensuring efficient resource allocation and facility usage. The software offers user-friendly online portals for easy access to bookings and program information, enhancing customer experience. Real-time reporting and data analytics deliver insights into attendance and preferences, aiding in strategic decision-making. Additionally, effective communication tools keep participants and staff informed with timely updates. Overall, recreation management software enhances efficiency, improves service delivery, and boosts customer satisfaction.
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Globus
Large Language Models (LLMs) are currently the center of attention in the tech world, particularly for their potential to advance research. In this presentation, we'll explore a straightforward and effective method for quickly initiating inference runs on supercomputers using the vLLM tool with Globus Compute, specifically on the Polaris system at ALCF. We'll begin by briefly discussing the popularity and applications of LLMs in various fields. Following this, we will introduce the vLLM tool, and explain how it integrates with Globus Compute to efficiently manage LLM operations on Polaris. Attendees will learn the practical aspects of setting up and remotely triggering LLMs from local machines, focusing on ease of use and efficiency. This talk is ideal for researchers and practitioners looking to leverage the power of LLMs in their work, offering a clear guide to harnessing supercomputing resources for quick and effective LLM inference.
Check out the webinar slides to learn more about how XfilesPro transforms Salesforce document management by leveraging its world-class applications. For more details, please connect with sales@xfilespro.com
If you want to watch the on-demand webinar, please click here: https://www.xfilespro.com/webinars/salesforce-document-management-2-0-smarter-faster-better/
2. Learning Objectives
● Explain how to define and write functions
● Illustrate how to call functions
● Analyze how to pass different arguments to
functions
● Demonstrate how to return a value from
functions
Computer Science Department, UET Lahore.
3. Working Example
Write a Python Program to calculate the mean of five
numbers input by user.
Formula for calculating the mean is:
For Example:
Computer Science Department, UET Lahore.
Input: 1, 2, 3, 4
Output: 2.5
Mean = {Sum of numbers} ÷ {Total numbers}
4. Working Example: Solution
Computer Science Department, UET Lahore.
add = 0
for x in range(0,5,1):
num = int(input(“Enter Number: ”))
add = add + num
print(“Mean: ”, add/5)
Output:
Enter Number: 1
Enter Number: 2
Enter Number: 3
Enter Number: 4
Enter Number: 5
Mean: 3.0
To calculate the mean,
We can use this method
5. Is there any better Solution?
Computer Science Department, UET Lahore.
add = 0
for x in range(0,5,1):
num = int(input(“Enter Number: ”))
add = add + num
print(“Mean: ”, add/5)
Output:
Enter Number: 1
Enter Number: 2
Enter Number: 3
Enter Number: 4
Enter Number: 5
Mean: 3.0
To calculate the mean,
We can use this method
6. Is there any better Solution?
Computer Science Department, UET Lahore.
● Better solution in terms of readability and
simplicity.
● Yes, there is.
● But before moving to the solution lets take a real
life example of Automobile factory.
7. Automobiles in Factory
● How do the automobiles are created in the
factory?
Computer Science Department, UET Lahore.
8. Components of Automobiles
● Wheels, Brakes, Engine, Steering Wheels etc are
the components of the car.
Computer Science Department, UET Lahore.
9. Automobiles in Factory
● Wheels, Brakes, Engine, Steering Wheels are
manufactured separately and they are assembled
in the automobile factory.
Computer Science Department, UET Lahore.
10. Functions
● Functions are like short programs that can take
input, process on it, and may return the results
● Functions are like building blocks. They let you
divide complicated programs into manageable
pieces
Computer Science Department, UET Lahore.
11. Functions: How to Create?
● Functions are defined using “def” keyword in python.
● Parameters are inputs to the function and they are
separated by commas.
● “return” is the keyword for returning the output
● Example:
Computer Science Department, UET Lahore.
12. Functions: How to Call?
● Functions are called by writing the name of the
function and passing the parameters to the
functions.
● Output of the function is received in a new
variable.
● Example:
Computer Science Department, UET Lahore.
14. Functions: Previous Example
Computer Science Department, UET Lahore.
def calculate_sum():
add = 0
for x in range(0,5,1):
num = int(input("Enter Number: "))
add = add + num
return add
To calculate the sum,
We can use this
function
def calculate_avg(sum):
avg = sum/5
return avg
To calculate the average,
We can use this method
sum = calculate_sum()
print("Mean: ", calculate_avg(sum))
The rest of program
would look like this.
15. User-Defined Functions:
● These Functions are called user-defined functions
because they are defined by the users.
● For the program’s simplicity and more readability,
users can define as many functions as they want.
Computer Science Department, UET Lahore.
16. User-Defined Functions: Benefits
● Functions make the code reusable. We can declare
them once and use them multiple times.
● Functions make the program easier as each small
task is divided into a function.
● Functions increase readability.
Computer Science Department, UET Lahore.
18. Pre-Defined (Library) Functions:
● Library functions are the built-in functions in
Python programming.
● Programmers can use library functions by invoking
the functions directly; they don't need to write
the functions themselves.
Computer Science Department, UET Lahore.
19. Functions: Previous Example
Computer Science Department, UET Lahore.
Instead of writing this complete code, Python library (statistics) has
already written this code.
20. Pre-Defined Functions: Extended
Computer Science Department, UET Lahore.
import statistics
my_list = []
for x in range(0,5,1):
y = int(input("Enter Number: "))
my_list.append(y)
mean = float(statistics.mean(my_list))
print("Mean: ", mean)
Output:
Enter Number: 1
Enter Number: 2
Enter Number: 3
Enter Number: 4
Enter Number: 5
Mean: 3.0
To calculate the mean,
We can use Pre-defined Functions
Don’t Worry. We will learn
about Lists in Coming Lectures.
22. Built-in Functions: with importing math library
Computer Science Department, UET Lahore.
● import maths
23. Built-in Functions: with importing math library
Computer Science Department, UET Lahore.
● For Example:
24. Learning Objective
In this lecture, we learnt about functions,
how to define functions with different
parameters, differentiate between built-in
and user-defined functions.
Computer Science Department, UET Lahore.
25. Conclusion
● A function is a block of organized, reusable code
that is used to perform a single, related action.
● Functions are of 2 types
○ Built-in Functions User-defined
Functions
● Functions can have zero or more parameters.
● Syntax to define and call Functions is as follows:
Computer Science Department, UET Lahore.
26. Take Home Tasks
1. Create a function that takes the age in years and returns
the age in days.
Note:
● Use 365 days as the length of a year for this challenge.
● Ignore leap years and days between last birthday and now.
● Expect only positive integer inputs.
Examples:
● calcAge(65) ➞ 23725
● calcAge(0) ➞ 0
● calcAge(20) ➞ 7300
Computer Science Department, UET Lahore.