Beyond Regular Matter. Click here

⚠️ Stay Safe Online

This website will never ask for money except for paid services enlisted here or collect personal information in other ways online or offline. Stay vigilant and protect yourself from cyber fraud. No paid service is enabled here now. Use this as a digital library made personally to support academic excellence.

Python Notes: Basics

PHYSICXION: basic python notes

cover image of python for physics on website physicxion

Basic Python Notes

What is Python?

Python is a high-level, interpreted programming language widely used in:
  • Scientific computing
  • Artificial Intelligence
  • Web development
  • Data analysis
  • Automation
  • Physics simulations

1. Writing Your First Python Program


print("Hello World")

OUTPUT
Hello World
print() is used to display output on the screen.

2. Variables in Python

Variables store data.

x = 10
name = "Physics"
pi = 3.14 
Rules for Variables Cannot start with a number No spaces allowed. Case-sensitive. 

Example:

age = 20
Age = 30 
Both are different variables.

3. Data types 

These are the primary basic data types used in Python, classified in the following table. There are more data types like list, tuple, range, frozenset, binary types, and null types.


Data TypeExample
Integer (int)5
Float (float)3.14
String (str)"hello"
Boolean (bool)True, False


Example:

a = 5
b = 2.5
c = "Einstein"
d = True

4. Taking User Input


name = input("Enter your name: ")
print(name)
Numerical Input

x = int(input("Enter a number: "))
For decimal numbers:

x = float(input("Enter value: "))

5. Basic Operator 

Arithmetic Operators

OperatorMeaning
+Addition
-Subtraction
*Multiplication
/Division
//Floor Division
%Modulus
**Power

Example:

a = 10
b = 3

print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a % b)
print(a ** b)

6. Conditional Statements

if Statement

x = 10

if x > 5:
    print("x is greater than 5")
if-else

x = 2

if x % 2 == 0:
    print("Even")
else:
    print("Odd")
if-elif-else

marks = 75

if marks >= 90:
    print("A")
elif marks >= 70:
    print("B")
else:
    print("C")

7. Loops in Python 

for loop

for i in range(5):
    print(i)
    
OUTPUT

Run started
Initializing environment
Installing packages
Running code
0
1
2
3
4
Run completed in 43.69999998807907ms
while loop

x = 1

while x <= 5:
    print(x)
    x += 1 
OUTPUT

Run started
Initializing environment
Installing packages
Running code
1

2

3

4

5

Run completed in 43.69999998807907ms

8. Functions

Functions help reuse code. 

Creating a Function

def greet():
    print("Hello")
Calling Function

greet()
Function with Parameters

def add(a, b):
    return a + b

result = add(2, 3)
print(result)

OUTPUT

Run started
Initializing environment
Installing packages
Running code
5

Run completed in 6982.300000000745ms

9. Lists

Lists store multiple values. in a list position of elements mapped as 0, 1, 2... This means the very first entry of a list element is assigned to a position index of 0, the second one has a position index of 1, and so on.

numbers = [1, 2, 3, 4]
Accessing Elements

To access an element within a list, we need to call it by its position index.
print(numbers[0])
Adding Elements

numbers.append(5)
Example:

numbers = [1, 2, 3, 4]
print(numbers[0])
numbers.append(5)
print(numbers)
OUTPUT

Run started
Initializing environment
Installing packages
Running code
1

[1, 2, 3, 4, 5]
Run completed in 27.200000001117587ms
Loop Through List

for x in numbers:
    print(x)
Example:

numbers = [1, 2, 3, 4]
for x in numbers:
    print(x)
OUTPUT

Run started
Initializing environment
Installing packages
Running code
1

2

3

4

Run completed in 72.09999999962747ms

10. Tuples are immutable lists.

t = (1, 2, 3)
Cannot change elements after creation. 

11. Dictionaries 

Store data as key-value pairs.

student = {
    "name": "Rahul",
    "age": 20
}
Access value:

print(student["name"])

12. Strings


text = "Physics"
String Operations

print(text.upper())
print(text.lower())
print(len(text))
Example:

text = "Physics"
print(text.upper())
print(text.lower())
print(len(text))
OUTPUT

Run started
Initializing environment
Installing packages
Running code
PHYSICS

physics

7

Run completed in 75.69999999925494ms

13. File Handling 


Writing to File

file = open("data.txt", "w")
file.write("Hello")
file.close()
Reading File

file = open("data.txt", "r")
print(file.read())
file.close()

14. Exception Handling Used to handle errors.


try:
    x = 10 / 0
except:
    print("Error occurred")
    
OUTPUT

Run started
Initializing environment
Installing packages
Running code
Error occurred

Run completed in 5855.799999998882ms
Python has thousands of modules, categorized into those built into the language and those created by the community. One can find 200+ native modules in the official "Python Module Index." 

Core standard library 

Basically, these are pre-installed with Python and handle basic system tasks. 
os: Interact with operating system (files, directories) 
sys: System-specific parameters and functions 
math: advanced mathematical operations 
datetime: work with dates and times. 
random: Generates random numbers and choices 
json: Encode and decode JSON data. 
re: Regular expression operations for text searching 
collections: Specialized container types like counter or deque. 

Web and networking

urllib: Handle URLs and HTTP requests 
http.server: Set up a simple local web server 
socket: low-level networking interface 
webbrowser: open links in the default browser. 

not discussable for core physics. Generally math- and simulation-dependent modules are used here. 

Third-party modules 

Those are installed separately before assignment, usually via PyPI, which hosts over 800,000 projects. 

Data-science: Numpy(arrays), Pandas(dataframes), SciPy(science) 
Visualization: Matplotlib, Seaborn, Plotly Machine learning: Scikit-learn, TensorFlow, PyTorch. 
Web-Frameworks: Django,Flask. 
Automation: Requests(HTTP),BeautifulSoup(sracpping). 

15. Importing Modules


import math

print(math.sqrt(25))
OUTPUT

Run started
Initializing environment
Installing packages
Running code
5.0

Run completed in 9985.400000002235ms
16. Object-Oriented Programming (Basic)

class Student:

    def __init__(self, name):
        self.name = name

    def show(self):
        print(self.name)

s1 = Student("Einstein")
s1.show()

Run started
Initializing environment
Installing packages
Running code
Einstein

Run completed in 5041.5ms

17. NumPy Basics 

 Useful for scientific computing. useful for computational theoretical physics.

import numpy as np

a = np.array([1,2,3])

print(a)
OUTPUT

Run started
Initializing environment
Installing packages
Running code
[1 2 3]

Run completed in 10387.79999999702ms

18. Matplotlib Basics 


Used for plotting graphs. highly useful for computational and theoretical physics. 

Example: 

Let's plot the simplest 2-D graph

import matplotlib.pyplot as plt

x = [1,2,3]
y = [1,4,9]

plt.plot(x, y)
plt.show()
OUTPUT

Run started
Initializing environment
Installing packages
Running code












Run completed in 27098.5ms

Summarizing 

19. Important Python Concepts


ConceptMeaning
VariableStores data
FunctionReusable block of code
LoopRepeats code
ConditionDecision-making
ListCollection of data
ModulePrewritten code library
ClassBlueprint for objects


20. Common Python Libraries

LibraryUse
NumPyNumerical computation
MatplotlibPlotting
PandasData analysis
SciPyScientific computing
SymPySymbolic mathematics


"These articles and the views expressed as notes are my own interpretations made to easily organize and simplify the complexity of higher studies and do not represent the official views of any professor or their institution. Collection of personal notes and ideas as portfolio"

Reference:

Python official documentation
Book: Scientific computing in Python by Abhijit Kar Gupta
Book: Scientific Computing with Python by Claus Führer, Olivier Verdier, Jan Erik Solem.