Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

Python CHP 8 Ex Full

Python chapter 8

Uploaded by

hamzamughal1549
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Python CHP 8 Ex Full

Python chapter 8

Uploaded by

hamzamughal1549
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

5.

1
1 A company pays its employee's weekly according to their hourly
wage up to 40 hours and 50% more for the overtime. Write a program
that uses a while statement to receive values of " hourly _ rate " and "
hourly _ worked " for an arbitrary number of employees and finds and
print's the gross pay for each employee.

Input

while True:
# Get input values from user
hourly_rate = float(input("Enter hourly rate (or -1 to quit): "))

# Exit the loop if user enters -1


if hourly_rate == -1:
break

hourly_worked = float(input("Enter hours worked: "))

# Calculate gross pay for employee


if hourly_worked <= 40:
gross_pay = hourly_worked * hourly_rate
else:
overtime_hours = hourly_worked - 40
gross_pay = 40 * hourly_rate + overtime_hours * hourly_rate *
1.5

# Print the gross pay for the employee


print("Gross pay: $", round(gross_pay, 2))
Here's how the program works:

The while loop continues until the user enters -1 as the hourly rate.
Inside the loop, the program asks the user for the hourly rate and
hours worked for the employee.
The program then calculates the gross pay for the employee using the
formula provided: regular pay for up to 40 hours plus 50% more for
any hours over 40.
The round() function is used to round the gross pay to 2 decimal places.
Finally, the program prints the gross pay for the employee.
You can run this program in a Python environment or save it as a .py
file and run it from the command line.

5.3

A large company pays its salespeople on a commission basis . The


salespeople each receive " fixed - pay " per week plus 9% of their
gross sales for that week . For example, a salesperson has fixed - pay
of Rs.2000 who sells Rs.5000 worth of product's in a week revives
Rs.2000 plus 9% of Rs.5000 ,or total of Rs. 2450. Write a program that
revices value's of " fixed-pay" and " gross sales" for last week form
each salespeople and finds and print's the gross pay for each pay of
the salespeople.

Input

while True:
# Get input values from user
fixed_pay = float(input("Enter fixed pay (or -1 to quit): "))

# Exit the loop if user enters -1


if fixed_pay == -1:
break

gross_sales = float(input("Enter gross sales: "))

# Calculate gross pay for salesperson


gross_pay = fixed_pay + (0.09 * gross_sales)

# Print the gross pay for the salesperson


print("Gross pay: Rs.", round(gross_pay, 2))

Here's how the program works:

The while loop continues until the user enters -1 as the fixed pay.
Inside the loop, the program asks the user for the fixed pay and
gross sales for the salesperson.
The program then calculates the gross pay for the salesperson using
the formula provided: fixed pay plus 9% of gross sales.
The round() function is used to round the gross pay to 2 decimal
places.
Finally, the program prints the gross pay for the salesperson.
You can run this program in a Python environment or save it as a
.py file and run it from the command line.

5.6
write a program for the secant method for solving the non linear
equation: f(x) = 4x + sinx-e'x with intial two roots x not =0 and x1= 1 .
The iterations of the method should stop/ terminate when a certain
tolerance/ convergence level is achieved or maximum number of
iterations are performed (whichever happens first)
Input

import math

# Define the function to be solved


def f(x):
return 4*x + math.sin(x) - math.exp(x)

# Define the secant method function


def secant_method(x0, x1, tol, max_iter):
# Initialize variables
iter_count = 0
# Loop until tolerance or maximum number of iterations is
reached
while iter_count < max_iter:
# Calculate the next approximation of the root using secant
method
x_next = x1 - (f(x1) * (x1 - x0)) / (f(x1) - f(x0))

# Check if the tolerance is achieved


if abs(x_next - x1) < tol:
print("Root found:", x_next)
return x_next

# Update variables for next iteration


iter_count += 1
x0 = x1
x1 = x_next

# Maximum number of iterations reached


print("Maximum number of iterations reached.")
return None

# Set initial values and call the secant method function


x0 = 0.5
x1 = 1.0
tol = 1e-6
max_iter = 1000
secant_method(x0, x1, tol, max_iter)

Here's how the program works:

The f(x) function defines the non-linear equation to be solved.


The secant_method(x0, x1, tol, max_iter) function implements the
secant method. It takes four arguments: the initial two roots x0 and
x1, the tolerance tol, and the maximum number of iterations
max_iter.
Inside the secant_method function, a while loop is used to repeatedly
calculate the next approximation of the root using the secant method
until the tolerance or maximum number of iterations is reached.
The abs(x_next - x1) < tol condition checks if the tolerance is
achieved. If it is, the program prints the root found and returns it.
If the maximum number of iterations is reached, the program prints
a message and returns None.
Finally, the x0, x1, tol, and max_iter values are set, and the
secant_method function is called with these values.
You can run this program in a Python environment or save it as a
.py file and run it from the command line. Note that the initial two
roots x0 and x1 should not be equal to 0 to avoid division by zero in
the secant method.

5.5

write a program for the Newton's method for solving the non linear
equation: f(x) = 4x+sinx-e'x=0 with initial root x not = 1 the iterations
of the method should stop / terminate when a certain tolerance/
convergence level is achieved or a maximum number of iterations are
performed ( whichever happens first )

Input
import math

# Define the function to be solved


def f(x):
return 4*x + math.sin(x) - math.exp(x)

# Define the derivative of the function


def f_prime(x):
return 4 + math.cos(x) - math.exp(x)

# Define the Newton's method function


def newton_method(x0, tol, max_iter):
# Initialize variables
iter_count = 0

# Loop until tolerance or maximum number of iterations is


reached
while iter_count < max_iter:
# Calculate the next approximation of the root using Newton's
method
x_next = x0 - f(x0) / f_prime(x0)

# Check if the tolerance is achieved


if abs(x_next - x0) < tol:
print("Root found:", x_next)
return x_next

# Update variables for next iteration


iter_count += 1
x0 = x_next

# Maximum number of iterations reached


print("Maximum number of iterations reached.")
return None
# Set initial values and call the Newton's method function
x0 = 2.0
tol = 1e-6
max_iter = 1000
newton_method(x0, tol, max_iter)

Here's how the program works:

The f(x) function defines the non-linear equation to be solved.


The f_prime(x) function defines the derivative of the function.
The newton_method(x0, tol, max_iter) function implements the
Newton's method. It takes three arguments: the initial root x0, the
tolerance tol, and the maximum number of iterations max_iter.
Inside the newton_method function, a while loop is used to
repeatedly calculate the next approximation of the root using
Newton's method until the tolerance or maximum number of
iterations is reached.
The abs(x_next - x0) < tol condition checks if the tolerance is
achieved. If it is, the program prints the root found and returns it.
If the maximum number of iterations is reached, the program prints
a message and returns None.
Finally, the x0, tol, and max_iter values are set, and the
newton_method function is called with these values.
You can run this program in a Python environment or save it as a
.py file and run it from the command line. Note that the initial root
x0 should not be equal to 1 to avoid division by zero in the Newton's
method.
5.4
X not = 1 the iterations of the method should stop/ terminate when a
given number of iterations are completed.

Input

import math

# Define the function to be solved


def f(x):
return 4*x + math.sin(x) - math.exp(x)

# Define the derivative of the function


def f_prime(x):
return 4 + math.cos(x) - math.exp(x)

# Define the Newton's method function with a maximum number of


iterations
def newton_method(x0, num_iter):
# Initialize variables
iter_count = 0

# Loop for a given number of iterations


while iter_count < num_iter:
# Calculate the next approximation of the root using Newton's
method
x_next = x0 - f(x0) / f_prime(x0)

# Update variables for next iteration


iter_count += 1
x0 = x_next
# Print the final approximation of the root
print("Root found:", x0)

# Set initial values and call the Newton's method function


x0 = 2.0
num_iter = 10
newton_method(x0, num_iter)

Here's how the program works:

The f(x) function defines the non-linear equation to be solved.


The f_prime(x) function defines the derivative of the function.
The newton_method(x0, num_iter) function implements the
Newton's method. It takes two arguments: the initial root x0 and the
number of iterations num_iter.
Inside the newton_method function, a while loop is used to
repeatedly calculate the next approximation of the root using
Newton's method for a given number of iterations.
The final approximation of the root is printed after the loop is
completed.
Finally, the x0 and num_iter values are set, and the newton_method
function is called with these values.
You can run this program in a Python environment or save it as a
.py file and run it from the command line. Note that the initial root
x0 should not be equal to 1 to avoid division by zero in the Newton's
method. Also, the number of iterations should be chosen carefully to
balance between computational time and accuracy.
5.2
An electric power supply company charges its residential consumer's
for the electricity unit's according to the tariff as below : Rs.7.74 per
unit ( kW/hour) for the first 100 unit's, Rs. 10.06 per unit KW / hour)
for next 100 unit's ( i.e., unit's from 101 to 200) ,Rs.12.15 per unit
kW/hour) for the next 100 unit's ( i.e., units from 201 to 300 ) , Rs.
19.55 per unit (kW/hour) for the next 400 unit's ( i.e.,units from 301 to
700) and Rs.22.65 per unit for rest of the units ( i.e.,units after 700 )
write a program that asks the user to enter the number of unit's
consumed and finds the electricity charge's for an arbitrary number of
consumers .

Input

# Define the tariff rates


rate_1 = 7.74 # Rs. per unit for first 100 units
rate_2 = 10.06 # Rs. per unit for next 100 units
rate_3 = 12.15 # Rs. per unit for next 100 units
rate_4 = 19.55 # Rs. per unit for next 400 units
rate_5 = 22.65 # Rs. per unit for units after 700

# Define a function to calculate the electricity charges


def calculate_charges(units):
if units <= 100:
return units * rate_1
elif units <= 200:
return 100 * rate_1 + (units - 100) * rate_2
elif units <= 300:
return 100 * rate_1 + 100 * rate_2 + (units - 200) * rate_3
elif units <= 700:
return 100 * rate_1 + 100 * rate_2 + 100 * rate_3 + (units - 300)
* rate_4
else:
return 100 * rate_1 + 100 * rate_2 + 100 * rate_3 + 400 * rate_4
+ (units - 700) * rate_5

# Define a while loop to ask for units consumed for each customer
while True:
# Ask the user for input
units = input("Enter the number of units consumed (or 'q' to
quit): ")

# Check if the user wants to quit


if units.lower() == 'q':
break

# Convert the input to a float


units = float(units)

# Calculate the electricity charges


charges = calculate_charges(units)

# Print the charges for this customer


print("Electricity charges: Rs.", charges)

Here's how the program works:


 The tariff rates are defined as constants at the beginning of the
program.
 The calculate_charges(units) function takes the number of
units consumed as input and calculates the corresponding
electricity charges based on the given tariff.
 A while loop is used to repeatedly ask for the number of units
consumed for an arbitrary number of customers.
 Inside the loop, the user is prompted to enter the number of
units consumed.
 If the user enters 'q', the loop breaks and the program exits.
 Otherwise, the input is converted to a float and passed to the
calculate_charges function to calculate the charges.
 The charges for the current customer are printed to the
console.
You can run this program in a Python environment or save it as a
.py file and run it from the command line.

You might also like