Python Programming for Computational Physics: Conditionals, Loops, and I/O, Exercises of Computational Physics

Loops iterate over a sequence of items. ○ In python, the items can be any items in a list. ○ We will often iterate through the indices that.

Typology: Exercises

2022/2023

Uploaded on 03/01/2023

agrima
agrima 🇺🇸

4.8

(10)

257 documents

1 / 23

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Python Programming
Computational Physics
Python Programming
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17

Partial preview of the text

Download Python Programming for Computational Physics: Conditionals, Loops, and I/O and more Exercises Computational Physics in PDF only on Docsity!

Python Programming

Computational Physics

Python Programming

Outline

Useful Programming Tools

– Conditional Execution

– Loops

– Input/Output

Python Scripts, Modules, and Packages

if...elif...else statement example

enter a value to test

X = input('Enter Value of X: ')

now we do the test with if statement

if X < 0: print 'X is less than 0!' elif X == 0: print 'X is zero!' elif X == 1: print 'X is one!' else: print 'X = ',X,' is not a special case'

another example of if...else

if X < 0 and X > -2: print 'X < 0 but X > -2 !' else: print 'X is not between -2 and 0.'

enter a value to test

X = input('Enter Value of X: ')

now we do the test with if statement

if X < 0: print 'X is less than 0!' elif X == 0: print 'X is zero!' elif X == 1: print 'X is one!' else: print 'X = ',X,' is not a special case'

another example of if...else

if X < 0 and X > -2: print 'X < 0 but X > -2 !' else: print 'X is not between -2 and 0.' If X is less than 0 we do this Otherwise, if X is equal To 0 we do this. == means “is equal to” Otherwise, if X is equal To 1 we do this. Otherwise, if X doesn't Match any of above, Condition can be any Then we do this.

Logical Statement

Loops

Loops are a special type

of conditional execution.

Loops iterate over a

sequence of items.

In python, the items can

be any items in a list.

We will often iterate

through the indices that

point to items in NumPy

arrays.

Item from sequence Execute Statement(s) on Item Ready for More Fun For iterating_var in sequence: statements No More Items In the Sequence Next Item

for loop example

enter an array for example

t = np.linspace(0.,1.,11)

use for look to iterate through array

for x in t: print x

loop on INDEX to the t array

for i in range(len(t)): print 'index = ',i, ' Value = ',t[i]

enter an array for example

t = np.linspace(0.,1.,11)

use for look to iterate through array

for x in t: print x

loop on INDEX to the t array

for i in range(len(t)): print 'index = ',i, ' Value = ',t[i] In this example, we consider each possible index in the t array. len(t) gives the number of elements. In this case len(t) = 11. range(t) makes a list starting at 0 that has len(t) elements. In this case: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Output is: index = 0 Value = 0. index = 1 Value = 0. index = 2 Value = 0. index = 3 Value = 0. index = 4 Value = 0. index = 5 Value = 0. index = 6 Value = 0. index = 7 Value = 0. index = 8 Value = 0. index = 9 Value = 0. index = 10 Value = 1.

while loops

While loops continue to

execute the statements

in the loop as long as a

condition is True.

Note that if statements

do not change the

condition, the loop will

continue forever.

Test Condition Execute Statement(s) Ready for More Fun while condition: statements False True

Input and Output

Input

– We have already seen “input” in action.

X = input('Set the value of X: ')

– NumPy provides a simple way to read in a 2D

array of values: np.loadtxt(' filename ')

A = np.loadtxt('mydata.dat')

mydata.dat is a text fle with a 2D array

arranged in rows and columns. A will

be a NumPy array with the data

arranged in rows and columns.

Input and Output

Input (continued)

– np.loadtxt can also read a csv text fle, such

as those made by Excel.

– In a csv fle, individual values are separated

by a “delimiter” ... often a , semicolon

(;) or comma (,)

A = np.loadtxt('mydata.csv', delimiter=';')

– Some rules about loadtxt:

2D only

All data of same type (as in NumPy)

Number of items in each row must be the

same.

Input and Output

NumPy loadtxt() and savetxt() are very

useful for quickly loading and saving

simple array data for our programs.

There is an equivalent load() and save()

that deal with NumPy arrays in binary

form.

Sometimes we need to read and write

data according to some more specifc

format. Maybe we want to mix types....

We can do this by reading and writing

from fles.

File I/O

SEE: docs.python.org/2/tutorial/inputoutput.html

Steps:

– Open the fle with open() method

– Read or Write to the fle with read() or write()

method

– Close the fle with close() method

Open the fle “f.dat”

– For writing

F = open('f.dat','w')

– For reading

F = open('f.dat','r')

Read Example

open f.dat for reading

F = open('f.dat', 'r')

read all the lines

Z = F.readlines()

use print to show contents

for x in Z: print eval(x) F.close()

open f.dat for reading

F = open('f.dat', 'r')

read all the lines

Z = F.readlines()

use print to show contents

for x in Z: print eval(x) F.close() f.dat: (^) Open the file Read all the lines into an array named Z Print each element of Z after evaluating it Close the file Output:

6

Writing Data to File

F.write(s)

Writes the string s to open fle F.

Note that if you wish to write a number,

you must convert it to a string.

Let a be a float and b be an int:

Old Way: F.write( '%5.3f %4d '% (a,b) )

New Way:

F.write('{0:5.3f} {1:4d}'.format(a,b) )

5.3f => write float in 5 spaces with 3 digits after

the decimal point.

4d => write int in 4 spaces

Scripts, Modules, Packages

We write “programs” in python using text

fles. We may distinguish:

– Scripts : a fle with a set of python

statements that we wish to run. It's the

same as typing them into ipython.

– Modules : a fle that defnes functions,

classes, and/or other variables that we want

to use with other pieces of python code.

– Packages : a package is a set of Modules

which are related and maintained together in

the same directory.

Why?

We use Modules to try to stay organized.

Functions and classes are separate from

the scripts that call them.

– They can be used by MANY diffferent scripts

– We don't risk changing them as we edit new

scripts.

Packages keep related Modules together.

– Keep individual modules from getting too big

to be easily maintained.

– Easy to gather the whole group together for

others to use.