0% found this document useful (0 votes)
41 views

1 IntroToPython-BasicCommands&PythonObjects

The document provides an introduction to basic Python commands and objects such as variables, lists, tuples, and dictionaries. It discusses how to define and manipulate different Python objects. For variables, it covers assigning values, data types, and naming conventions. For lists, it discusses indexing, slicing, and common list methods like append(), insert(), remove(), etc. It also introduces tuples as immutable lists and dictionaries as collections of key-value pairs. The document uses many examples and code snippets to demonstrate how to work with different Python objects.

Uploaded by

Hermine Koué
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views

1 IntroToPython-BasicCommands&PythonObjects

The document provides an introduction to basic Python commands and objects such as variables, lists, tuples, and dictionaries. It discusses how to define and manipulate different Python objects. For variables, it covers assigning values, data types, and naming conventions. For lists, it discusses indexing, slicing, and common list methods like append(), insert(), remove(), etc. It also introduces tuples as immutable lists and dictionaries as collections of key-value pairs. The document uses many examples and code snippets to demonstrate how to work with different Python objects.

Uploaded by

Hermine Koué
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Financial Econometrics with Python

Introduction to Python
Basic Commands and Python Objects

Kevyn Stefanelli
2023-2024

0. Basic commands
Before starting the course, an essential note:

Always include as many comments as possible in your code. They will be extremely valuable
when you revisit the code in the future and may have forgotten the reasons and methods behind
your coding decisions! Use "#" to write comment on Python chunks

To execute chunks use the Run bottom above or CTRL+ENTER

We can use Python as a calculator:

# sum
1+1
# difference
5-2
# product
3*3
# division
5/2
# power
4**2

16

Note: it prints on display only the last call.

To print more than one command use the function print()

# sum
print(1+1)
# difference
print(5-2)
# product
print(3*3)
# division
print(5/2)
# power
print(4**2)

2
3
9
2.5
16

1. Python objects
Python is an object-oriented language, which means that we can store values in objects.

For instance, we can assign the value 5 to a variable named "x," and from that point forward,
whenever we refer to "x," Python will respond with 5.

These objects (or variables) are contained in a space called the Global Namespace.

In Python, variables can store various types of values, including:

1. Numeric (integer or float): 1, 2, 3, 4, 0.5, -2.3


2. String (sequence of characters): "Kevyn", "Rome", "Nice"
3. Boolean: True or False

1.1 Variable definition


# Assign the value 2 to x
x = 2
# Assign the value -1.4 to y
y = -1.4

# Print (visualize) them


print(x)
print(y)

# Define a as a character variable: a = 'Hey! How are you?'


a = 'Hey! How are you?'
print(a)

2
-1.4
Hey! How are you?
Rules for defining variables in Python:
1. It is not possible to assign a name to a variable that starts with a number. For
example, z1 = 4 is correct, but 1z = 4 is incorrect.

2. In Python, you can use certain symbols as part of the variable name, such as the
underscore _.

For example, my_variable = 42 is correct.


Differently, you cannot use ".": my.variable = 42 returns error

1. Python is case-sensitive, so a and A are treated as two separate variables.

Let’s see what the Global namespace contains. We can use the magic command: %whos

In Python, magic commands are special commands used within interactive environments like
Jupyter Notebook.

# Display the names of the objects which are currently stored within
Python
%whos

# Create another variable and store it


italy = 0.1
france = 3.9
alps = italy * france # ";" is not needed in Python

# To see the updated variables in Python, we can use dir() again.


%whos

Variable Type Data/Info


-----------------------------
a str Hey! How are you?
x int 2
y float -1.4
Variable Type Data/Info
-----------------------------
a str Hey! How are you?
alps float 0.39
france float 3.9
italy float 0.1
x int 2
y float -1.4

We can delete objects using the function del:

del x # to remove x

or update the value of an object:


# define a variable called K
K = "What time is it?"
print("K:",K)
# now we update K and define it as a numeric variable
K=5
print("K:",K)

K: What time is it?


K: 5

Let's see the boolean variables: True or False?

We express a condition as: "a == b" --> We get a boolean

We define a variable as: "=" --> We get a new variable

Conditions:
• == equal
• != different
• > greater
• < lower
• =>/=< greater or equal/lower or equal

Logical Operators:
• and
• or
• not
print(10>9)
print(10==9)
print(10<9)

x=4
print(x<5 and x>10)
print(x<5 or x>10)
print(not(x<5 and x>10))

True
False
False
False
True
True
1.2 Lists
A list in Python is a collection of ordered and mutable elements enclosed in square brackets ([ ]).
Lists can contain elements of different data types, such as integers, floats, strings, or even other
lists.

Lists allow indexing, slicing, and various list-specific operations, making them versatile and
commonly used data structures in Python programming.

# define a list of objects


FirstList = ["Yellow", "Red", "Green"]
# print FirstList
print(FirstList)
# check its length with the function len()
print(len(FirstList))

['Yellow', 'Red', 'Green']


3

We can select elements in the list indicating their position.

ATTENTION:

Python starts counting from 0. Therefore, the first element of the list is referred to as the
element at position zero. Subsequently, the second element of the list is the one at position 1,
and so on.

# extract from FirstList the first element


print(FirstList[0]) # use square brackets to select elements

'Yellow'

Similarly, we can extract the first k elements or the last k elements as follows:

# the first two elements


print(FirstList[:2]) # 2 excluded
# the last two elements
print(FirstList[1:])

['Yellow', 'Red']
['Red', 'Green']

Note: row 2, the element in position 2 is not included

Modify a list
# I can update the value of a list
FirstList[1] = 4
print(FirstList)
['Yellow', 4, 'Green']

# or add elements to the list using insert


FirstList.insert(2, "Pink") # Add "Pink" at position 2 (index 2)
print(FirstList)

['Yellow', 4, 'Pink', 'Green']

# or simply append them at the end using append


FirstList.append("Orange")
print(FirstList)

['Yellow', 4, 'Pink', 'Green', 'Orange']

# alternatively, I can merge two lists using extend


List2 = ["Ship", "Train", "Airplane", "Car"]
FirstList.extend(List2)
print(FirstList)

['Yellow', 4, 'Pink', 'Green', 'Orange', 'Ship', 'Train', 'Airplane',


'Car']

Note: "method invocation" on an object

When you invoke a method on an object, you are essentially calling that method to perform
some action or operation on the object itself. The method is defined within the class and
operates on the data associated with the specific object.

For instance, we invoked the method/function "append" on FirstList

Similarly, I can remove items from lists using different methods:

. remove(item): Removes the first occurrence of item from the list. . pop(index): Removes and
returns the item at the specified index. If no index is provided, it removes and returns the last
item. . del list[index]: Removes the item at the specified index using the del statement. . clear():
Removes all items from the list, making it empty.

Let's see a couple of examples

FirstList.remove("Train") # specific objects


print(FirstList)

FirstList.pop(1) # specifying the position of the element to remove


print(FirstList)
# FirstList.pop() removes the last element.

['Yellow', 'Pink', 'Green', 'Orange', 'Ship', 'Train', 'Airplane',


'Car']

# Alternatively, I can use del


del FirstList[2]
print(FirstList)
['Yellow', 'Pink', 'Orange', 'Ship', 'Train', 'Airplane', 'Car']

# To empty the entire list, I use clear


FirstList.clear()
print(FirstList)

[]

1.3 Tuples
In Python, a tuple is similar to a list, but it is immutable, meaning its elements cannot be
changed or modified after creation.

Tuples are defined using parentheses () instead of square brackets [] used for lists. Once a tuple
is created, you cannot add, remove, or change its elements.

To modify a tuple, you can convert it into a list using the list() function, make the necessary
changes to the list, and then convert it back to a tuple if needed.

When we need a tuple?


Tuples are useful when you have a collection of items that should remain constant throughout
the program's execution, preventing accidental changes to the data.

# Define a tuple
Tuple1 = ("Soccer", "Tennis", "Basketball")
print(Tuple1)

# We cannot change the positions or elements of this object


# To modify a tuple, we need to convert it into a list:
Tuple1_list = list(Tuple1)
print(type(Tuple1_list)) # Now we can modify Tuple1_list

# The same rules as above apply to access its elements, e.g.:


print(Tuple1[1])
print(Tuple1[:2])
print(Tuple1[-1])

('Soccer', 'Tennis', 'Basketball')


<class 'list'>
Tennis
('Soccer', 'Tennis')
Basketball

1.4 Dictionaries
In Python, a dictionary is a collection of key-value pairs, where each key is associated with a
specific value. The keys are unique within a dictionary, meaning duplicate keys are not allowed.

Dictionaries are defined using curly braces {} and key-value pairs separated by colons :
FirstDict = {
"Brand": "BMW",
"Model": "X5",
"Year": [2012, 2014, 2018],
"Color": ["Blue", "Red", "Black"]
}
print(FirstDict)

{'Brand': 'BMW', 'Model': 'X5', 'Year': [2012, 2014, 2018], 'Color':


['Blue', 'Red', 'Black']}

Accessing Dictionary Elements


To access elements in a dictionary, you can use the key to retrieve its corresponding value.

The keys are unique, and you can access the value associated with a particular key using the
square bracket notation []. Alternatively, you can use the get() method, which also retrieves the
value associated with the specified key.

print(FirstDict["Model"])
print(FirstDict.get("Brand"))

X5
BMW

# Print the keys


print(FirstDict.keys())

# Print the values


print(FirstDict.values()) # Only values

# Print key-value pairs (items)


print(FirstDict.items()) # Key-value pairs = items

dict_keys(['Brand', 'Model', 'Year', 'Color'])


dict_values(['BMW', 'X5', [2012, 2014, 2018], ['Blue', 'Red',
'Black']])
dict_items([('Brand', 'BMW'), ('Model', 'X5'), ('Year', [2012, 2014,
2018]), ('Color', ['Blue', 'Red', 'Black'])])

Modify a dictionary
# update an item
FirstDict["Model"] = "X1"
print(FirstDict)

{'Brand': 'BMW', 'Model': 'X1', 'Year': [2012, 2014, 2018], 'Color':


['Blue', 'Red', 'Black']}
# Otherwise, I can use the method "update"
FirstDict.update({"Year": 2008})
print(FirstDict)

{'Brand': 'BMW', 'Model': 'X1', 'Year': 2008, 'Color': ['Blue', 'Red',


'Black']}

# To delete items
FirstDict.pop("Model")
print(FirstDict)

{'Brand': 'BMW', 'Year': 2008, 'Color': ['Blue', 'Red', 'Black']}

1. Exercises
1. Define a tuple named 'ID' containing your name, birthdate (separating day, month, and
year), and nationality.
2. Print the second element of the 'ID' tuple.
3. Convert this tuple into a list, and then add a fourth element to the 'ID' list, indicating your
favorite sport to play/watch.
4. Using the appropriate comparison operator, inquire whether the day of your birthdate is
greater than 15.
5. I have created a dictionary representing a football e-commerce shop's inventory:
Ecomm = {
"Brand": ["Adidas", "Nike", "Puma"],
"Model": ["Predator", "Vapor", "Future Match"],
"Year": [2022, 2021, 2023],
"Color": ["White", "Purple", "Yellow"]
}

5a. Display (print) the dictionary keys.

5b. Remove 'Year'.

5c. Update the Model's value "Predator" to "Accuracy".

You might also like