0% found this document useful (0 votes)
35 views6 pages

Python 2

The document provides an introduction to basic Python operations and concepts such as variables, data types, arithmetic operators, and built-in functions. It includes examples of printing output, assigning variables, performing calculations, and using functions like len(), min(), max(), and print(). The exercises at the end involve writing Python code to evaluate formulas, calculate the area of a square from user input, and determine the largest of three user-provided numbers.

Uploaded by

Alex Yuen
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
35 views6 pages

Python 2

The document provides an introduction to basic Python operations and concepts such as variables, data types, arithmetic operators, and built-in functions. It includes examples of printing output, assigning variables, performing calculations, and using functions like len(), min(), max(), and print(). The exercises at the end involve writing Python code to evaluate formulas, calculate the area of a square from user input, and determine the largest of three user-provided numbers.

Uploaded by

Alex Yuen
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 6

Special Funding Scheme for Innovation in Virtual Education in Business, CUHK

Learning Financial Analysis with Python from Scratch

Module 2 Basic operations


*We will use Colab for illustration in this note, while most of them work in Jupyter as well.

2.1 Your first code


Try to run some simple commands to get yourself familiar with the environment.
 In the code cell, let’s type print(“Hello World!”).
 If you press “Enter”, you can see that you go to the next line, but do not run the code.
 To run the code, you can press “Enter + Ctrl” or click the “Run” button.
 If you want to add comments to your code, you can write them down after a hash mark (#).
 A comment starts with the hash mark and extends to the end of the physical line
 Type print(“Hello World!”) # This is my first code.
 Try entering a simple mathematical expression 2+3.
 Type print(2 add 3) and run. What did you see?
 An error message tells you that the line of your codes cannot be executed properly.
 In this case, you need to debug your codes.

2.2 Variable
A variable is a name that is a reference to an object.
 You can use the assignment operator, “=” symbol, to assign values to variables.
 The text to the left of “=” is the name of the variable.
 The text to the right of “=” is the value that will be assigned to the variable.
 Let’s try the following code and run. What did you see?
 price = 5
 After an assignment, if you type the name, the value stored in the name will be displayed.
 stock = 15
 stock
 A name of a variable cannot start with a digit, and only letters, digits, or the underscore can
be used to form the name. Try the following codes:
 Q1

PHU Jacqueline & Dr. Edwin MOK 1


 pe_123 = 8
 Q2
 You can change the value of the variable by assigning a new value to this variable again
overwritten.
 stock = 8
 stock
 Python is a case-sensitive language, so uppercase and the lowercase of the same letter is
not treated the same.
 Stock
 You should make the name of the variable reflect the purpose of creating this variable, and
more importantly make it short. Which of the following is a good name?
1. mybankbalance
2. b
3. ty3945
4. balance

2.3 Variable Types


A variable can store different type of data that depends on the input data. A variable type is
determined when you first assign a value to a variable with the operator “=”.
 Integers are whole numbers without a fraction part.
 -20, 0, 506, 120304056
 Floats are real numbers that are written with a decimal point.
 23.56, 0.89, 2/3 , 6/2
 A string is a collection of characters represented in quotation marks (single-quoted or
double-quoted).
 “56”, ‘56’, “Tesla”, “2/3+5*6”
 Boolean has only two possible values.
 True, False
 List is a collection data type that is ordered and the value is changeable.
 [1,2,3],[“Tesla”,”Apple”,”Tencent”],[“0005”,”HSBC”]

PHU Jacqueline & Dr. Edwin MOK 2


2.4 Arithmetic Operators
You can find commonly used arithmetic operators for calculation in Table 1.
 Try the following codes:
 3*5+6
 5**3
 (3+5)*2
 21%4
 3>3
 3>=3
 3!=3
 Q3
 What did you see after running 3=3?
 As “=” indicates assignment, we use “==” for the mathematical meaning of equal to.

Table 1
List of arithmetic operators

Operator Meaning
+ Add
- Subtract
* Multiply
/ Divide
% Modulus
** Exponent
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
= x = 2 is the same as x = 2
+= x += 2 is the same as x = x + 2
-= x -= 2 is the same as x = x – 2
*= x *= 2 is the same as x = x * 2
/= x /= 2 is the same as x = x / 2

PHU Jacqueline & Dr. Edwin MOK 3


**= X **= 2 is the same as x = x ** 2
 Python uses the same precedence rules for its arithmetic operators as we do in the real
world.
1. Parenthesis has the highest precedence.
2. Exponentiation has the next precedence.
3. Multiplication and division have the same precedence, which has higher precedence than
addition and subtraction
4. Addition and subtraction have the same precedence.
5. Operator on the left has higher precedence than the operator on the right.

2.5 Built-in Functions


Python provides us with several pre-defined built-in functions to help us in performing different
function operations.
 Table 2 provides a list of a part of the commonly used built-in functions.
 abs returns the absolute value of a value.
 abs(-3/5)
 len returns the number of characters of a string.
 Q4
 min and max find the minimum and maximum of a series of values.
 min(5,max(8,3))
 int returns the integer part of a number or converts a string into an integer.
 int(2.99)+int(‘8’)
 float returns a number to a float variable or converts a string into a float variable.
 float(5)+float(‘3’)
 str returns a number into a string.
 str(26)+“83”
 eval evaluates an argument as a python expression.
 Q5
 input displays the argument and takes user input as a string returns.
 name = input(“What is your name?”)
 print is a simple way to produce an output.
 print(“Your name is “, name)

PHU Jacqueline & Dr. Edwin MOK 4


Table 2
List of built-in functions

Function Meaning
abs(x) This function returns the absolute value of x.
eval(x) The function evaluates an argument x as a python expression
filter(x, y) This function is applied to filter out the items from an iterable x with the function y.
float(x) This function returns a number x into a float variable or converts a string into a float
variable
help(x) This function displays the built-in help system and provides the relevant information of
an object x.
input(x) The function displays the message x in string and takes user input as a string.
int(x) This function returns the integer part of the number x or converts a string x into an
integer.
isintance(x, y) This function tests and returns
 True, when the stated object x is the stated type y.
 False, if not
len(x) This function returns the number of characters of a string x.
list(x) This function is used to form a list object x.
max(x, y, z, …) This function finds the maximum value in the series of values x, y, z, and others.
min(x, y, z, …) This function finds the minimum value in the series of values x, y, z, and others.
pow(x, y) This function calculates x to the power of y.
print(x) The function is a simple way to produce an output x.
range(x,y,z) The function returns a sequence of numbers.
 The first number starts from x
 The sequence ends when the next number is higher than or equal to y.
 z indicates increments of the sequence.
round(x, y) This function rounds a number x to a number with specified decimal places y.
slice(x, y, z) This function returns a slice object
 The slice object starts from position x
 The slicing ends at the position y
 Z sets the step of slicing.
sorted(x, key=key, This function returns a sorted iterable x, such as a list or a dictionary.
reverse=reverse)  In ascending order when reverse = False, which is the default
 Key is the function for the sort comparison and is None by default.
str(x) The function converts an object x into a string.
sum(x, y) This function calculates the sum of the items in an iterable x and y.

PHU Jacqueline & Dr. Edwin MOK 5


type(x) The function presents the type of an object x.
2.6 Exercises
1. How can you put the following formula into Python?
3
(5+6 )

3+ 8/2

2. Write a program that will get the perimeter of a square from a user and return the area of the
square.

3. Tell whether the value is True or False:


 ((2<8)and(3<6))and((5>7)or(11*2>3))and(not(9<8*2))

4. Design a program to allow a user to input 3 numbers, and then return the largest number.
 The terminal output would look like:

5. Design a small calculator that you can input a formula, and then return the result.
 The terminal output would look like:

End of Module 2

PHU Jacqueline & Dr. Edwin MOK 6

You might also like