Home
Physics

Scientific Coding with Python Part 1

In this part, we introduce Python and show how to write your first code.

Yusuf OlçunMay 4, 202612 min read
Scientific Coding with Python Part 1

Scientific Programming with Python, Chapter 1

In the present century, programming has become a skill that everyone needs and that forms part of their work. What will we do in this series? We will study numerical-analysis methods in physics using the Python language. Numerical analysis examines methods for finding approximate solutions to mathematical problems. Most real-world problems do not admit closed-form solutions; numerical analysis fills this gap.

Its principal applications in physics include differential equations, quantum mechanics, and physical simulations.

In this series, I will teach you Python using the Spyder program. To install Spyder, simply visit https://repo.anaconda.com/archive/, download the file compatible with your device, and install it.

Spyder.

From the “File” section marked on our screen, we can create a new file and save it. The button circled in red creates a new file; the orange-marked control saves it; and the yellow-marked control runs our code. These are shortcuts to Spyder's basic functions. We can write our code on the left side of the screen and see its output on the right, marked in blue.

Let us make a simple start:

print("merhaba biricik okurları")

Its output will be

merhaba biricik okurları

For many people, this will be the first program they have written, and we have written it together.

When writing by hand, we normally perform mathematical operations using +, -, . , :. On a computer, we carry them out with slight differences, as follows:

OperationConventional NotationComputer Notation
Additiona+ba+b
Subtractiona-ba-b
Multiplicationa.ba*b
Divisiona:ba/b
Exponentiationaba^ba^b
Now that we have learned this, let us reinforce it with a small example.

Example 1:

Write the following operations in Python:

i) (a+bc)((2a:2b)+7c)(a + b - c) \cdot ((2a : 2b) + 7c)

ii) a+b3c2a + b^3 - c^2

iii) a+b+a2+b3b24ac\sqrt{a + b} + \dfrac{a^2 + b^3}{b^2 - 4ac}

Our input will be

print("(a+b-c)*((2*a/2*b)+7*c)")
print("a+b^3-c^2")
print("((a+b)^1/2)+((a^2+b^3)/(b^2-4*a*c))")

Our output will be

(a+b-c)*((2*a/2*b)+7*c)
a+b^3-c^2
((a+b)^1/2)+((a^2+b^3)/(b^2-4*a*c))

The magnitude and equality expressions we use in everyday calculations have the same meanings in a computer environment. The table below shows commonly used expressions and their meanings.

Comparison Operators
==Equal to
<>Not equal to
>Greater than
<Less than
>= /=>Greater than or equal to
<=/=<Less than or equal to

Logical expressions such as and/or/not, which we use every day, are represented in a computer environment as follows:

Logical Expressions
And.
Or+
Not'

Now that we have learned these, let us work through examples involving logical and comparison expressions.

Example 2:
From among the students in a class, we want the names of only those who are older than 23 and have received a passing grade. Write the corresponding code.
(Data:

  • Şükrü → Age: 24, Grade: 55
  • Suer → Age: 22, Grade: 70
  • Mehmet → Age: 25, Grade: 45
  • Begüm → Age: 26, Grade: 80
  • Yusuf → Age: 23, Grade: 60
  • Elif → Age: 27, Grade: 50)
ogrenciler = [
    {"isim": "Şükrü", "yas": 24, "not": 55},
    {"isim": "Suer", "yas": 22, "not": 70},
    {"isim": "Mehmet", "yas": 25, "not": 45},
    {"isim": "Begüm", "yas": 26, "not": 80},
    {"isim": "Yusuf", "yas": 23, "not": 60},
    {"isim": "Elif", "yas": 27, "not": 50}
]

for ogrenci in ogrenciler:
    if ogrenci["yas"] > 23 and ogrenci["not"] >= 50:
        print(ogrenci["isim"])

The output of this code gives us the names of students who are older than 23 and have received a passing grade:

Şükrü
Begüm
Elif

Example 3: We want the names of students in a class who received a grade above 65 in Computer Science and a grade above 65 in either Turkish Language or Foreign Language.
(Data:

  • Mert → Computer Science: 70, Turkish Language: 60, Foreign Language: 50
  • Ömer → Computer Science: 80, Turkish Language: 66, Foreign Language: 40
  • Emin → Computer Science: 60, Turkish Language: 70, Foreign Language: 75
  • Bahar → Computer Science: 90, Turkish Language: 50, Foreign Language: 68
  • Can → Computer Science: 67, Turkish Language: 40, Foreign Language: 30
  • Büşra → Computer Science: 72, Turkish Language: 70, Foreign Language: 80)

First, we must introduce our data to Python. To do so, let us create a list named “ogrenciler[]” (a list in Python is created as follows: List[element1,element2,...]) and enter our data in order. Then let us define a term “o” for the data in the ogrenciler[] list and have this term retrieve and print the data we want from ogrenciler[].

ogrenciler = [
    {"isim": "Mert", "bil": 70, "td": 60, "yd": 50},
    {"isim": "Ömer", "bil": 80, "td": 66, "yd": 40},
    {"isim": "Emin", "bil": 60, "td": 70, "yd": 75},
    {"isim": "Bahar", "bil": 90, "td": 50, "yd": 68},
    {"isim": "Can", "bil": 67, "td": 40, "yd": 30},
    {"isim": "Büşra", "bil": 72, "td": 70, "yd": 80}
]

for o in ogrenciler:
    if o["bil"] > 65 and (o["td"] > 65 or o["yd"] > 65):
        print(o["isim"])

The output of our code, and therefore the solution, is

Ömer
Bahar
Büşra

Variables in Python

In mathematics, rather than drowning in long formulas or patterns, we can assign them to a variable. In Python, however, we cannot define variables arbitrarily; there are several basic rules. A variable name cannot begin with a digit. It may begin with a letter or underscore, after which digits may be included.

x=5          #int=sayı
y="merhaba"  #str=metin
z=3.14       #float=ondalıklı sayı
x=5              #int
y="merhaba"      #str
z=3.14           #float
print(x)
print(y)
print(z)

Our output is

5
merhaba
3.14

To learn or check the type of an expression in Python, we use the command print(type(x)). Let us now print the expressions used above and check their types:

x=5              #int
y="merhaba"      #str
z=3.14           #float
print(x)
print(y)
print(z)
#bu bir yorum satırıdır python bunu algılamaz notlar almak için kullanılabilir

print(type(x))
print(type(y))
print(type(z))

When we run this command, it prints our expressions and their types as follows:

5
merhaba
3.14
<class 'int'>
<class 'str'>
<class 'float'>

Python is case-sensitive! We must pay attention to this, because if the variables we define correspond to different expressions, it can cause errors in our operations. We should therefore take care with uppercase and lowercase letters in variable names. Here is a quick example:

A=5
a=10
x=17 diyelim ve bunlarla ufak bir işlem yapalım
A=5
a=10
x=17
print(A+x)
print(a+x)

Our output is

22
27

which shows us just how important case sensitivity is in variables.

Variables in Python cannot begin with a digit, but a variable name may contain a digit after a letter.

5x=5 → Invalid!

5x=5
print(5x)

This produces an error:

File <unknown>:8
    5x=5
    ^
SyntaxError: invalid decimal literal

If we define it as x_=5, the system recognizes it.

x_=5
print(x_)

Its output is

5

In Python, different variables can have the same value.
For example:

x_=5
a=5
bir=5

If we introduce these variables:

x_=5
a=5
bir=5
print(x_,a,bir)

and request the output:

5 5 5

We have seen that although we use different variables, they can equal the same value we specified.

Example 4: Define two variables and perform operations with them.

a=17
b=5

print(a + b)   # Toplama → 22
print(a - b)   # Çıkarma → 12
print(a * b)   # Çarpma → 85
print(a / b)   # Bölme → 3.4
print(a // b)  # Tam sayı bölme → 3
print(a % b)   # Kalan (mod) → 2
print(a ** b)  # Üs alma → 1419857

Our output is

22
12
85
3.4
3
2
1419857

giving the requested operations in order.


Converting Variable Types

In Python, operations can be performed on variables of the same type.

x="Ali"
y="Veli"

print(x+" "+y)

Our result is

Ali Veli

Variables of different types, however, cannot be combined. Python cannot combine two different variable types, so attempting to print an expression of the form int+str results in an error.

x=5
y="Merhaba"
print(x+y)

The corresponding output tells us about the error:

TypeError                            Traceback (most recent call last)
File c:\users\yusuf\onedrive\desktop\fizik\dersler\python\biricik.py:10
    0 <Error retrieving source code with stack_data see ipython/ipython#13598>

TypeError: unsupported operand type(s) for +: 'int' and 'str'

We have learned that we cannot operate on variables of different types in Python, but there is a solution. We can convert an expression on the other side of the equality to the desired type by placing it inside the parentheses of the format we want. Let us therefore represent the number 3 as a str and a float.

In the code, we should write

x=str(3)
y=int(3)
z=float(3)
x=str(3)
y=int(3)
z=float(3)

print(x)
print(y)
print(z)

Our output is

3
3
3.0

so the expressions have been converted successfully to the desired types. We have converted them successfully—but what use is that? Let us see it in action:

x="Yusuf"
y=str(23)
z="yaşında"
print(x+" "+y+" "+z)

Our output is

Yusuf 23 yaşında

We combined expressions of two different types to form a sentence, reinforcing what we explained above.


Representing Decimal Numbers in Python

Suppose, for example, that we have the two numbers x=3.14 and y=3 ∗ 10¹⁴. To write them in a computer environment, we use

x=3.14
y=3e14

print(x,y)

Printing them gives

3.14 30000000000000.0

which displays x and y explicitly.

Example 5: Let us write three decimal numbers and print their average.

x=3.14
y=3e14
z=3e-14

print((x+y+z)/3)

If we have Python calculate this, we obtain

100000000000001.05

Complex Numbers

In Python, we use the character “j” to represent complex numbers; this “j” helps us distinguish the imaginary part.

X=2+3j
Y=1j

The code is as follows:

x=2+3j
y=1j

print(x+y)

Adding them combines the real parts with the real parts and the imaginary parts with the imaginary parts:

(2+4j)

Let us add these numbers and then print the real (z.real) and imaginary (z.imag) parts separately.

x=2+3j
y=1j

print(x+y)

z=x+y
print(z.real)
print(z.imag)

Our result is

(2+4j)
2.0
4.0

Example 6: Choose ten arbitrary variables and print their maximum, minimum, and average.
(The sum command adds the numbers in a list, while the len command returns the number of elements in the list.)

a1=5
a2=7
a3=9
a4=12
a5=15
a6=17
a7=23
a8=52
a9=55
a10=72

#Hepsini bir listede toplayalım
sayilar = [a1,a2,a3,a4,a5,a6,a7,a8,a9,a10]
en_kucuk=min(sayilar)
en_buyuk=max(sayilar)
ortalama = sum(sayilar) / len(sayilar)

print("En küçük:", en_kucuk)
print("En büyük:", en_buyuk)
print("Ortalama:", ortalama)

Our output is

En küçük: 5
En büyük: 72
Ortalama: 26.7

with the calculations performed and returned as shown.

In this article, we discussed basic operations in Python. In the next, we will cover list operations, operators, loops, and tuples in Python. Best wishes to everyone.

Y

Yusuf Olçun

Author