Professional Documents
Culture Documents
Omputational Hysics With Ython: "Hello World!"
Omputational Hysics With Ython: "Hello World!"
Omputational Hysics With Ython: "Hello World!"
In Python, we can put all the code of our program into a text file with extension .py, for
example if the file my program.py has the following content:
//Content of the file my_program.py
def main():
print("hello World!")
if __name__ == "__main__":
// Call the main() function
main()
then if we run python my program.py, the code in this file will get executed and this will print
the text ’Hello World!’ into the console. In the following exercises, when I ask to write a program,
it means that you should create a file in which you modify the main() function above so that it
returns expected results.
Exercise 3: Loop
Write a program to ask how many people the user wants to invite to a party. If they enter
a number below 10, ask for the names and after each name display “[name] has been invited”.
If they enter a number which is 10 or higher, display the message “Too many people”. Then
print the final list of the invited guests.
Exercise 4: Loop
Write a program using the while loop to take an input number and test whether the number
is a prime number. If the input number is a prime number, print out ”[number] is a prime
1
number.”, otherwise print out ”[number] is not a prime number.” where [number] is the value of
the input.
a) Write a program (for example exercise 4.py) that takes as input three numbers, a, b, and c,
and prints out the two solutions to the quadratic equation ax2 + bx + c = 0 using the
standard formula √
−b ± b2 − 4ac
x= .
2a
Use your program to compute the solutions of 0.001x2 + 1000x + 0.001 = 0.
b) The equation does not have real solutions if the input parameters a, b, and c do not satisfy
the condition b2 − 4ac > 0. If this is the case, modify your program to display the warning
text: ”Invalid parameter! Please try again.”
d) Using what you have learned, write a new program that calculates both roots of a quadratic
equation accurately in all cases.
Hint: Look up for neccessary mathematical functions in the Python math module.
df f ( x + δ) − f ( x )
= lim .
dx δ →0 δ
On the computer we can’t actually take the limit as δ goes to zero, but we can get a reasonable
approximation just by making δ small.
a) Write a program that defines a function f(x) returning the value x ( x − 1), then calculates
the derivative of the function at the point x = 1 using the formula above with δ = 10−2 .
Calculate the true value of the same derivative analytically and compare with the answer
your program outputs. The two will not agree perfectly. Why not?
2
b) Repeat the calculation for δ = 10−4 , 10−6 , 10−8 , 10−10 , 10−12 , and 10−14 . You should see
that the accuracy of the calculation initially gets better as δ gets smaller, but then gets
worse again. Why is this?