SlideShare a Scribd company logo
Python workshop by Ebad ullah Qureshi
Instructor: Ebad ullah Qureshi
Email: ebadullah.qureshi@rutgers.edu
N2E Coding Club
Python Workshop
Functional
Programming
Python workshop by Ebad ullah Qureshi
Time Conversion – Problem
2
Given a time in 12-hour AM/PM format, convert it to military (24-hour) time.
Note: Midnight is 12:00:00AM on a 12-hour clock, and 00:00:00 on a 24-hour clock. Noon is
12:00:00PM on a 12-hour clock, and 12:00:00 on a 24-hour clock.
Input Format
A single string containing a time in 12-hour clock format (i.e.: hh:mm:ssAM or hh:mm:ssPM),
where 01≤hh≤12 and 00≤mm,ss≤59.
Constraints
All input times are valid, example, 07:05:45PM.
Output Format
Convert and print the given time in -hour format, where 00≤hh≤23, example, 19:05:45.
Testing
Test your program for 07:05:45AM, 12:05:45AM, 07:05:45PM, and 12:05:45PM.
Python workshop by Ebad ullah Qureshi 3
Time Conversion – Starting out
# Getting input
time12 = input("Enter time in hh:mm:ssAM or hh:mm:ssPM “)
# time12 and time24 have common minutes and seconds [:mm:ss]
time24 = time12[2:8]
# str12 format: hh:mm:ssAM or hh:mm:ssPM
am_or_pm = time12[8]
# Slicing hours
hour = time12[0:2]
Python workshop by Ebad ullah Qureshi 4
Time Conversion – Conditional Block
if am_or_pm == 'A':
# for str12 01:00AM to 11:59AM
if hour != '12':
time24 = hour + time24
# for str12 12:00AM to 12:59AM
else:
time24 = "00" + time24
else:
# for str12 01:00PM to 11:59PM
if hour != '12':
hr = int(hour) + 12
time24 = str(hr) + time24
# for str12 12:00PM to 12:59PM
else:
time24 = hour + time24
Python workshop by Ebad ullah Qureshi
Time Conversion – Program Output
5
print('Time in 24-hour clock format:', time24)
› Enter time in hh:mm:ssAM or hh:mm:ssPM 07:05:45AM
› Time in 24-hour clock format: 07:05:45
› Enter time in hh:mm:ssAM or hh:mm:ssPM 07:05:45PM
› Time in 24-hour clock format: 19:05:45
› Enter time in hh:mm:ssAM or hh:mm:ssPM 12:05:45AM
› Time in 24-hour clock format: 00:05:45
› Enter time in hh:mm:ssAM or hh:mm:ssPM 12:05:45PM
› Time in 24-hour clock format: 12:05:45
Python workshop by Ebad ullah Qureshi 6
Introducing Functions I
• In the previous problem, the program ran 4 times to test 4 inputs and it was dependent upon
the user’s valid input
• A time_conversion function would be very helpful here
• The user’s input can be validated separately from the function so that the function always
receives a valid input and the function can be reused as many times to test various inputs
• A function is a block of organized, reusable code that is used to perform a single, related action
• Functions provide better modularity for your application and a high degree of code reusing
Python workshop by Ebad ullah Qureshi 7
Introducing Functions II
# Previous Examples of functions you’ve already seen
print('Hello world')
range(5, 17, 2)
len('python')
• The words in front of the parentheses are function names
• The values inside the parenthesis are function arguments
Python workshop by Ebad ullah Qureshi
Defining and Calling a Function
8
# defining a function
def hello():
print('hello world')
# calling the function
hello()
› hello world
Python workshop by Ebad ullah Qureshi
Arguments and Return Statement
9
def add(num1, num2): # num1 and num 2 are arguments
return num1 + num2 # result is returned
# Function Calling
total = add(7, 9)
print(total)
› 16
Function returning the sum of 2 numbers
Python workshop by Ebad ullah Qureshi
Flexible Number of Arguments
10
def add_numbers(*args):
total = 0
for num in args:
total += num
return total
print(add_numbers(5, 6, 8, 4, 2))
print(add_numbers(234, 543))
print(add_numbers(34, 56, 78, 5, 5.67, 2.45, 5*4))
› 25
› 777
› 201.11999999999998
Function to return the sum of numbers passed as argument
Python workshop by Ebad ullah Qureshi
More about arguments
11
def cool_function(a, b=4, c=10):
# b and c are default value arguments
print('a is', a, 'b is', b, 'c is', c)
cool_function(38, 49) # a&b are passed c takes its default value
cool_function(54, c=74) # c is keyword argument, b is default argument
cool_function(c=72, a=23)# a&c are keyword arguments, b is default argument
data = [45, 35, 67] # a = data[0], b = data[1], c = data[2]
cool_function(*data) # * unpacks the list and passes it to the function
› a is 38 b is 49 c is 10
› a is 54 b is 4 c is 74
› a is 23 b is 4 c is 72
› a is 45 b is 35 c is 67
Python workshop by Ebad ullah Qureshi 12
Time Conversion – Function
def time_conversion(time12):
time24 = time12[2:8]
am_or_pm = time12[8]
hour = time12[0:2]
if am_or_pm == 'A':
if hour != '12':
time24 = hour + time24
else:
time24 = "00" + time24
else:
if hour != '12':
hr = int(hour) + 12
time24 = str(hr) + time24
else:
time24 = hour + time24
return time24
Python workshop by Ebad ullah Qureshi
Time Conversion – Testing the Function
13
# calling the function
print(time_conversion('07:05:45AM'))
print(time_conversion('12:05:45AM'))
print(time_conversion('07:05:45PM'))
print(time_conversion('12:05:45PM'))
› 07:05:45
› 00:05:45
› 19:05:45
› 12:05:45
Python workshop by Ebad ullah Qureshi
Python Modules
14
There are 3 main types of modules;
1. Those you write yourself
2. Those you install from external resources
3. Those that are preinstalled with Python
The last type is called the standard library and has many useful functions
Python workshop by Ebad ullah Qureshi
Python Standard Library
15
• Python’s extensive standard library is one of its main strengths as a language
• Some useful modules are;
 string
 re
 datetime
 math
 random
 os
 socket
 email
 json
 sys
 and much more
Python workshop by Ebad ullah Qureshi
Modules in Python Standard library
16
• Some of the Python Modules in the standard library are written in Python, and some are
written in C
• Most are available on all platforms, but some are windows or Unix specific
• Many third-party Python modules are stored on the Python Package Index (PyPI)
• Modules are installed using a program called pip
• To install, go to the command line (command prompt on windows) and enter
> pip install library_name
• An alternate way to install is through the Project Interpreter on Pycharm
• Some modules have prebuilt binaries that are normal executable files for Windows and let
you install them with a GUI in the same way you would install other programs.
• Use the modules in your program using the import keyword
Python workshop by Ebad ullah Qureshi
Gift Card Winners – Problem
17
import random
# random.randint(a,b) generates a random number N such that a <= N <= b
print(random.randint(1, 10))
› 7
As a General manager, you are responsible to give away a Gift Card to a raffle winner among your
top 10 performers. Write a python script to generate a random number that would correspond to
the winner of this week’s prize.
Python workshop by Ebad ullah Qureshi
Gift Card Winners – Alternate Solution
18
from random import randint
# randint(a,b) generates a random number N such that a <= N <= b
print(randint(1, 10))
› 4
• In the previous solution, the whole module was imported when we only required the randint()
function
• There is an alternate syntax for only importing functions that are required in the program
Python workshop by Ebad ullah Qureshi
Average of 10 random numbers – Problem
19
from statistics import mean as avg
import random as r
numbers = []
for _ in range(10):
numbers.append(r.randint(1, 50))
print(numbers)
print(avg(numbers))
› [47, 26, 34, 3, 8, 4, 43, 34, 44, 11]
› 25.4
Generate a list of 10 random numbers between 1 and 50 inclusive and calculate its average.
Achieve this by importing the random module and the mean function in the statistics module.
Rename the random module r and the mean function avg
Python workshop by Ebad ullah Qureshi
Lambdas
20
# function to convert temperature in Kelvin to temperatures in degree
celsius
def kelvin_to_celsius(temperature):
return temperature – 273
print(kelvin_to_celsius(298))
# lambda function
result = (lambda temperature: temperature - 273)(250)
print(result)
› 25
› -23
• Alternate way of creating functions – lambda syntax
• Functions created this way are known as anonymous and most commonly used when passing
a simple function to another function
Python workshop by Ebad ullah Qureshi
map() and filter() function
21
• The built-in functions map and filter are very useful higher order functions that operate on list
(or other iterables
• The function map takes a function and an iterable as arguments, and returns a new iterable
with the function applied to each argument
• The function filter filters an iterable by removing items that don’t match a predicate (function
that returns a Boolean)
Python workshop by Ebad ullah Qureshi
map() and filter() function
22
kelvin_temperatures = [298, 278, 305, 245, 0, 100, 300, 400]
# convert all the temperatures in the above list into celsius
celsius_temperatures = list(map(kelvin_to_celsius, kelvin_temperatures))
print(celsius_temperatures)
# filtering out temperatures below freezing point
temp_below_zero = list(filter(lambda x: x < 0, celsius_temperatures))
print(temp_below_zero)
› [25, 5, 32, -28, -273, -173, 27, 127]
› [-28, -273, -173]
Python workshop by Ebad ullah Qureshi
Instructor: Ebad ullah Qureshi
Email: ebadullah.qureshi@rutgers.edu
N2E Coding Club
Python Workshop
Thank You!
Any Questions?

More Related Content

What's hot

Peephole Optimization
Peephole OptimizationPeephole Optimization
Peephole Optimization
United International University
 
Dead Code Elimination
Dead Code EliminationDead Code Elimination
Dead Code Elimination
Samiul Ehsan
 
halstead software science measures
halstead software science measureshalstead software science measures
halstead software science measures
Deepti Pillai
 
Introduction to MPI
Introduction to MPIIntroduction to MPI
Introduction to MPI
yaman dua
 
Compiler optimization
Compiler optimizationCompiler optimization
Compiler optimization
ZongYing Lyu
 
Code Optimization
Code OptimizationCode Optimization
Code Optimization
ESUG
 
Introduction to code optimization by dipankar
Introduction to code optimization by dipankarIntroduction to code optimization by dipankar
Introduction to code optimization by dipankar
Dipankar Nalui
 
Apclass (2)
Apclass (2)Apclass (2)
Apclass (2)
geishaannealagos
 
Function Overloading,Inline Function and Recursion in C++ By Faisal Shahzad
Function Overloading,Inline Function and Recursion in C++ By Faisal ShahzadFunction Overloading,Inline Function and Recursion in C++ By Faisal Shahzad
Function Overloading,Inline Function and Recursion in C++ By Faisal Shahzad
Faisal Shehzad
 
Apclass
ApclassApclass
Introduction to design and analysis of algorithm
Introduction to design and analysis of algorithmIntroduction to design and analysis of algorithm
Introduction to design and analysis of algorithm
DevaKumari Vijay
 
Compiler Construction | Lecture 10 | Data-Flow Analysis
Compiler Construction | Lecture 10 | Data-Flow AnalysisCompiler Construction | Lecture 10 | Data-Flow Analysis
Compiler Construction | Lecture 10 | Data-Flow Analysis
Eelco Visser
 
Refactoring Techniques
Refactoring TechniquesRefactoring Techniques
Refactoring Techniques
Mayada Ghanem
 
Ch7
Ch7Ch7
Gcc porting
Gcc portingGcc porting
Gcc porting
Shiva Chen
 
Compiler Design- Machine Independent Optimizations
Compiler Design- Machine Independent OptimizationsCompiler Design- Machine Independent Optimizations
Compiler Design- Machine Independent Optimizations
Jyothishmathi Institute of Technology and Science Karimnagar
 
LLVM Instruction Selection
LLVM Instruction SelectionLLVM Instruction Selection
LLVM Instruction Selection
Shiva Chen
 
Peephole optimization techniques in compiler design
Peephole optimization techniques in compiler designPeephole optimization techniques in compiler design
Peephole optimization techniques in compiler design
Anul Chaudhary
 
LLVM Backend Porting
LLVM Backend PortingLLVM Backend Porting
LLVM Backend Porting
Shiva Chen
 
Peephole Optimization
Peephole OptimizationPeephole Optimization
Peephole Optimization
Meghaj Mallick
 

What's hot (20)

Peephole Optimization
Peephole OptimizationPeephole Optimization
Peephole Optimization
 
Dead Code Elimination
Dead Code EliminationDead Code Elimination
Dead Code Elimination
 
halstead software science measures
halstead software science measureshalstead software science measures
halstead software science measures
 
Introduction to MPI
Introduction to MPIIntroduction to MPI
Introduction to MPI
 
Compiler optimization
Compiler optimizationCompiler optimization
Compiler optimization
 
Code Optimization
Code OptimizationCode Optimization
Code Optimization
 
Introduction to code optimization by dipankar
Introduction to code optimization by dipankarIntroduction to code optimization by dipankar
Introduction to code optimization by dipankar
 
Apclass (2)
Apclass (2)Apclass (2)
Apclass (2)
 
Function Overloading,Inline Function and Recursion in C++ By Faisal Shahzad
Function Overloading,Inline Function and Recursion in C++ By Faisal ShahzadFunction Overloading,Inline Function and Recursion in C++ By Faisal Shahzad
Function Overloading,Inline Function and Recursion in C++ By Faisal Shahzad
 
Apclass
ApclassApclass
Apclass
 
Introduction to design and analysis of algorithm
Introduction to design and analysis of algorithmIntroduction to design and analysis of algorithm
Introduction to design and analysis of algorithm
 
Compiler Construction | Lecture 10 | Data-Flow Analysis
Compiler Construction | Lecture 10 | Data-Flow AnalysisCompiler Construction | Lecture 10 | Data-Flow Analysis
Compiler Construction | Lecture 10 | Data-Flow Analysis
 
Refactoring Techniques
Refactoring TechniquesRefactoring Techniques
Refactoring Techniques
 
Ch7
Ch7Ch7
Ch7
 
Gcc porting
Gcc portingGcc porting
Gcc porting
 
Compiler Design- Machine Independent Optimizations
Compiler Design- Machine Independent OptimizationsCompiler Design- Machine Independent Optimizations
Compiler Design- Machine Independent Optimizations
 
LLVM Instruction Selection
LLVM Instruction SelectionLLVM Instruction Selection
LLVM Instruction Selection
 
Peephole optimization techniques in compiler design
Peephole optimization techniques in compiler designPeephole optimization techniques in compiler design
Peephole optimization techniques in compiler design
 
LLVM Backend Porting
LLVM Backend PortingLLVM Backend Porting
LLVM Backend Porting
 
Peephole Optimization
Peephole OptimizationPeephole Optimization
Peephole Optimization
 

Similar to 04 Functional Programming in Python

Programming Fundamentals Functions in C and types
Programming Fundamentals  Functions in C  and typesProgramming Fundamentals  Functions in C  and types
Programming Fundamentals Functions in C and types
imtiazalijoono
 
01 Introduction to Python
01 Introduction to Python01 Introduction to Python
01 Introduction to Python
Ebad ullah Qureshi
 
Lec16-CS110 Computational Engineering
Lec16-CS110 Computational EngineeringLec16-CS110 Computational Engineering
Lec16-CS110 Computational Engineering
Sri Harsha Pamu
 
Intro to c++
Intro to c++Intro to c++
Intro to c++
temkin abdlkader
 
Parallel and Async Programming With C#
Parallel and Async Programming With C#Parallel and Async Programming With C#
Parallel and Async Programming With C#
Rainer Stropek
 
Basic Elements of C++
Basic Elements of C++Basic Elements of C++
Basic Elements of C++
Jason J Pulikkottil
 
02 functions, variables, basic input and output of c++
02   functions, variables, basic input and output of c++02   functions, variables, basic input and output of c++
02 functions, variables, basic input and output of c++
Manzoor ALam
 
Intro to Python for Non-Programmers
Intro to Python for Non-ProgrammersIntro to Python for Non-Programmers
Intro to Python for Non-Programmers
Ahmad Alhour
 
Building source code level profiler for C++.pdf
Building source code level profiler for C++.pdfBuilding source code level profiler for C++.pdf
Building source code level profiler for C++.pdf
ssuser28de9e
 
ProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdfProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdf
lailoesakhan
 
unit_2 (1).pptx
unit_2 (1).pptxunit_2 (1).pptx
unit_2 (1).pptx
JVenkateshGoud
 
Tech talks#6: Code Refactoring
Tech talks#6: Code RefactoringTech talks#6: Code Refactoring
Tech talks#6: Code Refactoring
Nguyễn Việt Khoa
 
Programming For Engineers Functions - Part #1.pptx
Programming For Engineers Functions - Part #1.pptxProgramming For Engineers Functions - Part #1.pptx
Programming For Engineers Functions - Part #1.pptx
NoorAntakia
 
Functions
FunctionsFunctions
Functions
Learn By Watch
 
Apclass (2)
Apclass (2)Apclass (2)
Apclass (2)
geishaannealagos
 
Object oriented programming 12 programming steps in cpp and example
Object oriented programming 12 programming steps in cpp and exampleObject oriented programming 12 programming steps in cpp and example
Object oriented programming 12 programming steps in cpp and example
Vaibhav Khanna
 
Thinking in Functions
Thinking in FunctionsThinking in Functions
Thinking in Functions
Alexandru Bolboaca
 
Operating System Lab Manual
Operating System Lab ManualOperating System Lab Manual
Operating System Lab Manual
Bilal Mirza
 
07 control+structures
07 control+structures07 control+structures
07 control+structures
baran19901990
 
C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#
Hawkman Academy
 

Similar to 04 Functional Programming in Python (20)

Programming Fundamentals Functions in C and types
Programming Fundamentals  Functions in C  and typesProgramming Fundamentals  Functions in C  and types
Programming Fundamentals Functions in C and types
 
01 Introduction to Python
01 Introduction to Python01 Introduction to Python
01 Introduction to Python
 
Lec16-CS110 Computational Engineering
Lec16-CS110 Computational EngineeringLec16-CS110 Computational Engineering
Lec16-CS110 Computational Engineering
 
Intro to c++
Intro to c++Intro to c++
Intro to c++
 
Parallel and Async Programming With C#
Parallel and Async Programming With C#Parallel and Async Programming With C#
Parallel and Async Programming With C#
 
Basic Elements of C++
Basic Elements of C++Basic Elements of C++
Basic Elements of C++
 
02 functions, variables, basic input and output of c++
02   functions, variables, basic input and output of c++02   functions, variables, basic input and output of c++
02 functions, variables, basic input and output of c++
 
Intro to Python for Non-Programmers
Intro to Python for Non-ProgrammersIntro to Python for Non-Programmers
Intro to Python for Non-Programmers
 
Building source code level profiler for C++.pdf
Building source code level profiler for C++.pdfBuilding source code level profiler for C++.pdf
Building source code level profiler for C++.pdf
 
ProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdfProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdf
 
unit_2 (1).pptx
unit_2 (1).pptxunit_2 (1).pptx
unit_2 (1).pptx
 
Tech talks#6: Code Refactoring
Tech talks#6: Code RefactoringTech talks#6: Code Refactoring
Tech talks#6: Code Refactoring
 
Programming For Engineers Functions - Part #1.pptx
Programming For Engineers Functions - Part #1.pptxProgramming For Engineers Functions - Part #1.pptx
Programming For Engineers Functions - Part #1.pptx
 
Functions
FunctionsFunctions
Functions
 
Apclass (2)
Apclass (2)Apclass (2)
Apclass (2)
 
Object oriented programming 12 programming steps in cpp and example
Object oriented programming 12 programming steps in cpp and exampleObject oriented programming 12 programming steps in cpp and example
Object oriented programming 12 programming steps in cpp and example
 
Thinking in Functions
Thinking in FunctionsThinking in Functions
Thinking in Functions
 
Operating System Lab Manual
Operating System Lab ManualOperating System Lab Manual
Operating System Lab Manual
 
07 control+structures
07 control+structures07 control+structures
07 control+structures
 
C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#
 

Recently uploaded

Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Safe Software
 
UI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentationUI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentation
Wouter Lemaire
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Alpen-Adria-Universität
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
DanBrown980551
 
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
Tatiana Kojar
 
WeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation TechniquesWeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation Techniques
Postman
 
Deep Dive: Getting Funded with Jason Jason Lemkin Founder & CEO @ SaaStr
Deep Dive: Getting Funded with Jason Jason Lemkin Founder & CEO @ SaaStrDeep Dive: Getting Funded with Jason Jason Lemkin Founder & CEO @ SaaStr
Deep Dive: Getting Funded with Jason Jason Lemkin Founder & CEO @ SaaStr
saastr
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
Zilliz
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
Zilliz
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
Hiroshi SHIBATA
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
Chart Kalyan
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Tosin Akinosho
 
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
saastr
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
Tatiana Kojar
 
A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024
Intelisync
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
Tomaz Bratanic
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
Zilliz
 
Recommendation System using RAG Architecture
Recommendation System using RAG ArchitectureRecommendation System using RAG Architecture
Recommendation System using RAG Architecture
fredae14
 
AWS Cloud Cost Optimization Presentation.pptx
AWS Cloud Cost Optimization Presentation.pptxAWS Cloud Cost Optimization Presentation.pptx
AWS Cloud Cost Optimization Presentation.pptx
HarisZaheer8
 

Recently uploaded (20)

Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
 
UI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentationUI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentation
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
 
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
 
WeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation TechniquesWeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation Techniques
 
Deep Dive: Getting Funded with Jason Jason Lemkin Founder & CEO @ SaaStr
Deep Dive: Getting Funded with Jason Jason Lemkin Founder & CEO @ SaaStrDeep Dive: Getting Funded with Jason Jason Lemkin Founder & CEO @ SaaStr
Deep Dive: Getting Funded with Jason Jason Lemkin Founder & CEO @ SaaStr
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
 
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
 
A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
 
Recommendation System using RAG Architecture
Recommendation System using RAG ArchitectureRecommendation System using RAG Architecture
Recommendation System using RAG Architecture
 
AWS Cloud Cost Optimization Presentation.pptx
AWS Cloud Cost Optimization Presentation.pptxAWS Cloud Cost Optimization Presentation.pptx
AWS Cloud Cost Optimization Presentation.pptx
 

04 Functional Programming in Python

  • 1. Python workshop by Ebad ullah Qureshi Instructor: Ebad ullah Qureshi Email: ebadullah.qureshi@rutgers.edu N2E Coding Club Python Workshop Functional Programming
  • 2. Python workshop by Ebad ullah Qureshi Time Conversion – Problem 2 Given a time in 12-hour AM/PM format, convert it to military (24-hour) time. Note: Midnight is 12:00:00AM on a 12-hour clock, and 00:00:00 on a 24-hour clock. Noon is 12:00:00PM on a 12-hour clock, and 12:00:00 on a 24-hour clock. Input Format A single string containing a time in 12-hour clock format (i.e.: hh:mm:ssAM or hh:mm:ssPM), where 01≤hh≤12 and 00≤mm,ss≤59. Constraints All input times are valid, example, 07:05:45PM. Output Format Convert and print the given time in -hour format, where 00≤hh≤23, example, 19:05:45. Testing Test your program for 07:05:45AM, 12:05:45AM, 07:05:45PM, and 12:05:45PM.
  • 3. Python workshop by Ebad ullah Qureshi 3 Time Conversion – Starting out # Getting input time12 = input("Enter time in hh:mm:ssAM or hh:mm:ssPM “) # time12 and time24 have common minutes and seconds [:mm:ss] time24 = time12[2:8] # str12 format: hh:mm:ssAM or hh:mm:ssPM am_or_pm = time12[8] # Slicing hours hour = time12[0:2]
  • 4. Python workshop by Ebad ullah Qureshi 4 Time Conversion – Conditional Block if am_or_pm == 'A': # for str12 01:00AM to 11:59AM if hour != '12': time24 = hour + time24 # for str12 12:00AM to 12:59AM else: time24 = "00" + time24 else: # for str12 01:00PM to 11:59PM if hour != '12': hr = int(hour) + 12 time24 = str(hr) + time24 # for str12 12:00PM to 12:59PM else: time24 = hour + time24
  • 5. Python workshop by Ebad ullah Qureshi Time Conversion – Program Output 5 print('Time in 24-hour clock format:', time24) › Enter time in hh:mm:ssAM or hh:mm:ssPM 07:05:45AM › Time in 24-hour clock format: 07:05:45 › Enter time in hh:mm:ssAM or hh:mm:ssPM 07:05:45PM › Time in 24-hour clock format: 19:05:45 › Enter time in hh:mm:ssAM or hh:mm:ssPM 12:05:45AM › Time in 24-hour clock format: 00:05:45 › Enter time in hh:mm:ssAM or hh:mm:ssPM 12:05:45PM › Time in 24-hour clock format: 12:05:45
  • 6. Python workshop by Ebad ullah Qureshi 6 Introducing Functions I • In the previous problem, the program ran 4 times to test 4 inputs and it was dependent upon the user’s valid input • A time_conversion function would be very helpful here • The user’s input can be validated separately from the function so that the function always receives a valid input and the function can be reused as many times to test various inputs • A function is a block of organized, reusable code that is used to perform a single, related action • Functions provide better modularity for your application and a high degree of code reusing
  • 7. Python workshop by Ebad ullah Qureshi 7 Introducing Functions II # Previous Examples of functions you’ve already seen print('Hello world') range(5, 17, 2) len('python') • The words in front of the parentheses are function names • The values inside the parenthesis are function arguments
  • 8. Python workshop by Ebad ullah Qureshi Defining and Calling a Function 8 # defining a function def hello(): print('hello world') # calling the function hello() › hello world
  • 9. Python workshop by Ebad ullah Qureshi Arguments and Return Statement 9 def add(num1, num2): # num1 and num 2 are arguments return num1 + num2 # result is returned # Function Calling total = add(7, 9) print(total) › 16 Function returning the sum of 2 numbers
  • 10. Python workshop by Ebad ullah Qureshi Flexible Number of Arguments 10 def add_numbers(*args): total = 0 for num in args: total += num return total print(add_numbers(5, 6, 8, 4, 2)) print(add_numbers(234, 543)) print(add_numbers(34, 56, 78, 5, 5.67, 2.45, 5*4)) › 25 › 777 › 201.11999999999998 Function to return the sum of numbers passed as argument
  • 11. Python workshop by Ebad ullah Qureshi More about arguments 11 def cool_function(a, b=4, c=10): # b and c are default value arguments print('a is', a, 'b is', b, 'c is', c) cool_function(38, 49) # a&b are passed c takes its default value cool_function(54, c=74) # c is keyword argument, b is default argument cool_function(c=72, a=23)# a&c are keyword arguments, b is default argument data = [45, 35, 67] # a = data[0], b = data[1], c = data[2] cool_function(*data) # * unpacks the list and passes it to the function › a is 38 b is 49 c is 10 › a is 54 b is 4 c is 74 › a is 23 b is 4 c is 72 › a is 45 b is 35 c is 67
  • 12. Python workshop by Ebad ullah Qureshi 12 Time Conversion – Function def time_conversion(time12): time24 = time12[2:8] am_or_pm = time12[8] hour = time12[0:2] if am_or_pm == 'A': if hour != '12': time24 = hour + time24 else: time24 = "00" + time24 else: if hour != '12': hr = int(hour) + 12 time24 = str(hr) + time24 else: time24 = hour + time24 return time24
  • 13. Python workshop by Ebad ullah Qureshi Time Conversion – Testing the Function 13 # calling the function print(time_conversion('07:05:45AM')) print(time_conversion('12:05:45AM')) print(time_conversion('07:05:45PM')) print(time_conversion('12:05:45PM')) › 07:05:45 › 00:05:45 › 19:05:45 › 12:05:45
  • 14. Python workshop by Ebad ullah Qureshi Python Modules 14 There are 3 main types of modules; 1. Those you write yourself 2. Those you install from external resources 3. Those that are preinstalled with Python The last type is called the standard library and has many useful functions
  • 15. Python workshop by Ebad ullah Qureshi Python Standard Library 15 • Python’s extensive standard library is one of its main strengths as a language • Some useful modules are;  string  re  datetime  math  random  os  socket  email  json  sys  and much more
  • 16. Python workshop by Ebad ullah Qureshi Modules in Python Standard library 16 • Some of the Python Modules in the standard library are written in Python, and some are written in C • Most are available on all platforms, but some are windows or Unix specific • Many third-party Python modules are stored on the Python Package Index (PyPI) • Modules are installed using a program called pip • To install, go to the command line (command prompt on windows) and enter > pip install library_name • An alternate way to install is through the Project Interpreter on Pycharm • Some modules have prebuilt binaries that are normal executable files for Windows and let you install them with a GUI in the same way you would install other programs. • Use the modules in your program using the import keyword
  • 17. Python workshop by Ebad ullah Qureshi Gift Card Winners – Problem 17 import random # random.randint(a,b) generates a random number N such that a <= N <= b print(random.randint(1, 10)) › 7 As a General manager, you are responsible to give away a Gift Card to a raffle winner among your top 10 performers. Write a python script to generate a random number that would correspond to the winner of this week’s prize.
  • 18. Python workshop by Ebad ullah Qureshi Gift Card Winners – Alternate Solution 18 from random import randint # randint(a,b) generates a random number N such that a <= N <= b print(randint(1, 10)) › 4 • In the previous solution, the whole module was imported when we only required the randint() function • There is an alternate syntax for only importing functions that are required in the program
  • 19. Python workshop by Ebad ullah Qureshi Average of 10 random numbers – Problem 19 from statistics import mean as avg import random as r numbers = [] for _ in range(10): numbers.append(r.randint(1, 50)) print(numbers) print(avg(numbers)) › [47, 26, 34, 3, 8, 4, 43, 34, 44, 11] › 25.4 Generate a list of 10 random numbers between 1 and 50 inclusive and calculate its average. Achieve this by importing the random module and the mean function in the statistics module. Rename the random module r and the mean function avg
  • 20. Python workshop by Ebad ullah Qureshi Lambdas 20 # function to convert temperature in Kelvin to temperatures in degree celsius def kelvin_to_celsius(temperature): return temperature – 273 print(kelvin_to_celsius(298)) # lambda function result = (lambda temperature: temperature - 273)(250) print(result) › 25 › -23 • Alternate way of creating functions – lambda syntax • Functions created this way are known as anonymous and most commonly used when passing a simple function to another function
  • 21. Python workshop by Ebad ullah Qureshi map() and filter() function 21 • The built-in functions map and filter are very useful higher order functions that operate on list (or other iterables • The function map takes a function and an iterable as arguments, and returns a new iterable with the function applied to each argument • The function filter filters an iterable by removing items that don’t match a predicate (function that returns a Boolean)
  • 22. Python workshop by Ebad ullah Qureshi map() and filter() function 22 kelvin_temperatures = [298, 278, 305, 245, 0, 100, 300, 400] # convert all the temperatures in the above list into celsius celsius_temperatures = list(map(kelvin_to_celsius, kelvin_temperatures)) print(celsius_temperatures) # filtering out temperatures below freezing point temp_below_zero = list(filter(lambda x: x < 0, celsius_temperatures)) print(temp_below_zero) › [25, 5, 32, -28, -273, -173, 27, 127] › [-28, -273, -173]
  • 23. Python workshop by Ebad ullah Qureshi Instructor: Ebad ullah Qureshi Email: ebadullah.qureshi@rutgers.edu N2E Coding Club Python Workshop Thank You! Any Questions?