2 - Language Basics

Download as pdf or txt
Download as pdf or txt
You are on page 1of 15

Sequences

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.

In [ ]: str_sample = "string sample"


# getting element at index 0:
str_sample[0]

Out[ ]: 's'

In [ ]: # attempting to change element at index 0:


str_sample[0] = 'b'

---------------------------------------------------------------------------
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'

TypeError: 'str' object does not support item assignment

In [ ]: # Lists are mutable


list_sample = ['egg', 'milk', 'sugar', 'oil']
list_sample

Out[ ]: ['egg', 'milk', 'sugar', 'oil']

In [ ]: # You can change an element in a list


list_sample[0] = 'soda'
list_sample

Out[ ]: ['soda', 'milk', 'sugar', 'oil']

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]

In [ ]: # A simpler form of the above expression


sequence_example[:5]

Out[ ]: [1, 2, 3, 4, 5]

In [ ]: # Another slicing example:


sequence_example[1:]

Out[ ]: [2, 3, 4, 5, 6, 7]

In [ ]: # Note that Python supports negative indexing;


# We could reference the last element of a sequence
# using -1:
sequence_example[-1]

Out[ ]: 7

In [ ]: # Try out the following examples


sequence_example[2:-1]
sequence_example[-2]
sequence_example[3:3]

Out[ ]: []

In [ ]: sequence_example[-2:] # last two items in the sequence

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

By default, this step value is one.

In [ ]: sequence_example[0:7:1]
sequence_example[0:7:2]

Out[ ]: [1, 3, 5, 7]

In [ ]: # You could reverse a sequence with a special slicing notation


sequence_example[2::-1]
sequence_example[1::3]

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 [ ]: # There are a lot of useful functions you can perform on strings:


dir(str)
Out[ ]: ['__add__',
'__class__',
'__contains__',
'__delattr__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__getitem__',
'__getnewargs__',
'__gt__',
'__hash__',
'__init__',
'__init_subclass__',
'__iter__',
'__le__',
'__len__',
'__lt__',
'__mod__',
'__mul__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__rmod__',
'__rmul__',
'__setattr__',
'__sizeof__',
'__str__',
'__subclasshook__',
'capitalize',
'casefold',
'center',
'count',
'encode',
'endswith',
'expandtabs',
'find',
'format',
'format_map',
'index',
'isalnum',
'isalpha',
'isascii',
'isdecimal',
'isdigit',
'isidentifier',
'islower',
'isnumeric',
'isprintable',
'isspace',
'istitle',
'isupper',
'join',
'ljust',
'lower',
'lstrip',
'maketrans',
'partition',
'removeprefix',
'removesuffix',
'replace',
'rfind',
'rindex',
'rjust',
'rpartition',
'rsplit',
'rstrip',
'split',
'splitlines',
'startswith',
'strip',
'swapcase',
'title',
'translate',
'upper',
'zfill']

In [ ]: num_str = '55'
num_str.isnumeric()

Out[ ]: True

In [ ]: new_str = 'Hello, This Is A Title'


new_str.istitle()

Out[ ]: True

In [ ]: # try these function calls


new_str.upper()
new_str.lower()

Out[ ]: 'hello, this is a title'

In [ ]: str_with_whitespace = " a string with whitespaces "


str_with_whitespace

Out[ ]: ' a string with whitespaces '

In [ ]: str_with_whitespace.lstrip()

Out[ ]: 'a string with whitespaces '

In [ ]: str_with_whitespace.rstrip()

Out[ ]: ' a string with whitespaces'

In [ ]: str_with_whitespace.strip()

Out[ ]: 'a string with whitespaces'

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()

Out[ ]: ['There', 'is', 'no', 'hiding', 'place.']

In [ ]: # Remember tabs, and newlines characters are whitespaces


y = 'There\tis\tno\thiding\nplace'
print(y)

There is no hiding
place

In [ ]: y.split()

Out[ ]: ['There', 'is', 'no', 'hiding', 'place']

In [ ]: # By passing a separator character to the split() method, a string


# can split into different parts. For example, to split a group of
# sentences into individual sentences:
message = 'First sentence. Second. Third sentence. Fourth sentence.'
message

Out[ ]: 'First sentence. Second. Third sentence. Fourth sentence.'

In [ ]: message.split('.')

Out[ ]: ['First sentence', ' Second', ' Third sentence', ' Fourth sentence', '']

In [ ]: # Joining strings is also possible:


z = 'a man never steps into the same river twice'
words = z.split()
words

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[ ]: []

In [ ]: # List are of type `list`:


type(c)
Out[ ]: list

In [ ]: # The number of elements in a list can be checked with the `len()`


# function:
a = [22, 11, 33, 44]
len(a)

Out[ ]: 4

In [ ]: # A list can have elements of different types:


d = [123, 'grizzly', -44.54, 0, 'polar']
d

Out[ ]: [123, 'grizzly', -44.54, 0, 'polar']

In [ ]: # A list can even contain other lists


list_of_lists = [
['Emeka', '1999/000419', 'UTME'],
['Amina', '1998/000319', 'DE']
]
list_of_lists

Out[ ]: [['Emeka', '1999/000419', 'UTME'], ['Amina', '1998/000319', 'DE']]

The range() command


The range() command is a special command for generating a sequence of numbers: the range(n) command generates integers starting from 0 and going up to n-1.

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.

In [ ]: list(range(5, 10)) # start=5

Out[ ]: [5, 6, 7, 8, 9]

In [ ]: list(range(5, 20, 3)) # start=5, step=3

Out[ ]: [5, 8, 11, 14, 17]

In [ ]: # Strings also have some useful methods:


dir(list)
Out[ ]: ['__add__',
'__class__',
'__class_getitem__',
'__contains__',
'__delattr__',
'__delitem__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__getitem__',
'__gt__',
'__hash__',
'__iadd__',
'__imul__',
'__init__',
'__init_subclass__',
'__iter__',
'__le__',
'__len__',
'__lt__',
'__mul__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__reversed__',
'__rmul__',
'__setattr__',
'__setitem__',
'__sizeof__',
'__str__',
'__subclasshook__',
'append',
'clear',
'copy',
'count',
'extend',
'index',
'insert',
'pop',
'remove',
'reverse',
'sort']

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 = (12, 13, 'green')


tuple_sample

Out[ ]: (12, 13, 'green')

In [ ]: tuple_sample[1]

Out[ ]: 13
You can define a tuple without parentheses; just list the elements and separate them by commas:

In [ ]: tuple_sample2 = 33, 44, 55, 67


print(tuple_sample2)
type(tuple_sample2)

(33, 44, 55, 67)


Out[ ]: tuple

In [ ]: # Caution: When defining a tuple with a single element, you


# must add a comma to the end of the element for the definition
# to result in a tuple.
ab = (2) # This is not a tuple
ab

Out[ ]: 2

(2) would read as defining operator precendence which simplifies to 2 which is just a number

In [ ]: type(ab)

Out[ ]: int

In [ ]: ac = (2,) # THis is a tuple with a single element


print(ac)
type(ac)

(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']

In [ ]: ad = ('a',) * 5 # possible because of the __mul__() magic method


ad

Out[ ]: ('a', 'a', 'a', 'a', 'a')

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

In [ ]: # Allows us to perform assignment operations in clever ways:


# we could swap values of x and y in a single line
x, y = y, x
print(f"x:{x}\ty:{y}")

x:33 y:44

Task: Read up Python dictionaries


What is the difference between a dictionary and a hash map?
Control Structures
Commands we have written so far is processed from top to bottom. We will now learn about different ways we can change the flow of our program.

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:

In [ ]: True and True

Out[ ]: True

In [ ]: True & True

Out[ ]: True

In [ ]: False and True # same as False & True

Out[ ]: False

In [ ]: new_var = a and b

There's also the or (|) operation, the not (~) operation

In [ ]: d = not True
d

Out[ ]: False

In [ ]: e = False or not True


e

Out[ ]: False

We often need to evaluate expressions that are either true or false

In [ ]: x = 30
x > 15
Out[ ]: True

In [ ]: x > 100

Out[ ]: False

In [ ]: x != 520

Out[ ]: True

if-else control statements


The if statment allows conditional execution of code.

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")

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

In [ ]: shopping_cart = ['chicken', 'spice', 'banana', 'rice']


for item in shopping_cart:
print(item)

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

while account_balance < target_balance:


account_balance = account_balance * rate
years = years + 1

print(f'It will take {years} years for balance to grow to {target_balance}')

It will take 15 years for balance to grow to 2000

Be careful when defining while loops to avoid unintended infinte loops.


However, infinte loops can be useful sometimes too. For example there could be a portion of code you want to run over and over again, you can use a simple while True: condition to achieve this effect.
Prompting user for input
You can prompt a user for an input the input keyword.

In [ ]: user_input = input("Enter your name: ")


print(f"Hello, {user_input}")

Enter your name:Chad


Hello, Chad

In [ ]: type(user_input)

Out[ ]: str

In [ ]: first_number = input("Enter first number: ")


type(first_number) # input will always return a value of type string

Enter first number: 44


Out[ ]: str

Exercise
Create a python script (or file): calculator.py

1. Present the user with options of arithmetic operations:


addition, subtraction, multiplication, division, square root, power
2. Listen for the user's choice
3. Prompt the user for operands
4. Compute the selected operation
5. Print the result
6. Repeat 1-5
Assignment 2
Question 1

Create a python script: primechecker.py.

1. Prompt the user to enter a number


2. Check if the number is a prime number
3. Display "(number entered by user) is a prime number" or "(number entered by user) is not a prime number" for the user

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.

1. Allow user enter all the values they wish to


2. Compute the average/mean of the values entered
3. Display the output message:
The average of (values entered by the user) is (computed average)

Link to submission form

Submit the assignment here: https://forms.gle/KUueG2oru8bhiPvC9

Note: The main difference between a tuple and a list is immutability. Tuples are immutable while lists are not.

You might also like