A variable is a named storage location where you can save some value when you execute your code. variables are created when you assign a value to it.
The benefit of saving your values to a variable is that the values and calculation (in our case addition) can be reused in some further parts of the code.
x = 5
y = 10
word = 'Hello'
print(5+10) # without variables
print(x+y) # using variables
15 15
A comment is a line in your code that you don’t want to run but write them just for some reference in your code like explaining what your code is doing.
Python has commenting capability for the purpose of in-code documentation.
In python, comments can be done using a #
symbol in the start of the line. It will inform the interpreter not to execute that line.
# this is a comment
print("hello world")
# this does addition
print(x+y)
hello world 15
In programming, data type is an important concept.
Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data.
We are not always working with the same type of data. For example, to store the details of a student I will need different values like:
Name: "John"
Age: 15
Class/Grade: 12
Subjects: ['Math','Biology','History','Physics']
In this above example, we can clearly see that the data with which we want to work is in different formats like the name is a string type, age is an int type, the percentage is a float type and subjects is of type list.
One way to categorize data types is in one of the key categories
Numeric : int
, float
and complex
Sequence : str
(string), list
, tuple
, range
Boolean : True
or False
Dictionary : dict
consists of (key
,value
) pairs
Set : set
consists unordered distinct items
We can use the type(variable_name) function to check the type of a specific variable. Operators in Python behave differently depending on the variable’s type and there are different built-in methods for each one.
The three types of numeric types are:
int (integer) : Integers represents whole numbers. This means that there are no fractional or decimal parts.
float : floating-point numbers are represented by numbers with decimals.
complex : Have a real part and an imaginary part
int
¶The int
data type deals with integer values. This means values like 0, 1, -2 and -15 and not numbers like 0.5, 1.01, 3.1444
If you give python the following code, it will conclude that a
is an integer and will assign the int data type to it
a = 5
print(type(a))
<class 'int'>
Note: the value of
int
is unconstrained. It doesn't have a maximum value - it's unbounded.
float
¶The float
data type can represent floating point numbers, up to 15 decimal places. This means it can cover numbers such as 0.3, -2.8, 3.0, 5.54243553, e.t.c but also integers.
Numbers that have more than 15 numbers after the dot will be truncated.
y = 2.3
print(type(y))
<class 'float'>
y = 5/4
print(type(y))
<class 'float'>
y = 5.0 # explitly set to float
print(type(y))
<class 'float'>
y = 5
print(type(y))
<class 'int'>
The float data type can be used to represent some special numbers like the NaN
(Not a Number), +/- Infinity, and exponents
y = float('-infinity')
print(y)
-inf
y = float(5e-3)
print(y)
0.005
y = float('nan')
print(y)
nan
float('nan') == float('nan') # nan does not equal nan
False
It represents imaginary numbers in a complex pair.
The character j
is used to express the imaginary part of the number, unlike the i
more commonly used in math.
Let's see how we can declare complex numbers in Python:
a = 1j
print(a)
1j
print(a*a)
(-1+0j)
# assigning a variable to a complex number
a = 3 + 1j
print(a+a)
(6+2j)
Sequence Data Types are used to represent collections of some sort. These collections of elements can consist of elements of the same type, or of completely different types.
Another key feature of sequences is that they are iterable, meaning that you can process through each item in a sequence.
str
¶Strings are representative of the characters that we use in writing.
Strings are IMMUTABLE or can say that they can’t be modified further or changed further.
Strings can be represented within single or double quotes or triple quotes, like: ‘string item’ or “string item”, or """value""". The triple quoted strings can be on multiple lines, the new lines will be included in the value of the variable. They’re also used for writing function documentation.
Strings are very common as they're the most basic way to represent a sequence of characters - or words:
my_string = 'Hello, World'
print(my_string)
print(type(my_string))
Hello, World <class 'str'>
They can also contain special values, some of which are \n
if we want the string, when printed, to have a new line, or if we want to use a special characater like \
, '
, "
we need to add a backslash \
before them.
Adding a backslash before them is called escaping the special characters, as we don't want their special meaning to be taken into consideration - we want their literal values to be used.
my_string = "adding a new line \n and some double quotes \" to the string"
print(my_string)
adding a new line and some double quotes " to the string
Another way of not worrying about adding a backslash before every '
or "
is to use '''
or """
(triple quotes) instead.
my_string = '''No need to worry about any ' or " or even
new line character'''
print(my_string)
No need to worry about any ' or " or even new line character
Strings are internally treated as a list in python. A list of characters. Square brackets can be used to access elements of the string.
### more on strings
List is an ordered sequence of items. Lists are used to store multiple items in a single variable. Lists are an important data type. They are basically an organized collection of different or same objects.
Lists are also usually represented as items within square brackets i.e.
[item1, item2, item3, ..., itemn]
They are MUTABLE. That means, they can be changed or modified further. They can have heterogeneous data types in them. That means, they can have same or different data types together.
Lists are heterogeneous (single list may contain int, float, str)
List are mutable (they can be updated or altered)
The elements in a list are indexed according to a definite sequence
Indexing of a list begins with 0 (zero) as the first index.
To create a list, put items separated using commas and enclose with square brackets []
One list can contain values of any type. It is possible that one list contains another nested lists for its values.
# create a list
fruits = ["pineapple","apple","lemon","strawberry","orange","kiwi"]
print(fruits)
['pineapple', 'apple', 'lemon', 'strawberry', 'orange', 'kiwi']
String elements can be accessed by their index in the list, with the index starting at 0
print(fruits[0]) # pineapple is the first in the list of fruits
pineapple
### More on lists
tuple
¶The tuple
data type is very similar to lists, the only difference being that it's immutable and that it's created using () instead of []. This means that once you create a tuple, you can't change the values it contains.
A tuple is a collection which is ordered and unchangeable.
Tuples are written with round brackets.
They are in most cases slightly faster than lists and are used to protect data from being changed:
# create a tuple
this_tup = ("carrot","onion","mango")
print(this_tup)
print(type(this_tup))
('carrot', 'onion', 'mango') <class 'tuple'>
Tuple items are ordered, unchangeable, and allow duplicate values.
Tuple items are indexed, the first item has index [0]
, the second item has index [1]
etc.
Tuple is an ordered collection of Python objects
Sequence of values stored in a tuple can be of any data type and they are indexed by integers
Difference between list and tuple are that tuples are immutable. Tuple once created cannot be modified.
Tuple are defined withing paranthesis ()
; where the items are separated using commas.
Tuples are used to protect data, and are usually faster than list as they cannot change dynamically.
Tuple are objects separated by commas, It's the comma that makes a tuple not paranthesis
# creating a tuple
tup1 = 1,False, "Girl",3.6
print(tup1)
print(type(tup1))
(1, False, 'Girl', 3.6) <class 'tuple'>
tup2 = (5) # not a tuple
print(type(tup2))
<class 'int'>
Tuples can also be created with single element, having one element, having one element is not sufficient so it must contain a trailing comma to make it a tuple.
tup3 = (5,) # a tuple
print(type(tup3))
<class 'tuple'>
print(tup1) # Tuples are immutable
tup1[0] = 7
print(tup1)
(1, False, 'Girl', 3.6)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Input In [35], in <module> 1 print(tup1) ----> 2 tup1[0] = 7 3 print(tup1) TypeError: 'tuple' object does not support item assignment
tuple()
constructor¶It is also possible to use the tuple() constructor to make a tuple.
# creating a tuple
tup2 = tuple()
print(type(tup2))
<class 'tuple'>
# creating a tuple
some_tup = "some string", 5, True, float('nan')
# printing the value of a tuple
print(some_tup)
('some string', 5, True, nan)
# Accessing an element of a tuple
first_elem = some_tup[0] # access the first element of the tuple
print(first_elem)
some string
# Accessing elements from a given index to the end of the index (slicing)
slice_tup = some_tup[1:]
print(slice_tup)
(5, True, nan)
# Accessing elements from a given index to another given index
some_tup[1:3]
(5, True)
# More on Tuples
range
¶Range items are a special type of sequences and usually helps to define ranges or intervals to review.
Usually, when defining a range you can define a range of another sequence data type by noting the start (where to start), stop (where to end), and step (number of instances between each item) which you are looking to investigate. These come in handy when defining how you want to loop through a sequence with more complex logic.
interval = range(5)
print(interval)
print(type(interval))
range(0, 5) <class 'range'>
bool
¶The bool
data type is used to represent boolean values - True
or False
.
The data type can't contain any other value.
In programming you often need to know if an expression is True or False.
Useful to perform a filtering operation on a data.
You can evaluate any expression in Python, and get one of two answers, True or False
The bool()
function allows you to evaluate any value, and give you True
or False
in return.
If you happen to say bool(5)
, Python will consider that True
, while bool(0)
will be considered False
.
# declaring and using booleans
some_bool = True
# pring the boolean's value
print(some_bool)
True
type(some_bool)
bool
# Assigning an empty string to a boolean
some_bool = bool('') # empty string evaluates to False
print(some_bool)
False
some_bool = bool('Hello') # string not empty
print(some_bool)
True
Note:
True
andFalse
are keywords, and that you can't sayortrue
false
True
¶Any string is True
, except empty strings
Any number is True
, except 0
Any list, tuple, set, and dict are True
, except empty ones
dict
¶Dictionaries are collections of key
:value
pairs.
This means that, unlike with lists for example, values are associated with keys and not with integer indexes.
Dictionaries are very powerful mapping types that allow some relational connection between two items kept within the dictionary.
It's important to note that keys have to be unique, while values don't. When you'd like to look up a value - you pass its key in and retrieve the pair.
Dictionaries are written with curly brackets, and have keys and values.
Key-value pair is separated by a (:) colon, whereas each key is separated by comma.
The keys in dictionaries can be of any immutable data type like numeric, frozenset, strings, etc. and the value can hold any of the data types from all. The values can be accessed using the respective keys.
A dictionary can be created by placing sequence of elements within curly braces {}
, separated by commas.
Key is unique, whereas values can be duplicates
We can retrieve and update values using keys
Keys are immutable
Dictionary can be created using a built-in dict()
function.
Dictionary keys are case sensitive.
If we want to get the value for a given key, we can do it like that: dict_name[key]
.get()
function is also used to access element from a dictionary
# creating an empty dict
thisdict = {}
print(type(thisdict))
<class 'dict'>
# create a dict
dict1 = {1: 'Good', 2:'Better', 3:'Best'}
print("original dictionary: ", dict1)
original dictionary: {1: 'Good', 2: 'Better', 3: 'Best'}
# accessing element using key
print("Accessing element using key: ", dict1[2])
Accessing element using key: Better
# accessing an element using get()
print("Accessing element using get(): ", dict1.get(2))
Accessing element using get(): Better
Deletion of keys can be done using del
keyword
Using del
keyword, specific values or whole dictionary can be deleted.
del dict1[1]
print(dict1)
{2: 'Better', 3: 'Best'}
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
# get the value of the brand
print(thisdict['brand'])
Ford
# change the year of the dict
thisdict['year'] = 1974
print(thisdict)
{'brand': 'Ford', 'model': 'Mustang', 'year': 1974}
# to add a new field to the dictionary
thisdict['color'] = 'Black'
print(thisdict)
{'brand': 'Ford', 'model': 'Mustang', 'year': 1974, 'color': 'Black'}
# add a list of values
del thisdict['color']
thisdict['colors'] = ['Blue','Black','White']
print(thisdict)
{'brand': 'Ford', 'model': 'Mustang', 'year': 1974, 'colors': ['Blue', 'Black', 'White']}
print(type(thisdict))
<class 'dict'>
Nesting dictionaries is another great example of making it even more powerful, where for a key/value pair in a dictionary the values are actually another dictionary nested within it.
# more on dictionaries
A set is a type of data in Python that contains unordered and distinct items. This means that a set cannot contain any duplicates.
Sets are very useful for determining membership testing (is an item within another item), removing duplicates from other sequence types, and performing mathematical operations like intersections, unions, differences, and symmetric differences.
They are mutable. That means they can be modified or changed further.
Due to the fact that sets are unordered, whenever you call a set it does not retain an index or position for the data within it.
Many of the sequence behaviors, therefore, do not work on sets, like slicing and indexing.
Sets are written with curly brackets.
Unordered - The items in a set do not have a defined order. Set items can appear in a different order every time you use them, and indexing is pointless.
Unchangeable - We cannot change the items after the set has been created. Once a set has been created, you cannot change its items, but you can remove items and add new items.
Unique - Duplicates Not allowed. Sets cannot have two items with the same value.
Set can be created using the built-in set()
function.
# creating a set
my_set = set()
print("empty set: ",my_set)
empty set: set()
# create a set from a list of values
set1 = set([1,2,3,4,5,'Hello'])
print(set1)
{1, 2, 3, 4, 5, 'Hello'}
# a set can contain only unique elements
set1 = set([1,2,3,3,3,4,4,5,6,7,8,1,3,9])
print(set1) # has no duplicates
{1, 2, 3, 4, 5, 6, 7, 8, 9}
There may be times when you want to specify a type on to a variable. This can be achieved via casting.
Casting in Python is done using constructor functions:
int()
- constructs an integer number from an integer literal, a float literal (by removing all decimals), or a string literal (provided the string represents a whole number)
float()
- constructs a float number from an integer literal, a float literal or a string literal (provided the string represents a float or an integer)
str()
- constructs a string.
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
print(x, y, z)
1 2 3
x = float(1) # x will be 1.0
y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2
print(x)
print(y)
print(z)
print(w)
1.0 2.8 3.0 4.2
int("three") # has to be numeric literal
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Input In [3], in <module> ----> 1 int("three") ValueError: invalid literal for int() with base 10: 'three'
x = str("string1") # x will be string1
y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'
print(x)
print(y)
print(z)
string1 2 3.0
# arithmetic operations cannot be done on string data type
x = str(1)
y = str(1)
z = x + y
print("string addition:",z)
# lets cast them back to int
z = int(x) + int(y)
print("integer addition:",z)
string addition: 11 integer addition: 2
In Python, type casting can also be done on sequence data types such as lists, tuples and sets.
Constructor functions.
list()
- constructs a list from a string, tuple, set, dictionary
tuple()
- constructs a list from a string, list, set
set()
- constructs a set from a string, list and tuple
lst = list("Mary") # list of characters in the word 'Mary'
print(lst)
lst=list((1,2,3,4)) # (1,2,3,4) is a tuple
print(lst)
lst = list({1,2,3}) # {1,2,3} is a set
print(lst)
['M', 'a', 'r', 'y'] [1, 2, 3, 4] [1, 2, 3]
tup = tuple('Mary') # tuple of characters in the word 'Mary'
print(tup)
tup = tuple([1,2,3,4]) # [1,2,3,4] is a list
print(tup)
('M', 'a', 'r', 'y') (1, 2, 3, 4)
set1 = set('everest') # unique characters in the word 'everest'
print(set1)
set2 = set([1,2,3,3,2,2,1,4,5]) # handy for removing duplicates
print(set2)
{'r', 'v', 't', 'e', 's'} {1, 2, 3, 4, 5}
You are given three variables name
,age
,rating
.
Name is the name of a person. age contains their age and rating is their performance.
name
- "Use your name"
age
- 15
rating
- 4.5
Print the following sentence:
Hello {name}, in the next 5 years your age will be {age in 5 years} years old. You have a rating of {rating} out of 5.
Note: This problem requires you to calculate what the age for this person should be after 5 years.
name = "Kennedy Waweru"
age = 30
rating = 3.98