Introduction to Value-Returning Functions: Generating Random Numbers

Slides:



Advertisements
Similar presentations
BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming.
Advertisements

Introduction to Computers and Programming Lecture 11: Introduction to Methods Professor: Evan Korth New York University.
Introduction to Computers and Programming Introduction to Methods in Java.
Python (yay!) November 16, Unit 7. Recap We can store values in variables using an assignment statement >>>x = We can get input from the user using.
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.
 2003 Prentice Hall, Inc. All rights reserved. CHAPTER 3 JavaScript 1.
Chapter 6: User-Defined Functions I Instructor: Mohammad Mojaddam
Functions and Modules CSIS 1595: Fundamentals of Programming and Problem Solving 1.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 6 Value- Returning Functions and Modules.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 6 Value-Returning.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 5 Functions.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
 2003 Prentice Hall, Inc. All rights reserved. CHAPTER 3 JavaScript 1.
Module 3 Fraser High School. Module 3 – Loops and Booleans import statements - random use the random.randint() function use while loop write conditional.
Functions, Procedures, and Abstraction Dr. José M. Reyes Álamo.
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 6 Using Methods.
Functions CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
FUNCTIONS. Topics Introduction to Functions Defining and Calling a Void Function Designing a Program to Use Functions Local Variables Passing Arguments.
Loops and Simple Functions CS303E: Elements of Computers and Programming.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter 3: User-Defined Functions I
COP 2510 Chapter 6 - Functions. Random function (randint) #import the desired function import random #integer random number in the range of 1 through.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Loops and Simple Functions COSC Review: While Loops Typically used when the number of times the loop will execute is indefinite Typically used when.
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 (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
Copyright © 2013 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Third Edition by Tony Gaddis.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4.
Fundamentals of Programming I Overview of Programming
Lesson 06: Functions Class Participation: Class Chat:
Chapter 9: Value-Returning Functions
Exam #1 You will have exactly 30 Mins to complete the exam.
Topics Introduction to Functions Defining and Calling a Void Function
Recap: If, elif, else If <True condition>:
Chapter 6: User-Defined Functions I
IGCSE 4 Cambridge Data types and arrays Computer Science Section 2
CMPT 120 Topic: Python Modules.
Topics Introduction Hardware and Software How Computers Store Data
Chapter 3 Assignment and Interactive Input.
CS 1110 Introduction to Programming Spring 2017
Topics Introduction to Repetition Structures
Chapter 6 Functions.
JavaScript: Functions
Functions CIS 40 – Introduction to Programming in Python
JavaScript: Functions.
Topics Introduction to Repetition Structures
User-Defined Functions
Functions, Procedures, and Abstraction
Functions.
First Python Program Professor Hugh C. Lauer CS-1004 — Introduction to Programming for Non-Majors (Slides include materials from Python Programming: An.
Topics Introduction Hardware and Software How Computers Store Data
CS 1111 Introduction to Programming Fall 2018
Lesson 06: Functions Class Chat: Attendance: Participation
Writing Functions( ) (Part 4)
Topics Designing a Program Input, Processing, and Output
Bryan Burlingame 13 February 2019
Topics Introduction to Functions Defining and Calling a Void Function
Introduction to Repetition Structures
Topics Introduction to Value-returning Functions: Generating Random Numbers Writing Your Own Value-Returning Functions The math Module Storing Functions.
Topics Introduction to Functions Defining and Calling a Function
Terminal-Based Programs
Loops and Simple Functions
COMPUTER PROGRAMMING SKILLS
Predefined Functions Revisited
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.
Global Variables Created by assignment statement placed at beginning of program and outside all functions Can be accessed by any statement in the program.
Functions, Procedures, and Abstraction
 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.
Using Modules.
Presentation transcript:

Introduction to Value-Returning Functions: Generating Random Numbers void function: group of statements within a program for performing a specific task Call function when you need to perform the task Value-returning function: similar to void function, returns a value Value returned to part of program that called the function when function finishes executing

Standard Library Functions and the import Statement Standard library: library of pre-written functions that comes with Python Library functions perform tasks that programmers commonly need Example: print, input, range Viewed by programmers as a “black box” Some library functions built into Python interpreter To use, just call the function

Standard Library Functions and the import Statement (cont’d.) Modules: files that stores functions of the standard library Help organize library functions not built into the interpreter Copied to computer when you install Python To call a function stored in a module, need to write an import statement Written at the top of the program Format: import module_name

Standard Library Functions and the import Statement (cont’d.)

Generating Random Numbers Random number are useful in a lot of programming tasks random module: includes library functions for working with random numbers Dot notation: notation for calling a function belonging to a module Format: module_name.function_name()

Generating Random Numbers (cont’d.) randint function: generates a random number in the range provided by the arguments Returns the random number to part of program that called the function Returned integer can be used anywhere that an integer would be used You can experiment with the function in interactive mode

Generating Random Numbers (cont’d.)

Generating Random Numbers (cont’d.)

Example # This program displays a random number # in the range of 1 through 100. import random def main(): # Get a random number. number = random.randint(1, 100) # Display the number. print('The number is', number) # Call the main function. main()

Writing Your Own Value-Returning Functions To write a value-returning function, you write a simple function and add one or more return statements Format: return expression The value for expression will be returned to the part of the program that called the function The expression in the return statement can be a complex expression, such as a sum of two variables or the result of another value- returning function

Writing Your Own Value-Returning Functions (cont’d.)

Example # This program uses the return value of a function. def main(): first_age = int(input('Enter your age: ')) second_age = int(input("Enter your best friend's age: ")) # Get the sum of both ages. total = sum(first_age, second_age) print('Together you are', total, 'years old.') # The sum function accepts two numeric arguments and # returns the sum of those arguments. def sum(num1, num2): result = num1 + num2 return result # Call the main function. main()

How to Use Value-Returning Functions Value-returning function can be useful in specific situations Example: have function prompt user for input and return the user’s input Simplify mathematical expressions Complex calculations that need to be repeated throughout the program Use the returned value Assign it to a variable or use as an argument in another function

Returning Strings You can write functions that return strings For example:

The math Module math module: part of standard library that contains functions that are useful for performing mathematical calculations Typically accept one or more values as arguments, perform mathematical operation, and return the result Use of module requires an import math statement

The math Module (cont’d.)

The math Module (cont’d.) The math module defines variables pi and e, which are assigned the mathematical values for pi and e Can be used in equations that require these values, to get more accurate results Variables must also be called using the dot notation Example: circle_area = math.pi * radius**2

Example # This program demonstrates the sqrt function. import math def main(): # Get a number. number = float(input('Enter a number: ')) # Get the square root of the number. square_root = math.sqrt(number) # Display the square root. print('The square root of', number, 'is', square_root) # Call the main function. main()

Storing Functions in Modules In large, complex programs, it is important to keep code organized Modularization: grouping related functions in modules Makes program easier to understand, test, and maintain Make it easier to reuse code for multiple different programs Import the module containing the required function to each program that needs it

Storing Functions in Modules (cont’d.) Module is a file that contains Python code Contains function definition but does not contain calls to the functions Importing programs will call the functions Rules for module names: File name should end in .py Cannot be the same as a Python keyword Import module using import statement

Example # The circle module has functions that perform # calculations related to circles. import math # The area function accepts a circle's radius as an # argument and returns the area of the circle. def area(radius): return math.pi * radius**2 # The circumference function accepts a circle's # radius and returns the circle's circumference. def circumference(radius): return 2 * math.pi * radius