Wednesday, November 16, 2022

Python Programming for Beginners Practice Exercises

Python

Python is a high-level, general-purpose programming language. Its design philosophy emphasizes code readability with the use of significant indentation. Python is dynamically-typed and garbage-collected. It supports multiple programming paradigms, including structured, object-oriented and functional programming.

Here is a list of practice exercises and solutions to get started with Python programming.

  1. Exercise 1 - Strings and Variables
  2. Exercise 2 - Strings and Variables
  3. Exercise 3 - Strings and Variables
  4. Exercise 4 - Numbers
  5. Exercise 5 - Numbers
  6. Exercise 6 - Booleans and Conditionals
  7. Exercise 7 - Functions
  8. Exercise 8 - Lists
  9. Exercise 9 - Dictionaries
  10. Exercise 10 - Tuples
  11. Exercise 11 - Modules
  12. Exercise 12 - Files
  13. Exercise 13 - Files

Strings and Variables 3 - Python Programming for Beginners Practice Exercise

Exercise 3:

Write a Python program that prompts for input and displays a cat "saying" what was provided by the user. Place the input provided by the user inside a speech bubble. Make the speech bubble expand or contract to fit around the input provided by the user.

Sample Output:


Solution:

#!/usr/bin/env python3

text = input('What would you like the cat to say? ')
text_length = len(text)

print('            {}'.format('_' * text_length))
print('          < {} >'.format(text))
print('            {}'.format('-' * text_length))
print('          /')
print(' /\_/\   /')
print('( o.o )')
print(' > ^ <')

Strings and Variables 2 - Python Programming for Beginners Practice Exercise

Exercise 2:

Write a Python program that prompts the user for input and simply repeats what the user entered.

Sample Output:

Please type something and press enter: Hello there!
You entered:
Hello there!

Solution:

#!/usr/bin/env python3

user_input = input('Please type something and press enter: ')
print('You entered:')
print(user_input)

Strings and Variables 1 - Python Programming for Beginners Practice Exercise

Exercise 1:

Write a Python program that uses three variables. The variables in your program will be animal, vegetable, and mineral. Assign a string value to each one of the variables. Your program should display "Here is an animal, a vegetable, and a mineral." Next, display the value for animal, followed by vegetable, and finally mineral. Each one of the values should be printed on their own line. Your program will display four lines in total.

Sample Output:

Here is an animal, a vegetable, and a mineral.

dog

tomato

gold

Solution:

#!/usr/bin/env python3
animal = 'dog'
vegetable = 'tomato'
mineral = 'gold'

print('Here is an animal, a vegetable, and a mineral.')
print(animal)
print(vegetable)
print(mineral)

Tuples - Python Programming for Beginners Practice Exercise 10

Exercise 10:

Create a list of airports that includes a series of tuples containing an airport's name and its code. Loop through the list and utilize tuple assignment. Use one variable to hold the airport name and another variable to hold the airport code. Display the airport's name and code to the screen.

Sample Output:

The code for O’Hare International Airport is ORD.

The code for Los Angeles International Airport is LAX.

The code for Dallas/Fort Worth International Airport is DFW.

The code for Denver International Airport is DEN.

Solution:

#!/usr/bin/env python3

airports = [
    ("O’Hare International Airport", 'ORD'),
    ('Los Angeles International Airport', 'LAX'),
    ('Dallas/Fort Worth International Airport', 'DFW'),
    ('Denver International Airport', 'DEN')
]

for (airport, code) in airports:
    print('The code for {} is {}.'.format(airport, code))

Numbers 1 - Python Programming for Beginners Practice Exercise 4

Exercise 4:

Building on the previous example, let's also assume that you have saved $918 to fund your new adventure. You wonder how many days you can keep one server running before your money runs out. Of course, you hope your social network becomes popular and requires 20 servers to keep up with the demand. How much will it cost to operate at that point?

Write a Python program that displays the answers to the following questions:

How much does it cost to operate one server per day?

How much does it cost to operate one server per month?

How much does it cost to operate twenty servers per day?

How much does it cost to operate twenty servers per month?

How many days can I operate one server with $918?

Solution:

#!/usr/bin/env python3

# The cost of one server per hour.
cost_per_hour = 0.51

# Compute the costs for one server.
cost_per_day = 24 * cost_per_hour
cost_per_month = 30 * cost_per_day

# Compute the costs for twenty servers
cost_per_day_twenty = 20 * cost_per_day
cost_per_month_twenty = 20 * cost_per_month

# Budgeting
budget = 918
operational_days = budget / cost_per_day

# Display the results.
print('Cost to operate one server per day is ${:.2f}.'.format(cost_per_day))
print('Cost to operate one server per month is ${:.2f}.'.format(cost_per_month))
print('Cost to operate twenty servers per day is ${:.2f}.'.format(cost_per_day_twenty))
print('Cost to operate twenty servers per month is ${:.2f}.'.format(cost_per_month_twenty))
print('A server can operate on a ${0:.2f} budget for {1:.0f} days.'.format(budget, operational_days))

Numbers 2 - Python Programming for Beginners Practice Exercise 5

Exercise 5:

Let's assume you are planning to use your Python skills to build a social networking service. You decide to host your application on servers running in the cloud. You pick a hosting provider that charges $0.51 per hour. You will launch your service using one server and want to know how much it will cost to operate per day and per month.

Write a Python program that displays the answers to the following questions:

How much does it cost to operate one server per day?

How much does it cost to operate one server per month?

Solution:

#!/usr/bin/env python3

# The cost of one server per hour.
cost_per_hour = 0.51

# Compute the costs for one server.
cost_per_day = 24 * cost_per_hour
cost_per_month = 30 * cost_per_day

# Display the results.
print('Cost to operate one server per day is ${:.2f}.'.format(cost_per_day))
print('Cost to operate one server per month is ${:.2f}.'.format(cost_per_month))

Modules - Python Programming for Beginners Practice Exercise 11

Exercise 11:

Update the "What Did the Cat Say" program from an earlier section so that it can be run directly or imported as a module. When it runs as a program is should prompt for input and display a cat "saying" what was provided by the user. Place the input provided by the user inside a speech bubble. Make the speech bubble expand or contract to fit around the input provided by the user.

Sample output when run interactively


Next, create a new program called cat_talk.py that imports the cat_say module. Use a function from the cat_say() module to display various messages to the screen.

Sample output when used as a module:


Solution 1:

#!/usr/bin/env python3

def cat_say(text):
    """Generate a picture of a cat saying something"""
    text_length = len(text)
    print('            {}'.format('_' * text_length))
    print('          < {} >'.format(text))
    print('            {}'.format('-' * text_length))
    print('          /')
    print(' /\_/\   /')
    print('( o.o )')
    print(' > ^ <')

def main():
    text = input('What would you like the cat to say? ')
    cat_say(text)

if __name__ == '__main__':
    main()

Solution 2:

#!/usr/bin/env python3

import cat_say

def main():
    cat_say.cat_say('Feed me.')
    cat_say.cat_say('Pet me.')
    cat_say.cat_say('Purr.  Purr.')

if __name__ == '__main__':
    main()

Tuesday, November 15, 2022

Lists - Python Programming for Beginners Practice Exercise 8

Exercise 8:

Create a Python program that captures and displays a person's to-do list. Continually prompt the user for another item until they enter a blank item. After all the items are entered, display the to­do list back to the user.

Sample Output:


Enter a task for your to-do list. Press <enter> when done: Buy cat food.
Task added.
Enter a task for your to-do list. Press <enter> when done: Mow the lawn.
Task added.
Enter a task for your to-do list. Press <enter> when done: Take over the world.
Task added.
Enter a task for your to-do list. Press <enter> when done:

Your To-Do List:
-------------------
Buy cat food.
Mow the lawn.
Take over the world.

Solution:

#!/usr/bin/env python3

# Create a list to hold the to-do tasks.
to_do_list = []
finished = False
while not finished:
    task = input('Enter a task for your to-do list.  Press  when done: ')
    if len(task) == 0:
        finished = True
    else:
        to_do_list.append(task)
        print('Task added.')

# Display the to-do list.
print()
print('Your To-Do List:')
print('-' * 16)
for task in to_do_list:
    print(task)

Functions - Python Programming for Beginners Practice Exercise 7

Exercise 7:

Create a fill in the blank word game. Prompt the user to enter a noun, verb, and an adjective. Use those responses to fill in the blanks and display the story.

Write a short story. Remove a noun, verb, and an adjective.

Create a function to get the input from the user.

Create a function that fills in the blanks in the story you created.

Ensure each function contains a docstring.

After the noun, verb, and adjective have been collected from the user, display the story using their input.

Solution:

#!/usr/bin/env python3

def get_word(word_type):
    """Get a word from a user and return that word."""

    # The lower() function converts the string to lowercase before testing it
    if word_type.lower() == 'adjective':
        # Use 'an' in front of 'adjective'
        a_or_an = 'an'
    else:
        # Otherwise, use 'a' in front of 'noun' or 'verb'
        a_or_an = 'a'
    return input('Enter a word that is {0} {1}: '.format(a_or_an, word_type))


def fill_in_the_blanks(noun, verb, adjective):
    """Fills in the blanks and returns a completed story."""

    # The \ lets the string continue on the next line to make the code easier to read
    story = "In this course you will learn how to {1}.  " \
            "It's so easy even a {0} can do it.  " \
            "Trust me, it will be very {2}.".format(noun, verb, adjective)
    return story


def display_story(story):
    """Displays a story."""
    print()
    print('Here is the story you created.  Enjoy!')
    print()
    print(story)


def create_story():
    """Creates a story by capturing the input and displaying a finished story."""
    noun = get_word('noun')
    verb = get_word('verb')
    adjective = get_word('adjective')

    the_story = fill_in_the_blanks(noun, verb, adjective)
    display_story(the_story)

create_story()

Files 1 - Python Programming for Beginners Practice Exercise 12

Exercise 12:

Read the contents of animals.txt and produce a file named animals­sorted.txt that is sorted alphabetically.

The contents of animals.txt:

man
bear
pig
cow
duck
horse
dog

Sample Output:

bear
cow
dog
duck
horse
man
pig

Solution:

#!/usr/bin/env python3

unsorted_file_name = 'animals.txt'
sorted_file_name = 'animals-sorted.txt'
animals = []

try:
    with open(unsorted_file_name) as animals_file:
        for line in animals_file:
            animals.append(line)
    animals.sort()
except:
    print('Could not open {}.'.format(unsorted_file_name))

try:
    with open(sorted_file_name, 'w') as animals_sorted_file:
        for animal in animals:
            animals_sorted_file.write(animal)
except:
    print('Could not open {}.'.format(sorted_file_name))

Files 2 - Python Programming for Beginners Practice Exercise 13

Exercise 13:

Create a program that opens file.txt. Read each line of the file and prepend it with a line number.

The contents of files.txt:

This is line one.
This is line two.
Finally, we are on the third and last line of the file.

Sample Output:

1: This is line one.
2: This is line two.
3: Finally, we are on the third and last line of the file.

Solution:

#!/usr/bin/env python3

with open('file.txt') as file:
    line_number = 1
    for line in file:
        print('{}: {}'.format(line_number, line.rstrip()))
        line_number += 1

Dictionaries - Python Programming for Beginners Practice Exercise 9

Exercise 9:

Create a dictionary that contains a list of people and one interesting fact about each of them. Display each person and their interesting fact to the screen. Next, change a fact about one of the people. Also add an additional person and corresponding fact. Display the new list of people and facts. Run the program multiple times and notice if the order changes.

Sample Output:

Jeff: Is afraid of clowns.
David: Plays the piano.
Jason: Can fly an airplane.
Jeff: Is afraid of heights.
David: Plays the piano.
Jason: Can fly an airplane.
Jill: Can hula dance.



Solution:

#!/usr/bin/env python3

def display_facts(facts):
    """Displays facts"""
    for fact in facts:
        print('{}: {}'.format(fact, facts[fact]))
    print()

facts = {
    'Jason': 'Can fly an airplane.',
    'Jeff':  'Is afraid of clowns.',
    'David': 'Plays the piano.'
}

display_facts(facts)

facts['Jeff'] = 'Is afraid of heights.'
facts['Jill'] = 'Can hula dance.'

display_facts(facts)

Booleans and Conditionals - Python Programming for Beginners Practice Exercise 6

Exercise 6:

Create a program that asks the user how far they want to travel. If they want to travel less than three miles tell them to walk. If they want to travel more than three miles, but less than three hundred miles, tell them to drive. If they want to travel three hundred miles or more tell them to fly.

Sample Output:

How far would you like to travel in miles? 2500
I suggest flying to your destination.

Solution:

#!/usr/bin/env python3

# Ask for the distance.
distance = input('How far would you like to travel in miles? ')

# Convert the distance to an integer.
distance = int(distance)

# Determine what mode of transport to use.
if distance < 3:
    mode_of_transport = 'walking'
elif distance < 300:
    mode_of_transport = 'driving'
else:
    mode_of_transport = 'flying'

# Display the result.
print('I suggest {} to your destination.'.format(mode_of_transport))

Thursday, September 1, 2022

(Solved) HTTP Error 503, the service is unavailable

Error Message:

HTTP Error 503, the service is unavailable

Reason:

This error occurring because of any of the following reasons,
  • The Application pool is stopped.
  • The server itself turned-off. 
  • The user identity which is running the application pool is outdated. The password might have changed.

Thursday, August 18, 2022

(Solved) ORA-01031: insufficient privileges error when using Oracle.ManagedDataAccess.EntityFramework

For me this issue occured while migrating .net framework from 4.0 to 4.8. I am using entiry framework to connect to database. As I was connecting to Oracle databse using Oracle.ManagedDataAccess 19.3, I had to upgrade it to latest version Oracle.ManagedDataAccess 21.7 nuget. With that we need to install latest version of Oracle.ManagedDataAccess.EntityFramework also.

Solution for this is, add the below code in DBContext constructor or Application_Start method in Global.asax class.

Reason for this error is, each time DBContext object initializes the Entity Framework was trying to create Oracle table under user that does not have permissions. If you work with existing database disable the initializer like mentioned below. Otherwise each table will be recreated based on C# class definition.

public EmployeeDbContext(): base("name=OracleConnection")
{
    Database.SetInitializer(null);
}

Or,
protected void Application_Start(Object sender, EventArgs e)  
{ 
     Database.SetInitializer(null); 
}

Friday, May 27, 2022

(Solved) XUnit Test not getting discovered in Visual Studio Test Explorer

Make sure you have all the below NuGet packages added in your test project. So that all test methods will be displayed in Test Explorer window.

  • xunit
  • xunit.runner.visualstudio
  • Microsoft.NET.Test.Sdk

Wednesday, April 6, 2022

How to calculate Age based on a birthday in C#

Here is a sample code to calculate Age based on a birthday in C#.
using System;
public class HelloWorld
{
    public static void Main(string[] args)
    {
        DateTime birthdate = DateTime.ParseExact("1989-02-25", "yyyy-MM-dd",                                               System.Globalization.CultureInfo.InvariantCulture);
        var today = DateTime.Today;
        
        var age = today.Year - birthdate.Year;
        
        today.AddYears(-age);
        
        Console.WriteLine (age);
    }
}

How to get the path of the assembly of your code is in

Here is a sample code to get the path of the assembly of your code is in.
    string codeBase = Assembly.GetExecutingAssembly().CodeBase;
    UriBuilder uri = new UriBuilder(codeBase);
    string path = Uri.UnescapeDataString(uri.Path);
    var assemblyPath = Path.GetDirectoryName(path);

How to get the assembly file version in C#

Here is a sample code to get assembly file version in C#.
System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
System.Diagnostics.FileVersionInfo fvi = System.Diagnostics.FileVersionInfo.GetVersionInfo(assembly.Location);
string version = fvi.FileVersion;

Another approach is,
var version = Application.ProductVersion;
This approach requires reference to below namespace.
System.Windows.Forms

Tuesday, April 5, 2022

What is Recursion in Programming

Recursion is calling a function itself multiple times to solve a given problem. Just like loops, you also need to specify when that function should stop calling itself. Such a condition is called as the base condition. 

For example, consider the below code which prints "Hello World" repeatedly. The showMessage function calls itself multiple times but the base condition is not defined and hence, this leads to an infinite loop.
function showMessage(n) {
    console.log("Hello world ", n);
    showMessage(n - 1);
}

showMessage(10);

Now, observe the code after adding the base condition. When n becomes 0, the recursive call stops.
function showMessage(n){
    if(n==0){
        return;
    }
    console.log("Hello world ",n);
    showMessage(n-1);
}

showMessage(10);
Let us see how to use recursion to perform some calculations. The below code calculates the sum of first n numbers.
function sum(n){
    if(n==1){
        return 1
    }
    else{
        return n+sum(n-1);
    }
}

var sumResult=sum(10);
console.log(sumResult);

Every recursion can be replaced with an equivalent iteration statement. Recursive algorithms are usually slower than iterative algorithms. In the above example which calculates the sum of first n numbers. Here, the sum of first 10 numbers is checked. If you want the sum of first 600000 numbers, the recursive code will crash. Interestingly, the below iterative algorithm to calculate the sum of n numbers has the same complexity, O(n).
function sum(n){
    var sum=0;
    while(n!=0){
        sum+=n;
        n--;
    }
    return sum;
}

var sumResult=sum(600000);
console.log(sumResult);

But the below equivalent code has a time complexity of O(1).
function sum(n){
    return n*(n+1)/2;
}

However, recursive algorithms have below advantages: 
  • Recursion adds clarity and sometimes reduces the time needed to write and debug code. 
  • Performs better in solving problems based on tree structures.