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
In this module we will continue to cover the fundamental building blocks of the Python programming language, namely:
# 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))
# The common len() function given a string
my_string = 'Hello World!'
print(len(my_string))
# A common string method that will return the string all in uppercase
my_string = 'Hello World!'
print(my_string.upper())
# Input function without a prompt message argument
full_name = input()
print(f'Your Full Name is: {full_name}')
# 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}!')
# Integer input using the int function (default base 10)
age = int(input('Please enter your age: '))
print(f'You are {age} years old')
# 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')
# Floating point input using the float function
height = float(input('Please enter your height in metres: '))
print(f'You are {height}m tall')
# Without the str function we cannot concatenate a number to a string
pi = 3.141592653589793238462643
print('The value of π is: ' + pi)
# The str function will convert pi into a string
print('The value of π is: ' + str(pi))
# Print a given string
print("My name is Jillur Quddus")
# Print a given collection of strings
print("Software Engineer", "Data Scientist", "Technical Architect")
# Print a given collection of strings with a separator
print("Software Engineer", "Data Scientist", "Technical Architect", sep=', ')
# Print a list of occupations on the same line
print("My Roles", end=": ")
print("Software Engineer", "Data Scientist", "Technical Architect", sep=', ')
# Print the value of e (Eulers number) using formatted string literals
e = 2.718281828459045235360287
print(f'The value of e is {e}')
# Print the value of e but to 3 decimal points
print(f'The value of e to 3 decimal points is {e:.3f}')
# Print age as a number of days
age = int(input('Please enter your age: '))
print(f'You are at least {age * 365} days old')
# 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}')
# 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")
# 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")
# 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")
# 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")
# 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")
# 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!")
# 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")
# Create an empty list
empty_list = []
# Create a list containing the first five square numbers
squares = [1, 4, 9, 16, 25]
print(squares)
# Access elements in a list by their index numbers
print(squares[0])
print(squares[3])
print(squares[-1])
print(squares[-4])
# 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])
# Define an end index that is purposefully too large
print(squares[0:100])
# Length of a list
print(f'The length of the squares list is: {len(squares)} elements')
# 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")
# Modify a specific element in a list
squares[0] = 0
print(squares)
# Revert to the original value
squares[0] = 1
print(squares)
# Remove a specific element from a list
del squares[-1]
print(squares)
# Delete a list collection entirely
del empty_list
print(empty_list)
# Append all elements from more_squares to squares
more_squares = [25, 36, 49, 64, 81, 100]
updated_squares = squares + more_squares
print(updated_squares)
# 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)
# 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)
# 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)
# 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])
# Calculate the length of a string
print(len(lorem_ipsum))
# 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!")
# 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)
# Try to create a string containing illegal characters
illegal_string = "My name is "Jillur""
# Escape the illegal characters using the backslash character
legal_string = "My name is \"Jillur\""
print(legal_string)
# 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)
# 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")
# 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']))
# 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}')
# 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}')
# 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)}')
# Range function with a single argument
for n in range(10):
print(n)
# Range function with two arguments
for n in range(10, 20):
print(n)
# Range function with three arguments
for n in range(10, 20, 2):
print(n)
# 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.')
# 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}.')
# 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)
# 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)
# 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('')