1 IntroToPython-BasicCommands&PythonObjects
1 IntroToPython-BasicCommands&PythonObjects
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
# sum
1+1
# difference
5-2
# product
3*3
# division
5/2
# power
4**2
16
# 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.
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 _.
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
del x # to remove x
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.
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.
'Yellow'
Similarly, we can extract the first k elements or the last k elements as follows:
['Yellow', 'Red']
['Red', 'Green']
Modify a list
# I can update the value of a list
FirstList[1] = 4
print(FirstList)
['Yellow', 4, 'Green']
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.
. 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.
[]
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.
# Define a tuple
Tuple1 = ("Soccer", "Tennis", "Basketball")
print(Tuple1)
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)
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
Modify a dictionary
# update an item
FirstDict["Model"] = "X1"
print(FirstDict)
# To delete items
FirstDict.pop("Model")
print(FirstDict)
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"]
}