CP-Post Mid
CP-Post Mid
P O S T - M I D
Sleep Debt
A “sleep debt” represents the difference between a person’s desirable and actual amount of sleep.
Write a program that prompts the user to enter how many hours they slept each day over a period
of seven days. Using 8 hours per day as the desirable amount of sleep, determine their sleep debt
by calculating the total hours of sleep they got over the seven-day period and subtracting that
from the total hours of sleep they should have got. If the user does not have a sleep debt, display
a message expressing your jealousy.
# initialize variables
total_sleep = 0
desirable_sleep = 8 * 7 # 8 hours per day over 7 days
sleep_debt = 0
# prompt user to enter hours of sleep for seven days
for i in range(7):
hours = int(input("Enter hours of sleep for day {}: ".format(i+1)))
total_sleep += hours
# calculate sleep debt
sleep_debt = desirable_sleep - total_sleep
# display results
if sleep_debt <= 0:
print("You do not have a sleep debt. I'm jealous!")
else:
print("Your sleep debt is {} hours.".format(sleep_debt))
Factorial
In mathematics, the notation n! represents the factorial of the nonnegative integer n. The factorial
of n is the product of all the nonnegative integers from 1 to n. For example,
7! = 1 x 2 x 3 x 4 x 5 x 6 x 7 = 5,040
Write a program that lets the user enter a nonnegative integer then uses a loop to calculate the
factorial of that number. Display the factorial.
n=int(input("Enter number:"))
fact=1
while(n>0):
fact=fact*n
n=n-1
print("Factorial of the number is: ", fact)
Fibonacci Series
Write a Python program to display Fibonacci numbers up to 20.
# initialize variables
a, b = 0, 1
# loop while a is less than or equal to 20
while a <= 20:
# print the current Fibonacci number followed by a tab
print(a, end='\t')
# update the values of a and b
a, b = b, a + b
Range Function
The program below uses the range function with a for loop to display “I love Pakistan” five
times.
# This program demonstrates how the range function can be used with a
for loop.
# Print a message five times.
for x in range(5):
print('I love Pakistan')
Examples
Write a program to print the first 10 natural numbers.
for n in range(1,11):
print(n)
Write a Python program that displays odd numbers between 1 and 10.
Write a Python program that displays even numbers between 1 and 10.
total_velocity = 0
for velocity in velocities:
total_velocity += velocity
Modeling
In computational physics, modeling involves creating mathematical equations that represent
physical systems, such as the motion of a particle or the behavior of a fluid. These equations
can be derived from first principles, such as the laws of motion or thermodynamics, or they can
be empirical, based on experimental data. Once a model has been created, it can be used to
simulate the behavior of the system over time.
Simulation
Simulation involves using the model to make predictions about the behavior of the system. This
can involve solving the equations that describe the system using numerical methods, such as
the finite difference or finite element method. These simulations can provide valuable insights
into the behavior of complex physical systems that may be difficult or impossible to study
experimentally.
One example of modeling and simulation in computational physics is the study of fluid
dynamics. Researchers can create mathematical models that describe the behavior of fluids,
such as the Navier-Stokes equations, and use simulations to study how fluids behave under
different conditions, such as in a pipe or around a moving object.
Importance
Modeling and simulation are two important techniques used in computational physics to
understand physical systems. Modeling involves creating mathematical representations of
physical systems, while simulation involves using those models to make predictions about the
behavior of the system. These techniques are essential for studying complex physical systems
that may be difficult or impossible to study experimentally.
Examples
1. Simulation of Bouncing of Ball Problem
# Bouncing ball physics problem
# Simulate the height of a bouncing ball over time
# Define variables
initial_height = 10 # height in meters
bounce_coefficient = 0.7 # energy retained after each bounce
num_bounces = 5 # number of bounces to simulate
# Calculate the height using a for loop
height = initial_height
for i in range(1,num_bounces+1):
height = height * bounce_coefficient**2
print(f"Bounce {i:d}, height {height:.2f} meters!")
print("The ball stopped bouncing after ", num_bounces," bounces.")
#Get the user input for the initial velocity and angle of launch
v_0 = float(input("Enter the initial velocity of the projectile in m/s: ")) # convert to
float
theta_0 = float(input("Enter the angle of launch of the projectile in degrees: ")) #
convert to float
theta_0 = math.radians(theta_0) # convert to radians
Random Number
Here's a simple Python program that generates and displays a random number between 1 and 10
(inclusive) using the built-in random module:
The random module is a built-in Python module that provides functions for generating random
numbers and sequences. It can be used to perform a variety of tasks, such as simulating random
events in games or generating random data for testing.
Random Walk Problem in Physics
In physics, the random walk problem refers to a mathematical model that describes the random
motion of a particle or system. The concept of a random walk is often used to analyze various
physical phenomena, such as diffusion, Brownian motion, and particle transport.
In a random walk, the motion of a particle or system is characterized by a series of discrete steps
taken in random directions. At each step, the particle moves a certain distance in a random
direction. The direction and distance of each step are determined independently and randomly.
The random walk problem can be approached in various ways depending on the specific context.
For example, in a one-dimensional random walk, the particle can only move along a line, while
in a two-dimensional random walk, the particle can move in any direction within a plane. The
random walk model can also be extended to three or more dimensions.
Applications
The random walk problem has applications in various areas of physics, such as statistical
physics, condensed matter physics, and biophysics. It is used to study the spreading of particles,
the behavior of polymers, the motion of molecules in a gas, and many other phenomena where
random motion plays a significant role.
ACTIVITY
Suppose a man is standing at point(5,5) in the x,y coordinate plane. The man is allowed 15 steps
and in 4 directions namely; front, back, right, and left. Each step covers a distance of 1 foot.
Write a fully commented Python program that simulates this. In the end, the program should find
and display displacement of the man from the starting point and his ending point in the x,y
coordinate plane.
import random
import math
return x, y
Another Example
import random
print(random.uniform(2.5,4))
Functions in Python
A function is a group of statements that exist within a program for the purpose of performing a
specific task.
Instead of writing a large program as one long sequence of statements, it can be written as
several small functions, each one performing a specific part of the task. These small functions
can then be executed in the desired order to perform the overall task.
A program that has been written with each task in its own function is called a modularized
program and the approach is called “Divide and Conquer”.
This program is one long, complex In this program the task has been divided
sequence of statements. into smaller tasks, each of which is
performed by a separate function.
↓ ↓
Statement def fun1():
Statement Statement
Statement Statement
Statement …
Statement Statement
Statement
Statement
Statement def fun2():
Statement Statement
Statement Statement
Statement …
Statement Statement
Statement
Statement
Statement def fun3():
Statement Statement
Statement Statement
Statement …
Statement Statement
Statement
Example
Write a function that displays “I love Pakistan”. Use this function to exhibit its function.
Now, you can call the show() function as many times as you want and anywhere in the program.
ACTIVITY
Write a function to find the value of force in newton when it receives the values of mass in kg
and acceleration in m/s2.
Write the following user-defined functions. The names of the functions, the values that they
receive and return are given in the table below.