0% found this document useful (0 votes)
10 views7 pages

Python Expt 4

Gyye

Uploaded by

Tanishka
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views7 pages

Python Expt 4

Gyye

Uploaded by

Tanishka
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

4/09/24

EXPERIMENT-04

❖ AIM: To practice conditional statements, conditional loops and packages in python.

❖ SOFTWARE USED: Spyder, MS Word.

❖ THEORY:

1. Conditional blocks statements or loops: They are fundamental concepts in programming that allow
you to control the flow of your code based on certain conditions.

Types of conditional statements

Conditional statements allow you to execute certain parts hf your code only if specific conditions are
met. Python provides the following condition statements

a) if statement: Checks a condition if its true it executes a block of code.


b) elif statement: checks another condition of the previous if or elif was false.
c) else: executes a block of code if none of the above conditions are true.

Loops allow you to run a code multiple times which is helpful for repetitive task like calculations or
processing data

Python has 2 main types of loops

a. for loop: used to iterate over a sequence(like a list, tuple, list, or range)
b. while loop: repeats a block of code as long as the condition is true.

2. Python packages for scientific computing NumPy and SciPy:

Python is a powerful language widely used for scientific computing due to its simplicity and
versatility. Two essential packages for mathematical and scientific computations in python are
NumPy and SciPy. These packages are particularly useful in fields like chemistry where you often
need to perform complex mathematical calculations and data analysis.

a. NumPy (numerical python)


NumPy is a fundamental package for numerical computing in python. It provides support for
large muti dimensional arrays and matrices along with a collection of mathematical functions to
operate on these arrays efficiently.
- efficiency: it's much faster than python's standard lists because it uses optimized C code.
- convenience: it provides many functions for mathematical operations, linear algebra, random
number generation and more.
- NumPy is compatible with many other python packages like SciPy, pandas and matplotlib
making an essential part of the python scientific stack

18
4/09/24
b. SciPy(Scientific Python)
SciPy builds on Numpy and provides additional functionality for scientific computing. It includes
modules for optimization, Integration, interpolation, eigen value problems, algebraic equations
and other tasks common in science and engineering.
Uses of SciPy are:
- Advanced mathematical functions: It is useful for solving differential equations, integrating
functions and optimizing parameters which are common tasks in physical chemistry.

❖ PRACTICE:

1. #Create 1-D NumPy array of atomic mass of oxygen, nitrogen, fluorine and helium
import numpy as np
a=np.array(["Oxygen","O","16"])
b=np.array(["Nitrogen","N","14"])
c=np.array(["Fluorine","F","18"])
d=np.array(["Helium","H","4"])
print(a,b,c,d)
#output

2. # To define the shape of a matrix


import numpy as np
a=np.array([
["okay","fine","thank you"],
["bye",3,10],
[54,78,90]
])
print(a.shape)
#output

3. # To convert 3x2 matrix into 2x3


import numpy as np
a=np.array([
["okay","fine","thank you"],
["bye",3,10]
])
print(np.transpose(a))
#output

19
4/09/24

4. # check_reaction_conditions(temperature, pressure):
def check_reaction_conditions(temperature, pressure):
if temperature > 25 and pressure > 1:
return "Reaction conditions met."
else:
return "Reaction conditions not met."
# Example usage
temp = float(input("Enter the temperature (°C): "))
press = float(input("Enter the pressure (atm): "))
result = check_reaction_conditions(temp, press)
print(result)
#output

5. #To calculate average pH of the values of pH entered


def calculate_average_pH():
total_pH = 0
count = 0
while True:
pH = input("Enter pH value (or type 'done' to finish): ")
if pH.lower() == 'done':
break
try:
pH = float(pH)
total_pH += pH
count += 1
except ValueError:
print("Invalid input. Please enter a number.")
if count > 0:
average_pH = total_pH / count
print("Average pH value:", average_pH)
else:
print("No pH values entered.")
# Example usage
calculate_average_pH()

20
4/09/24
#output

6. # Constants
MIN_CONCENTRATION = 0.1 # Minimum concentration in Molar
MAX_CONCENTRATION = 2.0 # Maximum concentration in Molar
# User input for moles of solute and volume of solution
moles_of_solute = float(input("Enter the moles of solute: "))
volume_of_solution = float(input("Enter the volume of solution (in liters): "))
# Calculate molarity
molarity = moles_of_solute / volume_of_solution
# Check if molarity is within the specified range
if molarity < MIN_CONCENTRATION:
print("The solution is too dilute.")
elif molarity > MAX_CONCENTRATION:
print("The solution is too concentrated.")
else:
print("The solution is within the desired concentration range.")
#output

7. # User input for initial concentration and volumes


initial_concentration = float(input("Enter the initial concentration (in Molar): "))
initial_volume = float(input("Enter the initial volume (in liters): "))
final_volume = float(input("Enter the final volume (in liters): "))
# Calculate new concentration
new_concentration = (initial_concentration * initial_volume) / final_volume
print(f"The new concentration after dilution is {new_concentration:.2f} M")
#output

21
4/09/24

8. # Avogadro's number
avogadro_number = 6.022e23
# Number of moles for each case
moles = [1, 2, 0.5, 0.1]
# Calculate number of molecules for each amount of moles
for mole in moles:
number_of_molecules = mole * avogadro_number
print(f"{mole} moles contains {number_of_molecules:.2e} molecules")
#output

9. # Reaction rates (in mol/(L*s))


reaction_rates = [0.01, 0.1, 1.0, 5.0]
# Determine and print reaction times
for rate in reaction_rates:
if rate < 0.1:
speed = 'Slow'
elif 0.1 <= rate < 1.0:
speed = 'Medium'
else:
speed = 'Fast'
print(f"A reaction with rate {rate} mol/(L*s) is {speed}")
#output

10. import numpy as np


# Molecular masses of different compounds in g/mol
molecular_masses = np.array([18.015, 58.44, 44.01]) # H2O, NaCl, CO2
# Molar fractions of each component in the mixture
molar_fractions = np.array([0.5, 0.3, 0.2])
# Calculate the average molecular mass of the mixture
average_mass = np.sum(molecular_masses * molar_fractions)
print(f"Average molecular mass: {average_mass:.2f} g/mol")
#output

22
4/09/24

11. import numpy as np

# Given masses in grams of substances


masses = np.array([18.015, 58.44, 44.01]) # H2O, NaCl, CO2
# Molar masses in g/mol
molar_masses = np.array([18.015, 58.44, 44.01]) # H2O, NaCl, CO2
# Calculate moles
moles = masses / molar_masses
print(f"Moles of substances: {moles}")
#output

❖ RESULT: Conditional statements, conditional loops and packages in python were practiced

23
4/09/24

24

You might also like