2 - Language Basics
2 - Language Basics
2 - Language Basics
In Python, Strings, lists and tuples are sequences. They can be indexed and sliced.
Sequences share the following operations:
1. a[i] returns i-th element of a (i is referred to as the index; in Python, indexes start from zero
2. a[i:j] returns elements i up to j-1 (this is referred to as slicing)
3. len(a) returns the number of elemetns in sequence
4. min(a) returns smallest value in sequence
5. max(a) returns largest value in sequence
6. x in a returns True if x is element of a
7. a + b concatenates sequences a and b
8. n * a creates n copies of sequence a
Tuples and strings are immutable, which means we can't change individual elements within a string or a tuple. Lists are "mutable", which means we can change elements in a list.Tuples and strings are immutable, which
means we can't change individual elements within a string or a tuple. Lists are "mutable", which means we can change elements in a list.
Out[ ]: 's'
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/tmp/ipykernel_40416/3658556251.py in <module>
1 # attempting to change element at index 0:
----> 2 str_sample[0] = 'b'
In [ ]: sequence_example = [1, 2, 3, 4, 5, 6, 7]
sequence_example
Out[ ]: [1, 2, 3, 4, 5, 6, 7]
In [ ]: # demonstrating slicing
sequence_example[0:5]
Out[ ]: [1, 2, 3, 4, 5]
Out[ ]: [1, 2, 3, 4, 5]
Out[ ]: [2, 3, 4, 5, 6, 7]
Out[ ]: 7
Out[ ]: []
Out[ ]: [6, 7]
In summary:
a[start:stop] # items in index start through stop-1
a[start:] # items in index start through the rest of the sequence
a[:stop] # items from the beginning through stop-1
a[:] # a copy of the whole sequuence
There's also a step value, which can be used with any of the above:
a[start:stop:step] # from index start to stop-1, in increments of step
In [ ]: sequence_example[0:7:1]
sequence_example[0:7:2]
Out[ ]: [1, 3, 5, 7]
Out[ ]: [2, 5]
Strings as sequences
Strings are immutable sequences of characters.
a = 'Hello World'
Strings have a type of str .
The number of characters in a string (that is its length) can be obtained using the len() function:
In [ ]: a = 'Hello World'
len(a)
Out[ ]: 11
In [ ]: num_str = '55'
num_str.isnumeric()
Out[ ]: True
Out[ ]: True
In [ ]: str_with_whitespace.lstrip()
In [ ]: str_with_whitespace.rstrip()
In [ ]: str_with_whitespace.strip()
In [ ]: str_with_num = '400'
str_with_num.zfill(5) # if len of str < 5 fill with leading zeros
Out[ ]: '00400'
In [ ]:
In [ ]: x = 'There is no hiding place.'
# split() will separate the string where it finds white space
x.split()
There is no hiding
place
In [ ]: y.split()
In [ ]: message.split('.')
Out[ ]: ['First sentence', ' Second', ' Third sentence', ' Fourth sentence', '']
Out[ ]: ['a', 'man', 'never', 'steps', 'into', 'the', 'same', 'river', 'twice']
In [ ]: " ".join(words)
Out[ ]: 'a man never steps into the same river twice'
Lists as sequences
A list is a sequence of objects. The objects can be of any type.
Integers:
a = [22, 11, 33, 44]
Strings:
b = ['polar', 'grizzly']
In [ ]: c = []
c
Out[ ]: []
Out[ ]: 4
In [ ]: list(range(5))
Out[ ]: [0, 1, 2, 3, 4]
The range command takes an optional parameter for the beginning of the integer sequence (start) and another optional parameter for the step size. This is written in the form range([start], stop, [step])
where the arguments in square brackets are optional.
Out[ ]: [5, 6, 7, 8, 9]
Tuples as sequences
A tuple is an immutable sequence of objects. Tuples are very similar in behavior to list with the exception that they cannot be modified (immutability). The elements of a tuple can be of any type:
In [ ]: tuple_sample[1]
Out[ ]: 13
You can define a tuple without parentheses; just list the elements and separate them by commas:
Out[ ]: 2
(2) would read as defining operator precendence which simplifies to 2 which is just a number
In [ ]: type(ab)
Out[ ]: int
(2,)
Out[ ]: tuple
In [ ]: dir(tuple)
Out[ ]: ['__add__',
'__class__',
'__class_getitem__',
'__contains__',
'__delattr__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__getitem__',
'__getnewargs__',
'__gt__',
'__hash__',
'__init__',
'__init_subclass__',
'__iter__',
'__le__',
'__len__',
'__lt__',
'__mul__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__rmul__',
'__setattr__',
'__sizeof__',
'__str__',
'__subclasshook__',
'count',
'index']
Tuples can also be used to make two assignments at the same time:
In [ ]: x, y = (44, 33)
print(f"x:{x}\ty:{y}")
x:44 y:33
x:33 y:44
Logical operations
The boolean data type are special builtin objects in python.
In [ ]: a = True
a
Out[ ]: True
In [ ]: type(a)
Out[ ]: bool
In [ ]: b = False
b
Out[ ]: False
We can operate with these two logical valueus using boolean loogic:
Out[ ]: True
Out[ ]: True
Out[ ]: False
In [ ]: new_var = a and b
In [ ]: d = not True
d
Out[ ]: False
Out[ ]: False
In [ ]: x = 30
x > 15
Out[ ]: True
In [ ]: x > 100
Out[ ]: False
In [ ]: x != 520
Out[ ]: True
In [ ]: a = 100
if a > 0:
print("a is positive")
a is positive
if statements can also have an else branch which is executed if the condition evaluates to False :
In [ ]: num = -45
if num > 0:
print("num is positive")
else:
print("num is not positive")
In the example above, num can still be negative or zero. We can further discriminate between these scenarios using the elif keyword.
The elif keyword is used for checking several other possiblities in addition to the condition being checked by the if statement:
In [ ]: num_two = 350
if num_two > 0:
print(f"{num_two} is positive")
elif num_two < 0:
print(f"{num_two} is negative")
else:
print(f"{num_two} is zero")
350 is positive
Note: In newer versions of Python (3.10+), you'll also find the match-case control structure
command = 'hello'
match command:
case 'hello':
print("Hi! Good to see you!")
case 'bye':
print("See you later!")
For loop
The for-loop allows iteration over a sequence.
In [ ]: for number in [1, 2, 3, 4, 5, 6, 7, 8]:
print(number)
1
2
3
4
5
6
7
8
In [ ]: for i in range(10):
print(i)
0
1
2
3
4
5
6
7
8
9
chicken
spice
banana
rice
While loop
The while keyword allows to repeat an operation while a condition remains true. This is helpful for performing operations where the number of times it has to be repeated is not known before the operation starts.
Just as an exmaple, suppose we'd like to know for how many years we have to keep 1000 naira in a savings account to reach 2000 naira simply due to annual payment of interest (5%). We could calculate the number
of years using a while block:
In [ ]: account_balance = 1000
target_balance = 2000
rate = 1.05
years = 0
In [ ]: type(user_input)
Out[ ]: str
Exercise
Create a python script (or file): calculator.py
Question 2
Write a Python program that asks a student to enter their current level of study, length of their program (number of years their course of study takes) and current CGPA.
The program should then display the possible CGPA the student can graduate with if he/she makes 5.0 for the rest of their stay in school!
Question 3
Create a python script: averagecalc.py This script will compute the average of all values entered by the user.
Note: The main difference between a tuple and a list is immutability. Tuples are immutable while lists are not.