Contents
English translation
Contents
4. Basic calculations
4.1 Basic mathematical operations
- Variables
- A variable is a name identifying a storage location for data. It is called a variable because the stored data can change.
- For readability, choose names that reflect the data type or purpose.
- (Reading other people's source code reveals some naming conventions.)
# Good variable examples
pos_x = 10
num_values = 5
_event_flag = False
# Bad variable examples
abc = 4
a1 = 50
xxxx = 3.4
temp1 = 4
temp2 = 5- Data types
- These include
integer,floating-point number,bool(True/False), andstring. - Python manages them automatically, so you generally do not need to handle them explicitly.
- However, be careful: a data type can change against your intention.
- These include
# Integer
number = 5
# Floating-point number
value = 2.5
# bool
is_number = True
# String (string)
name = 'Ivan'
# When an integer becomes a floating-point number
number = number / 2
print('number =', number)number = 2.5
- Basic operators
- Arithmetic
- Addition
+, subtraction-, multiplication*, division/)
- Addition
- Other operations
- Quotient
//, remainder%, exponentiation**
- Quotient
- Logical operations
- Greater than
>, greater than or equal to>=, less than<, less than or equal to<=, equal to==, not equal to!=,and,or
- Greater than
- Arithmetic
a = 10
b = 2.5
print(a+b, a-b, a*b, a/b, a//b, a%b, a**b)
print(a>b, a>=b, a<b, a<=b, a==b, a!=b, a>b or a<=b, a>b and a<=b)12.5 7.5 25.0 4.0 4.0 0.0 316.22776601683796 True True False False False True True False
- Common mathematical functions (using NumPy)
- Sine
sin, cosinecos, exponentialexp, roundround, ceilingceil, floorfloor
- Sine
# We will cover use of the numpy library in more detail later.
import numpy as np
angle = np.pi/4
print(angle)
print(np.sin(angle))
print(np.cos(angle))
print(np.exp(angle))
print(np.round(angle))
print(np.ceil(angle))
print(np.floor(angle))0.7853981633974483 0.7071067811865475 0.7071067811865476 2.1932800507380152 1.0 1.0 0.0
4.2 Simple loops (for)
- The
forstatement is a built-in feature commonly used torepeata specified number of times. - Format
for variable in items:
statement
...+ Each list element is assigned to the variable in order during iteration, and the loop ends after all elements have been processed.
+ The list can contain any data type.
for i in [4, 'text', 1.5 , True, {'name':'Charles', 'age':15}]:
print(i)4
text
1.5
True
{'name': 'Charles', 'age': 15}
- However, the following form is more common.
for i in range(5):
print(i)0 1 2 3 4
- The
continuestatement can skip one iteration. (Theifstatement is explained in more detail at the end of this section.)
for i in range(5):
if i==3:
continue
print(i)0 1 2 4
- The
breakstatement can completely end a loop. (breakexits only one loop at a time.)
for i in range(5):
if i==3:
break
for j in range(5):
if j==2:
break
print(i, j)0 0 0 1 1 0 1 1 2 0 2 1
- (Simple example) Multiplication table (Print only tables 2–4 to keep the output short.)
for i in range(2,5):
for j in range(1,10):
print('%d * %d = %d' % (i, j, i*j))
print('----------')2 * 1 = 2 2 * 2 = 4 2 * 3 = 6 2 * 4 = 8 2 * 5 = 10 2 * 6 = 12 2 * 7 = 14 2 * 8 = 16 2 * 9 = 18 ---------- 3 * 1 = 3 3 * 2 = 6 3 * 3 = 9 3 * 4 = 12 3 * 5 = 15 3 * 6 = 18 3 * 7 = 21 3 * 8 = 24 3 * 9 = 27 ---------- 4 * 1 = 4 4 * 2 = 8 4 * 3 = 12 4 * 4 = 16 4 * 5 = 20 4 * 6 = 24 4 * 7 = 28 4 * 8 = 32 4 * 9 = 36 ----------
4.3 Conditional loops (while)
- The
whilestatement is used torepeatonly when aconditionis satisfied. - Format
while(condition):
statement
...+ The condition has type bool and can be expressed as `True` or `False`.
- Conditions can be combined as (condition `and` condition), (condition `or` condition).
- When the condition is
True, the statements below execute, then the condition is checked again. - When the condition is
False, the loop stops and execution continues with the next statement. - When the condition is always
True, the loop has no way to stop and is often called an infinite loop.- Unless an infinite loop is intentional, carefully check whether some conditions could cause one.
continueandbreakwork the same way as in aforstatement, andbreakcan exit an infinite loop. (See the example below.)
i = [1,2,3,4,-1,5,6,7,8]
j = []
count=0
while(i[count]>0):
j.append(i[count])
count = count + 1
print(j)[1, 2, 3, 4]
- (Simple example) Multiplication table (Accept input and print the requested multiplication table.)
# Provide information about how the program works.
print('원하는 단수를 입력하시고, 종료하려면 -1을 입력하세요.')
# Deliberately use an infinite loop.
while(True):
# Assume the user enters an integer.
i = int(input())
# Exit the loop when -1 is entered.
if i==-1:
break
# Output
for j in range(1,10):
print('%d x %d = %d' % (i, j, i*j))원하는 단수를 입력하시고, 종료하려면 -1을 입력하세요. 4 4 x 1 = 4 4 x 2 = 8 4 x 3 = 12 4 x 4 = 16 4 x 5 = 20 4 x 6 = 24 4 x 7 = 28 4 x 8 = 32 4 x 9 = 36 5 5 x 1 = 5 5 x 2 = 10 5 x 3 = 15 5 x 4 = 20 5 x 5 = 25 5 x 6 = 30 5 x 7 = 35 5 x 8 = 40 5 x 9 = 45 -1
4.4 More complex calculations (if)
- The
ifstatement performs the desired action when aconditionis satisfied. (Unlikewhile, it does not repeat.) - Format
if (condition):
statement
...
elif (condition):
statement
...
else:
statement
...- The statements below run when the condition is
True. - If another condition needs to be checked when the condition is
False, use theelifstatement. - Place any statements to run when the condition is
Falseunder theelsestatement. - Examples of
ifstatements are omitted because many have already been shown above.