SlideShare a Scribd company logo
Recap Python
programming of the
previous week
• Python script files rules: one statement per line,
each statement starting in the 1st column
• A simple program contains 3 steps: Input,
Processing, Output
• Input involves assigning values to variables. It can
be done with assignment lines (such as a = 12) or
by reading the values from the keyboard (such as a
= int(input(‘Enter the value of a:’)) ). Note that
int() and input() are Python functions.
• Processing involves operations with the variables
• Output to the black screen involves the use of the
print() function
Slides are adapted from prof Radu I Campeanu
Calculating
mathematical
expressions
• Assignment statements
• Variables/Objects
• Floating point variables
• Mathematical operators and expressions
• Using the math module
Assignment statements
• In a program, a variable is a named item, such as a, used to hold a value.
• An assignment statement assigns a value to a variable, such as a = 4.
• ‘=‘ has nothing to do with mathematics. In computer programming it means
assignment, i.e. it gives the value 4 to the variable a.
• a = b means that the value of b is copied into a; as a result both variables a and
b have the same value.
• a = a+1 means that the value of a is incremented by 1. An alternative is to write
a +=1 (the meaning of ‘+=‘ is increment by the value on the right)
Objects
• Python variables are also called objects.
• Each Python object has three properties: value, type, and identity.
- Value: A value such as 4 or "abcdef".
- Type: The type of the object, such as integer or string.
- Identity: A unique identifier that describes the object
(i.e. its address in the principal memory).
a=4
print(a) # Output: 4
print(type(a)) # Output: <class ‘int’>
print(id(a)) # Output: 140728879073924
Floating-point numbers
• Floating-point numbers are real number, like 98.6 or 0.0001.
• The built-in function float() is used for these numbers, which have decimals.
#P1 calculate hours to cover the distance
miles = float(input('Enter a distance in miles: '))
hours_to_fly = miles / 500.0 #500 miles/hour is the speed to fly
hours_to_drive = miles / 60.0 #60 miles/hour is the speed to drive
print(miles, 'miles would take:')
print(hours_to_fly, 'hours to fly')
print(hours_to_drive, 'hours to drive’)
Input/Output:
Enter a distance in miles: 450
450.0 miles would take:
0.9 hours to fly
7.5 hours to drive
Scientific notation
• Scientific notation is useful for representing floating-point numbers that are much greater
than or much less than 0, such as 6.02x1023
• 6.02x1023 is written as 6.02e23
• Float-type objects can be stored on a 32 bits (or 4 bytes) computer if their values are
between 2.3x10-308 and 1.8x10308
• Outside this interval the float-type object produces underflow/overflow.
• Ex. print(2**1024) will produce an overflow error (‘2**1024’ means 2 to the
power 1024). Note that print() accepts mathematical expressions, which are executed before
the display of the result.
Formatting floating-point output
• Some floating-point numbers have many digits after the decimal point. Ex: Irrational numbers
such as the value of Pi = 3.14159265359…
• Python has the method format() which allows the reduction of the number of decimals
#P2
pi_v = 3.141592653589793
print('Default output of Pi:', pi_v)
print('Pi reduced to 4 digits after the decimal:', end=' ')
print('{:.4f}'.format(pi_v))
Output:
Default output of Pi: 3.141592653589793
Pi reduced to 4 digits after the decimal: 3.1416
Arithmetic Expressions
• An expression is a combination of items, like variables, operators, and parentheses, that evaluates
to a value. For example: 2 * (x + 1).
• A common place where expressions are used is on the right side of an assignment statement, as in
y = 2 * (x + 1).
• The arithmetic operators are: +, -, *, /, %, **
• % is the modulo operator producing the remainder of an int division
• ** is the exponent, or power operator
• In a long expression the following precedence rules will apply:
- operations inside parentheses are executed first
- unary minus and the exponent are executed next (ex. x* -2, 2 * x**2)
- next are *,/,% in the left-to-right order
- last are +, - in the left-to-right order
Examples
• total_cost = down_payment + payment_per_month * num_months
• 24 % 10 is 4. Reason: 24 / 10 is 2 with remainder 4.
• 50 % 50 is 0. Reason: 50 / 50 is 1 with remainder 0.
• 1 % 2 is 1. Reason: 1 / 2 is 0 with remainder 1.
• 20 / 10 is 2.0 (Division with ‘/’ produces a float)
• 50 / 50 is 1.0
• 5 / 10 is 0.5
• 20//10 is 2 (‘//’ is the floored division operator; produces an int)
• print(12 - 1 / 2 * 3 % 4 + 10 / 2 * 4) produces 30.5
Example 1 - money
The program shown below shows the calculation of the number of $5 bills for a certain integer
amount. What is the output if the input is 19?
#P3
amount_to_change = int(input())
num_fives = amount_to_change // 5
num_ones = amount_to_change % 5
print('Change for $', amount_to_change)
print(num_fives, 'five dollar bill(s) and', num_ones, 'one dollar coin(s)’)
Ans:
Change for $ 19
3 five dollar bill(s) and 4 one dollar coin(s)
Example 2 - time
The program shown below extracts the number of hours from an input of minutes. What will be
the output for 275 ?
#P4
minutes = int(input('Enter minutes:'))
hours = minutes // 60
minutes_remaining = minutes % 60
print(minutes, 'minutes is', end=' ')
print(hours, 'hours and', end=' ')
print(minutes_remaining, 'minutes.n', end=' ‘)
Input/Output
Enter minutes: 275
275 minutes is 4 hours and 35 minutes
Digits in an integer
The last digit in 23 is obtained by: 23%10
The last 3 digits in 1234 are obtained by:
1234%1000
The first digit in 23 is obtained by: 23//10
The first digit in 1234 is obtained by: 1234//1000
Example 3 - Telephone
number
#P5
nr = int(input('Enter a 10 digit integer:'))
tmp = nr // 10000 #tmp will have the value 103458
mid = tmp % 1000 #mid will have the value 458
first = nr // 10000000 #first will have the value 103
last = nr % 10000 #last will have the value 8231
print('(',first,') ',mid,'-',last) #notice the brackets and -
Input/Output:
Enter a 10 digit integer: 1034588231
( 103 ) 458 - 8231
Using modules
• Programmers often write code in more than just a single script file. Collections of logically
related code can be stored in separate files, and then imported for use into a script that
requires that code.
• A module is a file containing Python code that can be used by other modules or scripts.
• A module is made available for use via the import statement.
• Once a module is imported, any object defined in that module can be accessed using dot
notation.
• Python comes with a number of predefined modules, such as math and random.
Using the random module
• Python has a randrange() function as part of the module random. This function creates a
random integer between the function parameters.
import random
print(random.randrange(1,10)) # the dot notation
Output:
6 # a random number between 1 and 10
• An alternative is:
from random import randrange
print(randrange(1,10))
Output:
8 # another random number between 1 and 10
Equation Solutions using the
math module
The solutions for the equation ax2 + bx + c = 0 are:
𝑥1 =
−𝑏 + 𝑑
2𝑎
and 𝑥2 =
−𝑏 − 𝑑
2𝑎
, where d = b2 - 4ac
Write a Python program which enters from the keyboard the values of a, b, c (as integers) and then calculates and
shows x1 and x2.
#P6
import math
a = int(input('Enter the value of a:'))
b = int(input('Enter the value of b:'))
c = int(input('Enter the value of c:'))
d = b*b - 4*a*c;
x1 = (-b + math.sqrt(d))/2/a
x2 = (-b – math.sqrt(d))/2/a
print('x1=', x1)
print('x2=', x2)
Using the math module
Given three floating-point numbers x, y, and z, output x to the power of z, x to the power of (y to the power of z), the
absolute value of (x minus y), and the square root of (x to the power of z).
#P7
import math
x=float(input()) # enter 5.0
y=float(input()) # enter 1.5
z=float(input()) # enter 3.2
v1=x**z
v2=x**(y**z)
v3=math.fabs(x-y)
v4=math.sqrt(x**z)
print('{:.2f} {:.2f} {:.2f} {:.2f}'.format(v1,v2,v3,v4))
Output:
172.47 361.66 3.50 13.13
Using the random module
• Write a Python program which rolls two dice. This program should use the module random.
#P8
import random
a = random.randrange(1,6)
b = random.randrange(1,6)
print(‘the sum is ‘, a+b)
Possible Output:
the sum is 10
Using Constants in Python
• Constants are variables which have values that cannot be changed during the execution of the program
• In other programming languages such as C constants are written in capital letters. In Java one uses the reserved
word final in front of the constant to ensure that its value cannot be changed.
• Python does not have a way to enforce that the value of a constant is not changed. A good method to signal that
certain variables are constants is to create a constants module.
Creating and using the constants module
The time of a free falling object from a certain height is given by the following
formula: time = (2 ∗ height / g), where g is the gravitational constant.
In this program let us compare the times for falls on Earth and Mars.
constants.py # user defined module
# Gravitational constants for various planets
earth_g = 9.81 # m/s**2
mars_g = 3.71
========================================================
fall_time.py
#P9
# Find seconds to drop from a height on some planets.
import constants
import math # module available in Python
height = int(input('Height in meters: ')) # Meters from planet
print('Earth:', math.sqrt(2 * height / constants.earth_g), 'seconds')
print('Mars:', math.sqrt(2 * height / constants.mars_g), 'seconds’)
# notice the dot notation for functions and constants
Class exercise - Distance
between two points
The distance between point (x1, y1) and point (x2, y2) is given by the formula:
(x2 − x1)∗∗2 + (y2 − y1)∗∗2 .
All these variables have floating - point numbers.
Write a Python program which reads the coordinates of the 2 points and shows the value of
the distance, shown as a floating – point number with 3 decimals.
For example if the 4 numbers entered are 1.1, 2.2, 4.4 and 5.5
The output should be: Points distance: 4.667
Class exercise - Solution
import math
x1 = float(input('Enter x1:'))
y1 = float(input('Enter y1:'))
x2 = float(input('Enter x2:'))
y2 = float(input('Enter y2:'))
point_dist = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
print('Points distance: {:.3f}'.format(point_dist))

More Related Content

Similar to introduction to python programming course 2 (20)

Operators1.pptx
Operators1.pptxOperators1.pptx
Operators1.pptx
HARSHSHARMA840
 
Ch03
Ch03Ch03
Ch03
Arriz San Juan
 
Unit2 input output
Unit2 input outputUnit2 input output
Unit2 input output
deepak kumbhar
 
Functions IN CPROGRAMMING OF ENGINEERING.pptx
Functions IN CPROGRAMMING OF ENGINEERING.pptxFunctions IN CPROGRAMMING OF ENGINEERING.pptx
Functions IN CPROGRAMMING OF ENGINEERING.pptx
vanshhans21102005
 
lecture 2.pptx
lecture 2.pptxlecture 2.pptx
lecture 2.pptx
Anonymous9etQKwW
 
Java Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type ConversionJava Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type Conversion
Svetlin Nakov
 
C++ Language
C++ LanguageC++ Language
C++ Language
Syed Zaid Irshad
 
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
 
unit_2 (1).pptx
unit_2 (1).pptxunit_2 (1).pptx
unit_2 (1).pptx
JVenkateshGoud
 
Operators
OperatorsOperators
Operators
Krishna Kumar Pankaj
 
Each n Every topic of C Programming.pptx
Each n Every topic of C Programming.pptxEach n Every topic of C Programming.pptx
Each n Every topic of C Programming.pptx
snnbarot
 
C important questions
C important questionsC important questions
C important questions
JYOTI RANJAN PAL
 
PPS 6.6.FUNCTION INTRODUCTION & WRITING FUNCTIONS, SCOPE OF VARIABLES FUNCTIONS
PPS 6.6.FUNCTION INTRODUCTION & WRITING FUNCTIONS, SCOPE OF VARIABLES FUNCTIONSPPS 6.6.FUNCTION INTRODUCTION & WRITING FUNCTIONS, SCOPE OF VARIABLES FUNCTIONS
PPS 6.6.FUNCTION INTRODUCTION & WRITING FUNCTIONS, SCOPE OF VARIABLES FUNCTIONS
Sitamarhi Institute of Technology
 
Problem solving using computers - Unit 1 - Study material
Problem solving using computers - Unit 1 - Study materialProblem solving using computers - Unit 1 - Study material
Problem solving using computers - Unit 1 - Study material
To Sum It Up
 
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
 
MODULE. .pptx
MODULE.                              .pptxMODULE.                              .pptx
MODULE. .pptx
Alpha337901
 
Functions struct&union
Functions struct&unionFunctions struct&union
Functions struct&union
UMA PARAMESWARI
 
Functions
FunctionsFunctions
Functions
Swarup Boro
 
object oriented programming presentation
object oriented programming presentationobject oriented programming presentation
object oriented programming presentation
Mahesh_gmail_KNL Na
 
PPt Revision of the basics of python1.pptx
PPt Revision of the basics of python1.pptxPPt Revision of the basics of python1.pptx
PPt Revision of the basics of python1.pptx
tcsonline1222
 
Functions IN CPROGRAMMING OF ENGINEERING.pptx
Functions IN CPROGRAMMING OF ENGINEERING.pptxFunctions IN CPROGRAMMING OF ENGINEERING.pptx
Functions IN CPROGRAMMING OF ENGINEERING.pptx
vanshhans21102005
 
Java Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type ConversionJava Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type Conversion
Svetlin Nakov
 
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
 
Each n Every topic of C Programming.pptx
Each n Every topic of C Programming.pptxEach n Every topic of C Programming.pptx
Each n Every topic of C Programming.pptx
snnbarot
 
PPS 6.6.FUNCTION INTRODUCTION & WRITING FUNCTIONS, SCOPE OF VARIABLES FUNCTIONS
PPS 6.6.FUNCTION INTRODUCTION & WRITING FUNCTIONS, SCOPE OF VARIABLES FUNCTIONSPPS 6.6.FUNCTION INTRODUCTION & WRITING FUNCTIONS, SCOPE OF VARIABLES FUNCTIONS
PPS 6.6.FUNCTION INTRODUCTION & WRITING FUNCTIONS, SCOPE OF VARIABLES FUNCTIONS
Sitamarhi Institute of Technology
 
Problem solving using computers - Unit 1 - Study material
Problem solving using computers - Unit 1 - Study materialProblem solving using computers - Unit 1 - Study material
Problem solving using computers - Unit 1 - Study material
To Sum It Up
 
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
 
object oriented programming presentation
object oriented programming presentationobject oriented programming presentation
object oriented programming presentation
Mahesh_gmail_KNL Na
 
PPt Revision of the basics of python1.pptx
PPt Revision of the basics of python1.pptxPPt Revision of the basics of python1.pptx
PPt Revision of the basics of python1.pptx
tcsonline1222
 

Recently uploaded (20)

Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
EduSkills OECD
 
Capitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptxCapitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptx
CapitolTechU
 
IDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptxIDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptx
ArneeAgligar
 
Rai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptx
Rai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptxRai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptx
Rai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptx
Dr. Ravi Shankar Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.
jmansha170
 
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
parmarjuli1412
 
Ray Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big CycleRay Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big Cycle
Dadang Solihin
 
What are the benefits that dance brings?
What are the benefits that dance brings?What are the benefits that dance brings?
What are the benefits that dance brings?
memi27
 
TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025
TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025
TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025
Quiz Club of PSG College of Arts & Science
 
Pfeiffer "Secrets to Changing Behavior in Scholarly Communication: A 2025 NIS...
Pfeiffer "Secrets to Changing Behavior in Scholarly Communication: A 2025 NIS...Pfeiffer "Secrets to Changing Behavior in Scholarly Communication: A 2025 NIS...
Pfeiffer "Secrets to Changing Behavior in Scholarly Communication: A 2025 NIS...
National Information Standards Organization (NISO)
 
LDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad UpdatesLDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad Updates
LDM & Mia eStudios
 
How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18
Celine George
 
How to Create an Event in Odoo 18 - Odoo 18 Slides
How to Create an Event in Odoo 18 - Odoo 18 SlidesHow to Create an Event in Odoo 18 - Odoo 18 Slides
How to Create an Event in Odoo 18 - Odoo 18 Slides
Celine George
 
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti MpdBasic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Restu Bias Primandhika
 
How to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 SalesHow to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 Sales
Celine George
 
Allomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdfAllomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdf
Abha Pandey
 
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition OecdEnergy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
razelitouali
 
Unit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdfUnit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdf
KRUTIKA CHANNE
 
Unit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptxUnit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptx
bobby205207
 
How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18
Celine George
 
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
EduSkills OECD
 
Capitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptxCapitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptx
CapitolTechU
 
IDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptxIDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptx
ArneeAgligar
 
Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.
jmansha170
 
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
parmarjuli1412
 
Ray Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big CycleRay Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big Cycle
Dadang Solihin
 
What are the benefits that dance brings?
What are the benefits that dance brings?What are the benefits that dance brings?
What are the benefits that dance brings?
memi27
 
LDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad UpdatesLDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad Updates
LDM & Mia eStudios
 
How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18
Celine George
 
How to Create an Event in Odoo 18 - Odoo 18 Slides
How to Create an Event in Odoo 18 - Odoo 18 SlidesHow to Create an Event in Odoo 18 - Odoo 18 Slides
How to Create an Event in Odoo 18 - Odoo 18 Slides
Celine George
 
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti MpdBasic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Restu Bias Primandhika
 
How to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 SalesHow to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 Sales
Celine George
 
Allomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdfAllomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdf
Abha Pandey
 
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition OecdEnergy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
razelitouali
 
Unit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdfUnit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdf
KRUTIKA CHANNE
 
Unit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptxUnit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptx
bobby205207
 
How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18
Celine George
 
Ad

introduction to python programming course 2

  • 1. Recap Python programming of the previous week • Python script files rules: one statement per line, each statement starting in the 1st column • A simple program contains 3 steps: Input, Processing, Output • Input involves assigning values to variables. It can be done with assignment lines (such as a = 12) or by reading the values from the keyboard (such as a = int(input(‘Enter the value of a:’)) ). Note that int() and input() are Python functions. • Processing involves operations with the variables • Output to the black screen involves the use of the print() function Slides are adapted from prof Radu I Campeanu
  • 2. Calculating mathematical expressions • Assignment statements • Variables/Objects • Floating point variables • Mathematical operators and expressions • Using the math module
  • 3. Assignment statements • In a program, a variable is a named item, such as a, used to hold a value. • An assignment statement assigns a value to a variable, such as a = 4. • ‘=‘ has nothing to do with mathematics. In computer programming it means assignment, i.e. it gives the value 4 to the variable a. • a = b means that the value of b is copied into a; as a result both variables a and b have the same value. • a = a+1 means that the value of a is incremented by 1. An alternative is to write a +=1 (the meaning of ‘+=‘ is increment by the value on the right)
  • 4. Objects • Python variables are also called objects. • Each Python object has three properties: value, type, and identity. - Value: A value such as 4 or "abcdef". - Type: The type of the object, such as integer or string. - Identity: A unique identifier that describes the object (i.e. its address in the principal memory). a=4 print(a) # Output: 4 print(type(a)) # Output: <class ‘int’> print(id(a)) # Output: 140728879073924
  • 5. Floating-point numbers • Floating-point numbers are real number, like 98.6 or 0.0001. • The built-in function float() is used for these numbers, which have decimals. #P1 calculate hours to cover the distance miles = float(input('Enter a distance in miles: ')) hours_to_fly = miles / 500.0 #500 miles/hour is the speed to fly hours_to_drive = miles / 60.0 #60 miles/hour is the speed to drive print(miles, 'miles would take:') print(hours_to_fly, 'hours to fly') print(hours_to_drive, 'hours to drive’) Input/Output: Enter a distance in miles: 450 450.0 miles would take: 0.9 hours to fly 7.5 hours to drive
  • 6. Scientific notation • Scientific notation is useful for representing floating-point numbers that are much greater than or much less than 0, such as 6.02x1023 • 6.02x1023 is written as 6.02e23 • Float-type objects can be stored on a 32 bits (or 4 bytes) computer if their values are between 2.3x10-308 and 1.8x10308 • Outside this interval the float-type object produces underflow/overflow. • Ex. print(2**1024) will produce an overflow error (‘2**1024’ means 2 to the power 1024). Note that print() accepts mathematical expressions, which are executed before the display of the result.
  • 7. Formatting floating-point output • Some floating-point numbers have many digits after the decimal point. Ex: Irrational numbers such as the value of Pi = 3.14159265359… • Python has the method format() which allows the reduction of the number of decimals #P2 pi_v = 3.141592653589793 print('Default output of Pi:', pi_v) print('Pi reduced to 4 digits after the decimal:', end=' ') print('{:.4f}'.format(pi_v)) Output: Default output of Pi: 3.141592653589793 Pi reduced to 4 digits after the decimal: 3.1416
  • 8. Arithmetic Expressions • An expression is a combination of items, like variables, operators, and parentheses, that evaluates to a value. For example: 2 * (x + 1). • A common place where expressions are used is on the right side of an assignment statement, as in y = 2 * (x + 1). • The arithmetic operators are: +, -, *, /, %, ** • % is the modulo operator producing the remainder of an int division • ** is the exponent, or power operator • In a long expression the following precedence rules will apply: - operations inside parentheses are executed first - unary minus and the exponent are executed next (ex. x* -2, 2 * x**2) - next are *,/,% in the left-to-right order - last are +, - in the left-to-right order
  • 9. Examples • total_cost = down_payment + payment_per_month * num_months • 24 % 10 is 4. Reason: 24 / 10 is 2 with remainder 4. • 50 % 50 is 0. Reason: 50 / 50 is 1 with remainder 0. • 1 % 2 is 1. Reason: 1 / 2 is 0 with remainder 1. • 20 / 10 is 2.0 (Division with ‘/’ produces a float) • 50 / 50 is 1.0 • 5 / 10 is 0.5 • 20//10 is 2 (‘//’ is the floored division operator; produces an int) • print(12 - 1 / 2 * 3 % 4 + 10 / 2 * 4) produces 30.5
  • 10. Example 1 - money The program shown below shows the calculation of the number of $5 bills for a certain integer amount. What is the output if the input is 19? #P3 amount_to_change = int(input()) num_fives = amount_to_change // 5 num_ones = amount_to_change % 5 print('Change for $', amount_to_change) print(num_fives, 'five dollar bill(s) and', num_ones, 'one dollar coin(s)’) Ans: Change for $ 19 3 five dollar bill(s) and 4 one dollar coin(s)
  • 11. Example 2 - time The program shown below extracts the number of hours from an input of minutes. What will be the output for 275 ? #P4 minutes = int(input('Enter minutes:')) hours = minutes // 60 minutes_remaining = minutes % 60 print(minutes, 'minutes is', end=' ') print(hours, 'hours and', end=' ') print(minutes_remaining, 'minutes.n', end=' ‘) Input/Output Enter minutes: 275 275 minutes is 4 hours and 35 minutes
  • 12. Digits in an integer The last digit in 23 is obtained by: 23%10 The last 3 digits in 1234 are obtained by: 1234%1000 The first digit in 23 is obtained by: 23//10 The first digit in 1234 is obtained by: 1234//1000
  • 13. Example 3 - Telephone number #P5 nr = int(input('Enter a 10 digit integer:')) tmp = nr // 10000 #tmp will have the value 103458 mid = tmp % 1000 #mid will have the value 458 first = nr // 10000000 #first will have the value 103 last = nr % 10000 #last will have the value 8231 print('(',first,') ',mid,'-',last) #notice the brackets and - Input/Output: Enter a 10 digit integer: 1034588231 ( 103 ) 458 - 8231
  • 14. Using modules • Programmers often write code in more than just a single script file. Collections of logically related code can be stored in separate files, and then imported for use into a script that requires that code. • A module is a file containing Python code that can be used by other modules or scripts. • A module is made available for use via the import statement. • Once a module is imported, any object defined in that module can be accessed using dot notation. • Python comes with a number of predefined modules, such as math and random.
  • 15. Using the random module • Python has a randrange() function as part of the module random. This function creates a random integer between the function parameters. import random print(random.randrange(1,10)) # the dot notation Output: 6 # a random number between 1 and 10 • An alternative is: from random import randrange print(randrange(1,10)) Output: 8 # another random number between 1 and 10
  • 16. Equation Solutions using the math module The solutions for the equation ax2 + bx + c = 0 are: 𝑥1 = −𝑏 + 𝑑 2𝑎 and 𝑥2 = −𝑏 − 𝑑 2𝑎 , where d = b2 - 4ac Write a Python program which enters from the keyboard the values of a, b, c (as integers) and then calculates and shows x1 and x2. #P6 import math a = int(input('Enter the value of a:')) b = int(input('Enter the value of b:')) c = int(input('Enter the value of c:')) d = b*b - 4*a*c; x1 = (-b + math.sqrt(d))/2/a x2 = (-b – math.sqrt(d))/2/a print('x1=', x1) print('x2=', x2)
  • 17. Using the math module Given three floating-point numbers x, y, and z, output x to the power of z, x to the power of (y to the power of z), the absolute value of (x minus y), and the square root of (x to the power of z). #P7 import math x=float(input()) # enter 5.0 y=float(input()) # enter 1.5 z=float(input()) # enter 3.2 v1=x**z v2=x**(y**z) v3=math.fabs(x-y) v4=math.sqrt(x**z) print('{:.2f} {:.2f} {:.2f} {:.2f}'.format(v1,v2,v3,v4)) Output: 172.47 361.66 3.50 13.13
  • 18. Using the random module • Write a Python program which rolls two dice. This program should use the module random. #P8 import random a = random.randrange(1,6) b = random.randrange(1,6) print(‘the sum is ‘, a+b) Possible Output: the sum is 10
  • 19. Using Constants in Python • Constants are variables which have values that cannot be changed during the execution of the program • In other programming languages such as C constants are written in capital letters. In Java one uses the reserved word final in front of the constant to ensure that its value cannot be changed. • Python does not have a way to enforce that the value of a constant is not changed. A good method to signal that certain variables are constants is to create a constants module.
  • 20. Creating and using the constants module The time of a free falling object from a certain height is given by the following formula: time = (2 ∗ height / g), where g is the gravitational constant. In this program let us compare the times for falls on Earth and Mars. constants.py # user defined module # Gravitational constants for various planets earth_g = 9.81 # m/s**2 mars_g = 3.71 ======================================================== fall_time.py #P9 # Find seconds to drop from a height on some planets. import constants import math # module available in Python height = int(input('Height in meters: ')) # Meters from planet print('Earth:', math.sqrt(2 * height / constants.earth_g), 'seconds') print('Mars:', math.sqrt(2 * height / constants.mars_g), 'seconds’) # notice the dot notation for functions and constants
  • 21. Class exercise - Distance between two points The distance between point (x1, y1) and point (x2, y2) is given by the formula: (x2 − x1)∗∗2 + (y2 − y1)∗∗2 . All these variables have floating - point numbers. Write a Python program which reads the coordinates of the 2 points and shows the value of the distance, shown as a floating – point number with 3 decimals. For example if the 4 numbers entered are 1.1, 2.2, 4.4 and 5.5 The output should be: Points distance: 4.667
  • 22. Class exercise - Solution import math x1 = float(input('Enter x1:')) y1 = float(input('Enter y1:')) x2 = float(input('Enter x2:')) y2 = float(input('Enter y2:')) point_dist = math.sqrt((x2 - x1)**2 + (y2 - y1)**2) print('Points distance: {:.3f}'.format(point_dist))