HyperLearning AI - Introduction to Python

An introductory course to the Python 3 programming language, with a curriculum aligned to the Certified Associate in Python Programming (PCAP) examination syllabus (PCAP-31-02).
https://knowledgebase.hyperlearning.ai/courses/introduction-to-python

03. Control and Evaluations Part 2

https://knowledgebase.hyperlearning.ai/courses/introduction-to-python/modules/3/control-and-evaluations-part-2

In this module we will continue to cover the fundamental building blocks of the Python programming language, namely:

  • Functions and Methods - the difference between methods and functions
  • Input and Output - input, print, int, float and str functions
  • Formatting - formatting the output of the print function, and formatted string literals
  • Conditional Statements - if, if-else, if-elif, if-elif-else statements and the pass instruction
  • Basic Lists - constructing, accessing and manipulating list data collection structures
  • Basic Strings - constructing, accessing and operating on string literals
  • Loops - while loops, for loops, and controlling loops using break and continue statements

1. Functions and Methods

In [1]:
# A simple function to return the product of two given numbers
def product(number_1, number_2):
    return number_1 * number_2

print(product(12, 20))
240
In [4]:
# The common len() function given a string
my_string = 'Hello World!'
print(len(my_string))
12
In [2]:
# A common string method that will return the string all in uppercase
my_string = 'Hello World!'
print(my_string.upper())
HELLO WORLD!

2. Input and Output

2.1. Input Function

In [2]:
# Input function without a prompt message argument
full_name = input()
print(f'Your Full Name is: {full_name}')
Jillur Quddus
Your Full Name is: Jillur Quddus
In [3]:
# Input function with a prompt message argument
fname = input('Please enter your first name: ')
lname = input('Please enter your last name: ')
print(f'Hello {fname} {lname}!')
Please enter your first name: Jillur
Please enter your last name: Quddus
Hello Jillur Quddus!

2.2. Int Function

In [15]:
# Integer input using the int function (default base 10)
age = int(input('Please enter your age: '))
print(f'You are {age} years old')
Please enter your age: 28
You are 28 years old
In [16]:
# Integer input using the int function and base 16
# For example 28 (base 10) would be 1c in base 16
age = int(input('Please enter your age: '), 16)
print(f'You are {age} years old')
Please enter your age: 1c
You are 28 years old

2.3. Float Function

In [19]:
# Floating point input using the float function
height = float(input('Please enter your height in metres: '))
print(f'You are {height}m tall')
Please enter your height in metres: 2
You are 2.0m tall

2.4. Str Function

In [12]:
# Without the str function we cannot concatenate a number to a string
pi = 3.141592653589793238462643
print('The value of π is: ' + pi)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-12-32674aad3599> in <module>
      1 # Without the str function we cannot concatenate a number to a string
      2 pi = 3.141592653589793238462643
----> 3 print('The value of π is: ' + pi)

TypeError: can only concatenate str (not "float") to str
In [13]:
# The str function will convert pi into a string
print('The value of π is: ' + str(pi))
The value of π is: 3.141592653589793

2.5. Print Function

In [25]:
# Print a given string
print("My name is Jillur Quddus")
My name is Jillur Quddus
In [26]:
# Print a given collection of strings
print("Software Engineer", "Data Scientist", "Technical Architect")
Software Engineer Data Scientist Technical Architect
In [27]:
# Print a given collection of strings with a separator
print("Software Engineer", "Data Scientist", "Technical Architect", sep=', ')
Software Engineer, Data Scientist, Technical Architect
In [28]:
# Print a list of occupations on the same line
print("My Roles", end=": ")
print("Software Engineer", "Data Scientist", "Technical Architect", sep=', ')
My Roles: Software Engineer, Data Scientist, Technical Architect

3. Formatting

3.1. Formatted String Literals

In [30]:
# Print the value of e (Eulers number) using formatted string literals
e = 2.718281828459045235360287
print(f'The value of e is {e}')
The value of e is 2.718281828459045
In [31]:
# Print the value of e but to 3 decimal points
print(f'The value of e to 3 decimal points is {e:.3f}')
The value of e to 3 decimal points is 2.718
In [32]:
# Print age as a number of days
age = int(input('Please enter your age: '))
print(f'You are at least {age * 365} days old')
Please enter your age: 28
You are at least 10220 days old
In [34]:
# Access common mathematical constants using the Python math module
import math
print(f'The value of π to 3 decimal points is {math.pi:.3f}')
print(f'The value of e to 3 decimal points is {math.e:.3f}')
The value of π to 3 decimal points is 3.142
The value of e to 3 decimal points is 2.718

4. Conditional Statements

4.1. If Statement

In [2]:
# If statement using a comparison operator
age = int(input('Please enter your age: '))
if age >= 18:
    print("You are allowed to vote in UK elections")
Please enter your age: 19
You are allowed to vote in UK elections
In [3]:
# If statement using comparison and logical operators
if age >= 16 and age < 21:
    print("You are allowed to work full-time, join the armed forces, drive and vote but you cannot yet adopt a child in the UK")
You are allowed to work full-time, join the armed forces, drive and vote but you cannot yet adopt a child in the UK
In [5]:
# If statement using an identity operator
a = 10
b = 20
c = a

if a is b:
    print("a and b are the same object at object memory level")
if a is c:
    print("a and c are the same object at object memory level")
if b is c:
    print("b and c are the same object at object memory level")
a and c are the same object at object memory level
In [8]:
# If statement using a membership operator
first_ten_prime_numbers = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29)
if 13 in first_ten_prime_numbers:
    print("13 is in the first ten prime numbers")
13 is in the first ten prime numbers

4.2. If-else Statement

In [9]:
# If-else statement using a comparison operator
age = int(input('Please enter your age: '))
if age >= 18:
    print("You ARE allowed to vote in UK elections")
else:
    print("You are NOT yet allowed to vote in UK elections")
Please enter your age: 17
You are not yet allowed to vote in UK elections

4.3. If-elif Statement

In [12]:
# If-elif statements using comparison and logical operators
age = int(input('Please enter your age: '))
if age >= 21:
    print("You are entitled to undertake all legally permissible activities in the UK")
elif age >= 14 and age < 16:
    print("You can get a part-time job in the UK")
    print("But you cannot work full-time nor get married in the UK")
elif age >=16 and age < 18:
    print("You can get a full-time job and get married in the UK")
    print("But you cannot yet vote in the UK")
elif age >=18 and age < 21:
    print("You can get a full-time job, get married and vote in the UK")
    print("But you cannot adopt a child in the UK")
else:
    print("You can't do by yourself much unfortunately")
    print("Stay in school and listen to your parents!")
    if age >= 10:
        print("But since you greater than 10 years old, you have full criminal responsibility for your actions and can be convicted of a criminal offence in the UK")
        print("So think before you act!")
Please enter your age: 11
You can't do by yourself much unfortunately
Stay in school and listen to your parents!
But since you greater than 10 years old, you have full criminal responsibility for your actions and can be convicted of a criminal offence
So think before you act!

4.4. Pass Statement

In [27]:
# Use the pass statement to only print if x is even
x = int(input('Please enter an integer number: '))
if x % 2 != 0:
    pass
else:
    print(f"{x} is an even number")
Please enter an integer number: 88
88 is an even number

5. Basic Lists

5.1. Defining a List

In [2]:
# Create an empty list
empty_list = []

# Create a list containing the first five square numbers
squares = [1, 4, 9, 16, 25]
print(squares)
[1, 4, 9, 16, 25]

5.2. Index and Negative Indexing

In [62]:
# Access elements in a list by their index numbers
print(squares[0])
print(squares[3])
print(squares[-1])
print(squares[-4])
1
16
25
4

5.3. List Slicing

In [63]:
# Slicing a list
print(squares[0:2])
print(squares[2:])
print(squares[:3])
print(squares[:])
print(squares[-3:-1])
print(squares[-1:])
print(squares[:-2])
[1, 4]
[9, 16, 25]
[1, 4, 9]
[1, 4, 9, 16, 25]
[9, 16]
[25]
[1, 4, 9]
In [3]:
# Define an end index that is purposefully too large
print(squares[0:100])
[1, 4, 9, 16, 25]

5.4. List Length

In [64]:
# Length of a list
print(f'The length of the squares list is: {len(squares)} elements')
The length of the squares list is: 5 elements

5.5. List Membership

In [65]:
# Test whether an element exists in a list
x = 169
if x in squares:
    print(f"{x} exists in our list of square numbers")
else:
    print(f"{x} does not exist in our list of square numbers")
169 does not exist in our list of square numbers

5.6. Modifying Elements in a List

In [66]:
# Modify a specific element in a list
squares[0] = 0
print(squares)

# Revert to the original value
squares[0] = 1
print(squares)
[0, 4, 9, 16, 25]
[1, 4, 9, 16, 25]

5.7. Deleting Elements and Lists

In [67]:
# Remove a specific element from a list
del squares[-1]
print(squares)

# Delete a list collection entirely
del empty_list
print(empty_list)
[1, 4, 9, 16]
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-67-e400c12c82e4> in <module>
      5 # Delete a list collection entirely
      6 del empty_list
----> 7 print(empty_list)

NameError: name 'empty_list' is not defined

5.8. Joining Lists

In [68]:
# Append all elements from more_squares to squares
more_squares = [25, 36, 49, 64, 81, 100]
updated_squares = squares + more_squares
print(updated_squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

5.9. List Methods

In [69]:
# list.append(element)
squares.append(25)
print(squares)

# list.extend(newlist)
del more_squares[0]
squares.extend(more_squares)
print(squares)

# list.insert(index, element)
squares.insert(0, 0)
print(squares)

# list.remove(element)
squares.remove(0)
print(squares)

# list.pop([index])
squares.pop()
print(squares)

# list.clear()
squares.clear()
print(squares)
[1, 4, 9, 16, 25]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81]
[]
In [70]:
# Populate the list of square numbers again
squares.extend([1, 4, 9, 16, 25, 36, 49, 64, 81, 100])

# list.index(element[, start[, end]])
print(squares.index(64))

# list.count(element)
print(squares.count(169))

# list.sort()
squares.sort()
print(squares)

# list.reverse()
squares.reverse()
print(squares)

# list.copy()
squares_copy = squares.copy()
print(squares_copy)
7
0
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
[100, 81, 64, 49, 36, 25, 16, 9, 4, 1]
[100, 81, 64, 49, 36, 25, 16, 9, 4, 1]

6. Basic Strings

6.1. Creating Strings

In [74]:
# Create a simple string
first_name = 'Jillur'
print(first_name)

# Create a multiline string
envelope_label = """Jillur Quddus
1600 Pennsylvania Ave NW
Washington
DC 20500
United States"""
print(envelope_label)
Jillur
Jillur Quddus
1600 Pennsylvania Ave NW
Washington
DC 20500
United States

6.2. Index and Slicing

In [82]:
# Create a simple string
lorem_ipsum = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."

# Print the 13th character
print(lorem_ipsum[12])

# Print the substring between the 29th and 56th characters
print(lorem_ipsum[28:55])

# Print the last word
print(lorem_ipsum[-7:-1])
d
consectetur adipiscing elit
aliqua

6.3. String Length

In [83]:
# Calculate the length of a string
print(len(lorem_ipsum))
123

6.4. String Membership

In [84]:
# Test whether a given sequence of characters can be found in a string
if "tempor" in lorem_ipsum:
    print("The latin word for time has been found!")
The latin word for time has been found!

6.5. Concatenating Strings

In [85]:
# Concatenate one string to another string
lorem_ipsum_continued = "Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
lorem_ipsum_updated = lorem_ipsum + " " + lorem_ipsum_continued
print(lorem_ipsum_updated)
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

6.6. Escape Character

In [87]:
# Try to create a string containing illegal characters
illegal_string = "My name is "Jillur""
  File "<ipython-input-87-91727dda3ee7>", line 1
    illegal_string = "My name is "Jillur""
                                       ^
SyntaxError: invalid syntax
In [88]:
# Escape the illegal characters using the backslash character
legal_string = "My name is \"Jillur\""
print(legal_string)
My name is "Jillur"

6.7. Raw and Unicode String Literals

In [94]:
# Create and print a raw string literal
raw_string_literal = r"My name is Jillur Quddus\nI am a Chief Data Scientist and Principal Polyglot Software Engineer. Please find attached my résumé"
print(raw_string_literal)

# Create and print a unicode string literal
unicode_string_literal = u"My name is Jillur Quddus\nI am a Chief Data Scientist and Principal Polyglot Software Engineer. Please find attached my résumé"
print(unicode_string_literal)
My name is Jillur Quddus\nI am a Chief Data Scientist and Principal Polyglot Software Engineer. Please find attached my résumé
My name is Jillur Quddus
I am a Chief Data Scientist and Principal Polyglot Software Engineer. Please find attached my résumé

6.8. Comparing Strings

In [110]:
# Compare two strings
individual1_first_name = "Jillur"
individual2_first_name = "jillur"
if individual1_first_name == individual2_first_name:
    print("Both individuals share the same first name")
elif individual1_first_name.upper() == individual2_first_name.upper():
    print("Both individuals share the same first name when uppercased")
else:
    print("No name match found")
Both individuals share the same first name when uppercased

6.9. String Methods

In [108]:
# Create a new string literal
my_string = "    Hello! My name is Jillur Quddus and I am a Chief Data Scientist and Principal Polyglot Software Engineer.    "
print(my_string)

# str.lower()
print(my_string.lower())

# str.upper()
print(my_string.upper())

# str.strip()
stripped_string = my_string.strip()
print(stripped_string)

# str.replace('find', 'replacewith')
initialized_string = stripped_string.replace('Jillur', 'J').replace('Quddus', 'Q')
print(initialized_string)

# str.find('substring')
print(initialized_string.find('Data Scientist'))

# str.startswith('substring')
print(initialized_string.startswith('Hello!'))

# str.endswith('substring')
print(initialized_string.endswith("Good Bye!"))

# str.split('delimiter')
print(initialized_string.split('!'))

# delimiter.join([list])
print('|'.join(['Chief Data Scientist', 'Principal Polyglot Software Engineer', 'Technical Architect']))
    Hello! My name is Jillur Quddus and I am a Chief Data Scientist and Principal Polyglot Software Engineer.    
    hello! my name is jillur quddus and i am a chief data scientist and principal polyglot software engineer.    
    HELLO! MY NAME IS JILLUR QUDDUS AND I AM A CHIEF DATA SCIENTIST AND PRINCIPAL POLYGLOT SOFTWARE ENGINEER.    
Hello! My name is Jillur Quddus and I am a Chief Data Scientist and Principal Polyglot Software Engineer.
Hello! My name is J Q and I am a Chief Data Scientist and Principal Polyglot Software Engineer.
39
True
False
['Hello', ' My name is J Q and I am a Chief Data Scientist and Principal Polyglot Software Engineer.']
Chief Data Scientist|Principal Polyglot Software Engineer|Technical Architect

7. Loops

7.1. While Loop

In [14]:
# Calculate the factorial of a given positive integer using a while loop
n = int(input('Please enter a positive integer value: '))
if n < 1:
    print('Please enter a positive integer value.')
else:
    factorial = 1
    counter = 1
    while counter <= n:
        factorial *= counter
        counter += 1
    print(f'The factorial of {n} is {factorial}')
Please enter a positive integer value: 7
The factorial of 7 is 5040

7.2. While-else

In [16]:
# Calculate the sum of the first 10 positive integer values using a while loop with else
counter = 1
sum = 0
while (counter <= 10):
     sum += counter
     counter += 1
else :
     print(f'The sum of first 10 positive integer values is {sum}')
The sum of first 10 positive integer values is 55

7.3. For Loop

In [17]:
# Iterate over a list of strings and print each element and its string length
shopping_list = ['Apples', 'Bananas', 'Potatoes', 'Tomatoes', 'Milk', 'Cheese', 'Bread', 'Eggs', 'Butter']
for shopping_item in shopping_list:
    print(f'{shopping_item}: {len(shopping_item)}')
Apples: 6
Bananas: 7
Potatoes: 8
Tomatoes: 8
Milk: 4
Cheese: 6
Bread: 5
Eggs: 4
Butter: 6

7.4. Range Function

In [21]:
# Range function with a single argument
for n in range(10):
    print(n)
0
1
2
3
4
5
6
7
8
9
In [22]:
# Range function with two arguments
for n in range(10, 20):
    print(n)
10
11
12
13
14
15
16
17
18
19
In [23]:
# Range function with three arguments
for n in range(10, 20, 2):
    print(n)
10
12
14
16
18

7.5. For-else Loop

In [25]:
# Attempt to enter a password three times using a for loop with the range function and else statement
for n in range(3):
    password_attempt = input('Please enter your password: ')
    if password_attempt == 'Passw0rd123!':
        print('Successful authentication')
        break
else:
    print('Your account has been locked after 3 failed attempts to login.')
    print('Please contact your system administrator to unlock your account.')
Please enter your password: d
Please enter your password: Passw0rd123!
Successful authentication

7.6. Break Statement

In [5]:
# Guess the number game demonstrating the break statement in a while loop
import random
random_number = random.randint(1, 30)
guess_counter = 0
guess_limit = 5
print('******** Guess the Number! ********')
print(f'I am thinking of a number between 1 and 30. Can you guess it in less than {guess_limit} attempts?')
while guess_counter < guess_limit:
    guess = int(input(f'Attempt #{guess_counter + 1} Enter your guess: '))
    guess_counter += 1
    if guess < random_number:
        print('Too low!')
    elif guess > random_number:
        print('Too high!')
    else:
        break

if guess == random_number:
    print(f'Congratulations! You guessed correctly in {guess_counter} attempts!')
else:
    print(f'Sorry! Game Over! The number I was thinking of was {random_number}.')
******** Guess the Number! ********
I am thinking of a number between 1 and 30. Can you guess it in less than 5 attempts?
Attempt #1 Enter your guess: 1
Too low!
Attempt #2 Enter your guess: 2
Too low!
Attempt #3 Enter your guess: 10
Too low!
Attempt #4 Enter your guess: 20
Too high!
Attempt #5 Enter your guess: 13
Too low!
Sorry! Game Over! The number I was thinking of was 14.

7.7. Continue Statement

In [11]:
# Print only non-dairy products from a shopping list using a for loop and continue statement
shopping_list = ['Apples', 'Bananas', 'Potatoes', 'Tomatoes', 'Milk', 'Cheese', 'Bread', 'Eggs', 'Butter']
dairy_products = ['Milk', 'Cheese', 'Eggs', 'Butter']
for shopping_item in shopping_list:
    if shopping_item in dairy_products:
        continue
    print(shopping_item)
Apples
Bananas
Potatoes
Tomatoes
Bread
In [14]:
# Print only the odd numbers in a given range using a while loop and continue statement
n = 0
while n < 10:
    n += 1
    if n % 2 == 0:
        continue
    print(n)
1
3
5
7
9

7.8. Nested Loops

In [21]:
# Render a rectangle of given dimensions using nested for loops
number_columns = 5
number_rows = 5
fill_character = '*'
for row in range(number_rows):
    print(fill_character, end=' ')
    for column in range(number_columns - 1):
        row *= column
        print(fill_character, end=' ')
    print('')
* * * * * 
* * * * * 
* * * * * 
* * * * * 
* * * * *