Lectures from a Python workshop I taught in 2013 at the University of Pittsburgh. These are introductory slides to teach important aspects of the Python language.
Update: python limits the number of recursion calls, so computing the factorial as shown in the slides may not be generally usable.
A Gentle Introduction to Coding ... with PythonTariq Rashid
A gentle introduction to coding (programming) for complete beginners. Starting from then basics - electrical wires - proceeding through variables, data structures, loops, functions, and exploring libraries for visualisation and specialist tools. Finally we use flask to make a very simple twitter clone web application.
Lectures from a Python workshop I taught in 2013 at the University of Pittsburgh. These are introductory slides to teach important aspects of the Python language.
Update: python limits the number of recursion calls, so computing the factorial as shown in the slides may not be generally usable.
A Gentle Introduction to Coding ... with PythonTariq Rashid
A gentle introduction to coding (programming) for complete beginners. Starting from then basics - electrical wires - proceeding through variables, data structures, loops, functions, and exploring libraries for visualisation and specialist tools. Finally we use flask to make a very simple twitter clone web application.
Introduction to Python Programming | InsideAIMLVijaySharma802
Machine Learning With Python From India’s Most Advanced Learner’s Community. 200+ High-Quality Lectures. 4 Months Live Mentor-ship. 15+ Projects. Industry Insights.
Visit- https://insideaiml.com/course-details/Machine-Learning-with-Python-Statistics
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...DRVaibhavmeshram1
Python
Language
is uesd in engineeringStory adapted from Stephen Covey (2004) “The Seven Habits of Highly Effective People” Simon & Schuster).
“Management is doing things right, leadership is doing the right things”
(Warren Bennis and Peter Drucker)
Story adapted from Stephen Covey (2004) “The Seven Habits of Highly Effective People” Simon & Schuster).
“Management is doing things right, leadership is doing the right things”
(Warren Bennis and Peter Drucker)
Story adapted from Stephen Covey (2004) “The Seven Habits of Highly Effective People” Simon & Schuster).
“Management is doing things right, leadership is doing the right things”
(Warren Bennis and Peter Drucker)
The Sponsor:
Champion and advocates for the change at their level in the organization.
A Sponsor is the person who won’t let the change initiative die from lack of attention, and is willing to use their political capital to make the change happen
The Role model:
Behaviors and attitudes demonstrated by them are looked upon by everyone else. . Hence, they must be willing to go first.
Employees watch leaders for consistency between words and actions to see if they should believe the change is really going to happen.
The decision maker:
Leaders usually control resources such as people, budgets, and equipment, and thus have the authority to make decisions (as per their span of control) that affect the initiative.
During change, leaders must leverage their decision-making authority and choose the options that will support the initiative.
The Decision-Maker is decisive and sets priorities that support change.
The Sponsor:
Champion and advocates for the change at their level in the organization.
A Sponsor is the person who won’t let the change initiative die from lack of attention, and is willing to use their political capital to make the change happen
The Role model:
Behaviors and attitudes demonstrated by them are looked upon by everyone else. . Hence, they must be willing to go first.
Employees watch leaders for consistency between words and actions to see if they should believe the change is really going to happen.
The decision maker:
Leaders usually control resources such as people, budgets, and equipment, and thus have the authority to make decisions (as per their span of control) that affect the initiative.
During change, leaders must leverage their decision-making authority and choose the options that will support the initiative.
The Decision-Maker is decisive and sets priorities that support change.
The Sponsor:
Champion and advocates for the change at their level in the organization.
A Sponsor is the person who won’t let the change initiative die from lack of attention, and is willing to use their political capital to make the change happen
The Role model:
Behaviors and attitudes demonstrated by them are looked upon by everyone else. . Hence, they must be willing to go first.
Employees watch leaders for consistency between words and actions to see if they s
Introduction to Python Programming | InsideAIMLVijaySharma802
Machine Learning With Python From India’s Most Advanced Learner’s Community. 200+ High-Quality Lectures. 4 Months Live Mentor-ship. 15+ Projects. Industry Insights.
Visit- https://insideaiml.com/course-details/Machine-Learning-with-Python-Statistics
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...DRVaibhavmeshram1
Python
Language
is uesd in engineeringStory adapted from Stephen Covey (2004) “The Seven Habits of Highly Effective People” Simon & Schuster).
“Management is doing things right, leadership is doing the right things”
(Warren Bennis and Peter Drucker)
Story adapted from Stephen Covey (2004) “The Seven Habits of Highly Effective People” Simon & Schuster).
“Management is doing things right, leadership is doing the right things”
(Warren Bennis and Peter Drucker)
Story adapted from Stephen Covey (2004) “The Seven Habits of Highly Effective People” Simon & Schuster).
“Management is doing things right, leadership is doing the right things”
(Warren Bennis and Peter Drucker)
The Sponsor:
Champion and advocates for the change at their level in the organization.
A Sponsor is the person who won’t let the change initiative die from lack of attention, and is willing to use their political capital to make the change happen
The Role model:
Behaviors and attitudes demonstrated by them are looked upon by everyone else. . Hence, they must be willing to go first.
Employees watch leaders for consistency between words and actions to see if they should believe the change is really going to happen.
The decision maker:
Leaders usually control resources such as people, budgets, and equipment, and thus have the authority to make decisions (as per their span of control) that affect the initiative.
During change, leaders must leverage their decision-making authority and choose the options that will support the initiative.
The Decision-Maker is decisive and sets priorities that support change.
The Sponsor:
Champion and advocates for the change at their level in the organization.
A Sponsor is the person who won’t let the change initiative die from lack of attention, and is willing to use their political capital to make the change happen
The Role model:
Behaviors and attitudes demonstrated by them are looked upon by everyone else. . Hence, they must be willing to go first.
Employees watch leaders for consistency between words and actions to see if they should believe the change is really going to happen.
The decision maker:
Leaders usually control resources such as people, budgets, and equipment, and thus have the authority to make decisions (as per their span of control) that affect the initiative.
During change, leaders must leverage their decision-making authority and choose the options that will support the initiative.
The Decision-Maker is decisive and sets priorities that support change.
The Sponsor:
Champion and advocates for the change at their level in the organization.
A Sponsor is the person who won’t let the change initiative die from lack of attention, and is willing to use their political capital to make the change happen
The Role model:
Behaviors and attitudes demonstrated by them are looked upon by everyone else. . Hence, they must be willing to go first.
Employees watch leaders for consistency between words and actions to see if they s
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
Let's dive deeper into the world of ODC! Ricardo Alves (OutSystems) will join us to tell all about the new Data Fabric. After that, Sezen de Bruijn (OutSystems) will get into the details on how to best design a sturdy architecture within ODC.
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Ramesh Iyer
In today's fast-changing business world, Companies that adapt and embrace new ideas often need help to keep up with the competition. However, fostering a culture of innovation takes much work. It takes vision, leadership and willingness to take risks in the right proportion. Sachin Dev Duggal, co-founder of Builder.ai, has perfected the art of this balance, creating a company culture where creativity and growth are nurtured at each stage.
Essentials of Automations: Optimizing FME Workflows with ParametersSafe Software
Are you looking to streamline your workflows and boost your projects’ efficiency? Do you find yourself searching for ways to add flexibility and control over your FME workflows? If so, you’re in the right place.
Join us for an insightful dive into the world of FME parameters, a critical element in optimizing workflow efficiency. This webinar marks the beginning of our three-part “Essentials of Automation” series. This first webinar is designed to equip you with the knowledge and skills to utilize parameters effectively: enhancing the flexibility, maintainability, and user control of your FME projects.
Here’s what you’ll gain:
- Essentials of FME Parameters: Understand the pivotal role of parameters, including Reader/Writer, Transformer, User, and FME Flow categories. Discover how they are the key to unlocking automation and optimization within your workflows.
- Practical Applications in FME Form: Delve into key user parameter types including choice, connections, and file URLs. Allow users to control how a workflow runs, making your workflows more reusable. Learn to import values and deliver the best user experience for your workflows while enhancing accuracy.
- Optimization Strategies in FME Flow: Explore the creation and strategic deployment of parameters in FME Flow, including the use of deployment and geometry parameters, to maximize workflow efficiency.
- Pro Tips for Success: Gain insights on parameterizing connections and leveraging new features like Conditional Visibility for clarity and simplicity.
We’ll wrap up with a glimpse into future webinars, followed by a Q&A session to address your specific questions surrounding this topic.
Don’t miss this opportunity to elevate your FME expertise and drive your projects to new heights of efficiency.
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualityInflectra
In this insightful webinar, Inflectra explores how artificial intelligence (AI) is transforming software development and testing. Discover how AI-powered tools are revolutionizing every stage of the software development lifecycle (SDLC), from design and prototyping to testing, deployment, and monitoring.
Learn about:
• The Future of Testing: How AI is shifting testing towards verification, analysis, and higher-level skills, while reducing repetitive tasks.
• Test Automation: How AI-powered test case generation, optimization, and self-healing tests are making testing more efficient and effective.
• Visual Testing: Explore the emerging capabilities of AI in visual testing and how it's set to revolutionize UI verification.
• Inflectra's AI Solutions: See demonstrations of Inflectra's cutting-edge AI tools like the ChatGPT plugin and Azure Open AI platform, designed to streamline your testing process.
Whether you're a developer, tester, or QA professional, this webinar will give you valuable insights into how AI is shaping the future of software delivery.
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Tobias Schneck
As AI technology is pushing into IT I was wondering myself, as an “infrastructure container kubernetes guy”, how get this fancy AI technology get managed from an infrastructure operational view? Is it possible to apply our lovely cloud native principals as well? What benefit’s both technologies could bring to each other?
Let me take this questions and provide you a short journey through existing deployment models and use cases for AI software. On practical examples, we discuss what cloud/on-premise strategy we may need for applying it to our own infrastructure to get it to work from an enterprise perspective. I want to give an overview about infrastructure requirements and technologies, what could be beneficial or limiting your AI use cases in an enterprise environment. An interactive Demo will give you some insides, what approaches I got already working for real.
UiPath Test Automation using UiPath Test Suite series, part 4DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 4. In this session, we will cover Test Manager overview along with SAP heatmap.
The UiPath Test Manager overview with SAP heatmap webinar offers a concise yet comprehensive exploration of the role of a Test Manager within SAP environments, coupled with the utilization of heatmaps for effective testing strategies.
Participants will gain insights into the responsibilities, challenges, and best practices associated with test management in SAP projects. Additionally, the webinar delves into the significance of heatmaps as a visual aid for identifying testing priorities, areas of risk, and resource allocation within SAP landscapes. Through this session, attendees can expect to enhance their understanding of test management principles while learning practical approaches to optimize testing processes in SAP environments using heatmap visualization techniques
What will you get from this session?
1. Insights into SAP testing best practices
2. Heatmap utilization for testing
3. Optimization of testing processes
4. Demo
Topics covered:
Execution from the test manager
Orchestrator execution result
Defect reporting
SAP heatmap example with demo
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
The publishing industry has been selling digital audiobooks and ebooks for over a decade and has found its groove. What’s changed? What has stayed the same? Where do we go from here? Join a group of leading sales peers from across the industry for a conversation about the lessons learned since the popularization of digital books, best practices, digital book supply chain management, and more.
Link to video recording: https://bnctechforum.ca/sessions/selling-digital-books-in-2024-insights-from-industry-leaders/
Presented by BookNet Canada on May 28, 2024, with support from the Department of Canadian Heritage.
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Jeffrey Haguewood
Sidekick Solutions uses Bonterra Impact Management (fka Social Solutions Apricot) and automation solutions to integrate data for business workflows.
We believe integration and automation are essential to user experience and the promise of efficient work through technology. Automation is the critical ingredient to realizing that full vision. We develop integration products and services for Bonterra Case Management software to support the deployment of automations for a variety of use cases.
This video focuses on the notifications, alerts, and approval requests using Slack for Bonterra Impact Management. The solutions covered in this webinar can also be deployed for Microsoft Teams.
Interested in deploying notification automations for Bonterra Impact Management? Contact us at sales@sidekicksolutionsllc.com to discuss next steps.
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Lecture 5 – Computing with Numbers (Math Lib).pptx
1. Python Programming, 3/e 1
Python Programming:
An Introduction to
Computer Science
Lecture 5 / Chapter 3 in book
Computing with Numbers
2. Python Programming, 3/e 2
Objectives
To understand the concept of data types.
To be familiar with the basic numeric data types
in Python.
To understand the fundamental principles of how
numbers are represented on a computer.
To be able to use the Python Math library.
To be able to read and write programs that
process numerical data.
3. Python Programming, 3/e 3
Numeric Data Types
The information that is stored and manipulated by
computer programs is referred to as data.
There are two different kinds of numbers!
(5, 4, 3, 6) are whole numbers – they don’t have a
fractional part
(.25, .10, .05, .01) are decimal fractions
Inside the computer, whole numbers and decimal
fractions are represented quite differently!
We say that decimal fractions and whole numbers
are two different data types.
4. Python Programming, 3/e 4
Numeric Data Types
The data type of an object determines what
values it can have and what operations can be
performed on it.
Whole numbers are represented using the
integer (int for short) data type.
These values can be positive or negative whole
numbers.
5. Python Programming, 3/e 5
Numeric Data Types
Python has a special function to tell us the
data type of any value.
>>> type(3)
<class 'int'>
>>> type(3.1)
<class 'float'>
>>> type(3.0)
<class 'float'>
>>> myInt = 32
>>> type(myInt)
<class 'int'>
>>>
6. Python Programming, 3/e 6
Numeric Data Types
Why do we need two number types?
Values that represent counts can’t be fractional
(you can’t have 3 ½ quarters)
Most mathematical algorithms are very efficient
with integers
The float type stores only an approximation to the
real number being represented!
Since floats aren’t exact, use an int whenever
possible!
8. 8
Numeric Data Types
Integer division produces a whole number.
That’s why 10//3 = 3
Think of it as ‘gozinta’, where 10//3 = 3 since 3 gozinta
(goes into) 10, 3 times (with a remainder of 1)
10%3 = 1 is the remainder of the integer division of 10
by 3.
For more info on //: https://www.pythontutorial.net/advanced-python/python-floor-division/
9. Python Programming, 3/e 9
Rounding floats
Python can also round floats, using the simple,
round() function
>>> round(7.36)
7
Lets use it on Pi! - do you know, the number of Pi?
pi = 3.141592653589793
>>> round(pi, 3)
3.142
>>> round(3.6)
4
10. Python Programming, 3/e 10
Accumulating Results: Factorial
How did we calculate 6!=6*5*4*3*2*1 ?
6*5 = 30
Take that 30, and 30 * 4 = 120
Take that 120, and 120 * 3 = 360
Take that 360, and 360 * 2 = 720
Take that 720, and 720 * 1 = 720
11. Python Programming, 3/e 11
Accumulating Results: Factorial
The general form of an accumulator
algorithm looks like this:
Initialize the accumulator variable
Loop until final result is reached
update the value of accumulator
variable
12. Python Programming, 3/e 12
Accumulating Results: Factorial
It looks like we’ll need a loop!
fact = 1
for factor in [6, 5, 4, 3, 2, 1]:
fact = fact * factor
For a random number n – we need a loop and
range accumulator to calculate n!
14. Range() method
Python Programming, 3/e 14
What does range(n) return?
0, 1, 2, 3, …, n-1
What does range(5) return? 0, 1, 2, 3, 4
range has another optional parameter!
range(start, n) returns
start, start + 1, …, n-1
But wait! There’s more!
range(start, n, step)
start, start+step, …, n-1
list(<sequence>) to make a list
15. Python Programming, 3/e 15
Accumulating Results: Factorial
Completed factorial program:
# factorial.py
# Program to compute the factorial of a number
# Illustrates for loop with an accumulator
def main():
n = eval(input("Please enter a whole number: "))
fact = 1
for factor in range(n,1,-1):
fact = fact * factor
print("The factorial of", n, "is", fact)
main()
16. Python Programming, 3/e 16
Using the Math Library
Besides (+, -, *, /, //, **, %, abs), we have
lots of other math functions available in a
math library.
A library is a module with some useful
definitions/functions.
17. Python Programming, 3/e 17
Using the Math Library
Let’s write a program to compute the roots of a
quadratic equation!
The only part of this we don’t know how to do is
find a square root… but it’s in the math library!
2
4
2
b b ac
x
a
18. Python Programming, 3/e 18
Using the Math Library
To use a library, we need to make sure this line
is in our program:
import math
Importing a library makes whatever functions are
defined within it available to the program.
19. Python Programming, 3/e 19
Using the Math Library
To access the sqrt library routine, we need to
access it as math.sqrt(x).
Using this dot notation tells Python to use the
sqrt function found in the math library module.
To calculate the root, you can do
discRoot = math.sqrt(b*b – 4*a*c)
2
4
2
b b ac
x
a
20. 20
2
4
2
b b ac
x
a
1) Let:
a= 1
b = 3
c = -4
2) Given formula 3) Plug numbers
Sqr 25 = 5
X1 = (-3 + 5)/2
X1 = 1
X2 = (-3 - 5)/2
X2 = -4
Solution 1 Solution 2
x^2 + 3x – 4 = 0 An example of a quadratic equation to try
a*x^2 + b*x + c = 0.
2
4
2
b b ac
x
a
21. Python Programming, 3/e 21
Roots of quadratic equation
# quadratic.py
# A program that computes the real roots of a quadratic equation.
# Illustrates use of the math library.
# Note: This program crashes if the equation has no real roots.
import math # Makes the math library available.
def main():
print("This program finds the real solutions to a quadratic")
print()
a, b, c = eval(input("Please enter the coefficients (a, b, c): "))
discRoot = math.sqrt(b * b - 4 * a * c)
root1 = (-b + discRoot) / (2 * a)
root2 = (-b - discRoot) / (2 * a)
print()
print("The solutions are:", root1, root2 )
22. Python Programming, 3/e 22
This program finds the real solutions to a quadratic
Please enter the coefficients (a, b, c): 3, 4, -1
The solutions are: 0.215250437022 -1.54858377035
What do you suppose this means?
This program finds the real solutions to a quadratic
Please enter the coefficients (a, b, c): 1, 2, 3
Traceback (most recent call last):
File "<pyshell#26>", line 1, in -toplevel-
main()
File "C:Documents and SettingsTerryMy DocumentsTeachingW04CS
120Textbookcodechapter3quadratic.py", line 14, in main
discRoot = math.sqrt(b * b - 4 * a * c)
ValueError: math domain error
>>>
Roots of quadratic equation
23. Python Programming, 3/e 23
Using the Math Library
If a = 1, b = 2, c = 3, then we are trying to
take the square root of a negative number!
Using the sqrt function is more efficient than
using **.
How could you use ** to calculate a square
root? /power by 0.5/
24. Using the Math Library
Python Mathematics English
pi An approximation of pi
e e An approximation of e
sqrt(x) The square root of x
sin(x) sin x The sine of x
cos(x) cos x The cosine of x
tan(x) tan x The tangent of x
asin(x) arcsin x The inverse of sine x
acos(x) arccos x The inverse of cosine x
atan(x) arctan x The inverse of tangent x
log(x) ln x The natural (base e) logarithm of x
log10(x) The common (base 10) logarithm of x
exp(x) The exponential of x
ceil(x) The smallest whole number >= x
floor(x) The largest whole number <= x
24
x
10
log x
x
e
x
x
25. Quick conversion of numbers
Type int(x) to convert x to a plain integer.
Type long(x) to convert x to a long integer.
Type float(x) to convert x to a floating-point number.
Type complex(x) to convert x to a complex number
with real part x and imaginary part zero.
Type complex(x, y) to convert x and y to a complex
number with real part x and imaginary part y. x and y
are numeric expressions
Python Programming, 3/e 25
26. Python Programming, 3/e 26
Mathematical functions (1)
abs(x) - The absolute value of x: the (positive) distance
between x and zero.
ceil(x) - The ceiling of x: the smallest integer not less than x.
cmp(x, y)
-1 if x < y, 0 if x == y, or 1 if x > y. Deprecated in Python 3.
Instead use return (x>y)-(x<y).
exp(x) - The exponential of x: e
x
fabs(x) - The absolute value of x.
floor(x) - The floor of x: the largest integer not greater than x.
log(x) - The natural logarithm of x, for x > 0.
27. Mathematical functions (2)
Python Programming, 3/e 27
log10(x) - The base-10 logarithm of x for x > 0.
max(x1, x2,...) - The largest of its arguments: the value closest to
positive infinity
min(x1, x2,...) - The smallest of its arguments: the value closest
to negative infinity.
modf(x) - The fractional and integer parts of x in a two-item
tuple. Both parts have the same sign as x. The integer part is
returned as a float.
pow(x, y) - The value of x**y.
round(x [,n]) - x rounded to n digits from the decimal point.
Python rounds away from zero as a tie-breaker: round(0.5) is 1.0
and round(-0.5) is -1.0.
sqrt(x) - The square root of x for x > 0.
28. Random number functions
Python Programming, 3/e 28
choice(seq) - A random item from a list, tuple, or string.
randrange ([start,] stop [,step]) - A randomly selected element from
range(start, stop, step).
random() - A random float r, such that 0 is less than or equal to r
and r is less than 1
seed([x]) - Sets the integer starting value used in generating random
numbers. Call this function before calling any other random module
function. Returns None.
shuffle(lst) - Randomizes the items of a list in place. Returns None.
uniform(x, y) - A random float r, such that x is less than or equal to r
and r is less than y.
29. Trigonometric functions
Python Programming, 3/e 29
acos(x) - Returns the arc cosine of x, in radians.
asin(x) - Returns the arc sine of x, in radians.
atan(x) - Returns the arc tangent of x, in radians.
atan2(y, x) - Returns atan(y / x), in radians.
cos(x) - Returns the cosine of x radians.
hypot(x, y) - Return the Euclidean norm, sqrt(x*x + y*y).
sin(x) - Return the sine of x radians.
tan(x) - Return the tangent of x radians.
degrees(x) - Converts angle x from radians to degrees.
radians(x) - Converts angle x from degrees to radians.
We have a few objectives lined up for today’s lecture and we’re touching upon a few mathematical concepts today but don’t worry, I will explain each before moving on to the next.
To understand the concept of data types, which up to now, we’ve seen a few of but today, we’re specifically looking into numerical data types which is our 2nd objective – To be familiar with the basic numeric data types in Python.
To understand the fundamental principles of how numbers are represented on a computer and how the different data types can change that.
To understand the use of a specific library called Math Lib and how we can use it to run mathematical operations such as basic operations including finding floored quotients of x and y, floored division that is, exponentiation (raising powers), dividing floats by ints and vice versa etc.
To be able to read and write programs that process numerical data and to do this, we’re going to use a simple program called quadratic.py in which we will attempt to work out a quadratic equation.
Information stored and manipulated by computer programs is called data. We’ve all heard of data and data is everywhere but the way in which we represent this data in our computer programs matters. When it comes to specifically, numerical data, we have two data types to represent it. Namely, ints and floats.
Ints are whole numbers and floats are numbers that contain decimal fractions/fractionals. Since floats have decimal fractions, it introduces incompleteness of data and it’s why we refer to floats as proximations of a real number or the result value. What I mean by this will hopefully become clear by the end of this lecture.
By now, you already know that whole numbers are represented using ints but something to bear in mind is that ints can of course, be negative numbers as well. For exmaple, -1, -2, -1200 and so on are considered whole numbers and as such, we refer to them as integers and implement them syntactically using int keyword.
When in doubt, we can use a python function called type in order to check the data type of any value.
For example, to get the data type of this numerical value (click next) we call the function type (click next) and put the value in between the parenthesis which returns its data type (click next).
As you can see, when we ask what is the data type of 3.1, the function type, returns float.
In the last line syntax input, we declared myint variable and assigned 32 to it and when we want to find out the data type of this variable, we can do the same thing, type(myint) and the type function returns the data type of the value of this variable which is int of course, as it’s 32.
The reason we need two number types is due to a number of things but primarly, we need them in order to correctly represent the values which in turn, gives us reason number 2, which is to be able to compute the different number types. In the past, the processing of ints was done very quickly and most importantly, very efficiently when compared to floats which required special arithmetic algorithms to process floats.
But really, In modern computers, the hardware and processing power of processors is so optimised that I would say, this is useless point. In fact, what’s actually very important to focus on and remember, is the fact that floats – as you can imagine– as only approximations of real numbers. there is a limit to the precision, or accuracy, of the stored values unlike the case with ints which are absolute.
So the general rule here is to only use floats if necessary. For example, working out how much change to give back requires floats but there’s no reason to use floats when working out how many people are on this session.
Operations on ints produce ints, operations on floats produce floats (except for /).
This means all mathematical operations involving ints will produce an int as a result except when there’s a division operation.
In other words,
Sum of ints is an int (click next)
Multiplication of ints is int (click next)
Floored quotient of 2 ints is an int (click next) – the double backslash indicates a floor division.
Raising an int to the power of an int will result in an int. I.e., the exponentiation of ints (click next) for example, 5 to the power of 2 is 25, 2 to the power of 5 is 32.
For those that don’t know this, raising x to a power is equivalent to multiplying x by the power. So 5 * 2 is equivalent to 5 * 5 which is 25, 2 to the power of 5 is 2*2*2*2*2, 5 times which is of course, 32 and so on.
Now, in terms of float products, you will notice that even if we only ints by ints we still get a float which is not the same for other operations such as floor division where the result depends on the initial data type. If Floored division of 2 ints such as in line 8, we get int as a product, otherwise, it’s a float as you can see in line 9. What’s a floor division you ask, well lets have a look in the next slide but first, are there any questions up to this point at all?
Ok, so what’s a floor division? So first, we need to understand the correct operator to use which the double divison or double back slash operator for floor division, as I said before. So, think about this way, how many times does 3 go into 10? The answer is 3 which is 9 and we’re left with 1, which is the remainder.
Another example, what’s 10/4?.......The correct answer is 2.5 of course with a remainder of 2. Then, what’s the floored quotient of 10 and 4, so floor division of 10 by 4?
The answer is 2 which means it returns the floor value (whole number). 10/4=2,5 <—-normal division 10//4=2 <—-floor division. For more info, I’ve attached a very useful link to learn more about floor division though this shouldn’t don’t spend too much time on this. The basics are already covered.
This floor division operator is also called integer division operator as we can use it to always produce integer result. Otherwise, we can just the regular division operator which always returns a float.
Now, let me ask you a quick question, how can we find out a remainder of a division instead? Suppose you want to find out how much is left of a given division ? The answer is to use another operator known as Modulo or Modulus Operator. This operator is denoted by the percentage symbole.
So, 10 modulo 3 is 1 as 3 goes into 10, 3 times and leaves us with 1. therefor, the correct answer is 1. Another one, what about 6%3? The division of 6/3 is = 2 and there’s no remainder. Therefor, 6 modulo 3 is 0.
Avoid-----------
What about 3%5? It’s 3 of course, because we can’t devide as 5 is bigger than 3 – the right hand side of the modulo operator is greater than the left. 2&5 is 2, 1&5 is 1 and so on.
In python, there’s a built-in function called round which can be very handy when working with numerical data types and maths operations in general.
Lets see how this works with the value of Pi but first, does anybody know what the value of Pi is ?
For those that don’t know this, It’s approx 3.14 (CLICK NEXT) but of course, since pi is an irrational number, its decimal form doesn’t end or repeat and the number of decimal places you see here is just 15 but as I said, it goes much further than this. Now, suppose you only need to know or work with the first 3 decimal places, how do you that?
The answer is to round it to the 3rd decimal place using the round function.
In python this means we use the round function with a second param to indicate the number of decimal places we want (CLICK NEXT). You can see in the second round call, we gave it a second param to specify the number of decimal places we need.
If you look closer, something very interesting took place when we called the round function the first time, notice, we gave it a float 7.36 and it returned an int. This means, we can call the round function in this simple way to actually covert a float into an int validly. The opposite of this is the type conversion you see on the right hand-side (click next).
What do you think is happening in both cases? Hint….Is it rounding, just like the round function?
The answer is no, (CLICK NEXT) it’s actually cutting off the decimal point which is also known as truncation. So it just truncates the number and return everything before the decimal point (whole number). Where’s the round function
So, two different ways of converting types but two very different results.
In order for us to use some of these function such as math.floor(number) and some other functions, we need to work with a library called Math. To use it, we have to import it to our program using python import.
If you can imagine a file or module, full of mathematical definitions and functions which we can use in an instance just by importing it to our program – we can use it in order to perform common mathematical tasks such as the one we’re about to see invovng working out the roots of a mathematical equation.
Here’s what I’m referring to.
Suppose we need to write a program that computes the roots of a quadratic equation.
Just so I know, how many of you have encountered quadratic equations or learnt about it from college ?
So, here’s the general formula to work out or in this case, compute the roots.
You’ll know, in order to this correctly, we have to find the square root. We can do this by hand by where’s the fun in that?
Lets do it syntactically. So first things first, (next page)
We will need to use our beloved math library to make our lives easier. Somebody, somewhere has already done the work for us and included this work in what’s known as the math library. To use their work, we need to import it into our program.
When we do that, whatever is contained in that library, becomes available for us to use instantly. We can import only one function (click next) from the library or the whole library or module itself (click next).
Please note - this math library comes installed in python so there’s no need for any additional installation – just import it.
Now, in order to compute the square root, we need a function called sqrt - short for square root. The math library has this routine or function which we can access by this dot notation (click next).
Dot notation is called dot notation as we use the precedent (the name of the library) dot whatever specific function we want from this library.
Now, to calculate root we can use this line discRoot = math.sqrt(b*b – 4*a*c) but where does b*b – 4 * a * c, so, where does it come from? And what is it?
The answer is that, it comes from our formula that we’ve seen before – this one (Click next) and, it’s the formula to work out the square root. We have to compute the two roots as a direct result of this formula containing the +-. First, as addition and secondly, as subtraction.
In order to program this, first let’s refresh our memory on how to do a quadratic equation
So, we have here an example, x to the power of 2 + 3 times x – 4 = 0
(Click next)
1) Since there’s no co-efficient next to x to the power of 2, we assign 1 to a.
2) The value of b is given as 3, so let b = 3 and the value of c is given as -4.
Now that we know this, we just need to plugs the numbers into the formula (click next).
Square root of 25 is 5 which is the result of the calculation of (CLICK NEXT) 3^2 – 4 * 1 * (-4). As I said we plug in the numbers 1, 3 and -4 of a, b and c into the formula that’s all.
Now, a rule to keep mind is when a square root is greater than 0, it means you will have to solutions to the quadratic equation. So we have to keep going to work out the second solution.
In order words, because the square root is 25 and 25 is greater than 0, it means our quadratic equation will have 2 solutions.
So now, we need to
Right – so now that you have refreshed your memory on how to solve quadratic equations, let’s use Python and the math library to help us work it out instead.
So, here’s the program as a whole.
We have a main function inside of which, the program will compute the real roots of a quadratic equation.
Now, a, b and c are our coefficients, and these are taken as input (click next), so the values are not known in advance. Instead, the user enters 3 numbers which we assign it to coefficients a, b and c respectively.
Once the user provides us with this information we then calculate the square root of our discriminant (click next) using the math.sqrt library to do so. (b * b - 4 * a * c) > this is our discriminant.
Once python work this out, it then needs to compute the value of each of the 2 equation roots (click next) which are the fraction denominator using the formula given and finally print the roots.
Lets see an example,
Here’s an example, 3, 4 and -1 respectively given by the user as coefficients.
The results, are given as 0.2152 etc for root 1 and -1.548 etc for root 2.
So that’s fine and understandable but look at what happens in the second instance we run the program.
In the second run, the user enters different coeffecients. So a is given as 1, b is given as 2 and c as 3.
When the user hits enter, the program crashes.
Do you have any idea why this could be ?
Try to plug in the numbers into the formula “(b * b - 4 * a * c)” (click next)
Discrimnant of (2 ^ 2 minus 4 * 1 * 3) (click next) again just plugging in numbers, gives us (4 - 12) which gives square root of -8.
Because it is impossible to compute a square root of a negative number, the equation doesn’t have roots and so the program throws the error. The square root gets calculated first and it gives us an indication as to the numbers of roots we will have. Having -8 means there are no roots as the value is negative. If instead, it was 0 then it means we have only 1 root and if it was a number greater than 0, it means we will have 2 roots.
So yeah, I’ve already covered this as it turns out but we can also compute a square root of a discriminant using powers (**). Square root can be represented as a power of 1 over 2 / 1 devided by 2 or 0.5. So instead of using square root, we take the discriminant (b * b - 4 * a * c) and raise it to the power of 0.5.
Here we have just an idea of what is included in the math library – of course, there’s more including functions on trigonometrics and many more. Whenever you want to use a function you see here or else where from the math library, remember to use the dot notation as I mentioned before.
For example, if we wanted to use floor function we need to the library name which is math dot floor and then enter the numerical value inside the parenthesis. In order for this to work, we need to have imported the math library to begin with. After all, how can we use its functions without importing it.
Notice, the sqrt function ? That’s the one we’ve just used to work out the square root.
So that’s all for today’s session – I appreciate it’s packed but I’m sure going over the recording of this lecture and practicing during the workshop will help a great deal. During the workshop, your tutor and I will explain how the quadratic equation works in more detail
Also, take a look at the last one, floor function. That’s also the one we’ve covered before but in relation to the floor division. This function returns the largest whole number that’s less than or equal to x or whatever number is inside the square brackets. For example, floor of 3.5 or 3,6 or 3,19 is 3.