5 Python Projects for Engineering Students

In this tutorial, we'll look at a wide range of Python projects, suitable for everybody from beginners to experienced developers. These projects are designed to give you hands-on experience with Python, allowing you to develop applications that are practical. Either you're just getting started with coding or want to improve your Python skills, you'll find a project that suits your ability levels and interests you.

Cows and Bulls game

Cows and Bulls is a traditional pen-and-paper code-breaking activity for two people. Here is the way it works:

  1. One person creates a secret code, which is usually a number with four digits with no repetitions.
  2. The other player then tries to guess this secret number. After each guess, they receive two types of feedback: the number of "Bulls" and "Cows."
  3. "Bulls" count how many digits in the guess are correct and in the right position. "Cows" count how many digits are correct but in the wrong position. For example, if the hidden code is 1234 but your guess is 1246, the result is 2 Bulls (for 1 and 2 being in the proper position) and 1 Cow (for 4 being accurate yet in the incorrect area).
  4. Players keep guessing until someone cracks the code. The winner is the one who figures out the secret number in the fewest attempts.

Approach

To construct this Python game, a computer produces a secret code, which the player must guess. Let us break it down into the following stages:

Generate a Secret Code:

  • Generate a random 4-digit number.
  • Ensure the number has no repeated digits.

Generate Hint or Response:

  • Take the generated 4-digit secret number and the guessed number (input).
  • Identify the digits that match exactly (bulls) and the common digits in the wrong positions (cows).
  • Continue the procedure for each guess unless the user receives four bulls (an precise match) or runs out of attempts.

Constraint:

  • Either the hidden code and the anticipated code should be four-digit numbers (between 1000 and 9999) that shouldn't have any repeats.

Code

Output:

 
Enter the number of attempts: 5
Enter your guess: 4567
0 bulls, 2 cows
Enter your guess: 7890
0 bulls, 3 cows
Enter your guess: 6789
1 bulls, 2 cows
Enter your guess: 4567
0 bulls, 2 cows
Enter your guess: 3456
1 bulls, 0 cows
Out of attempts! The secret code was 9706.   

Code Explanation:

The given code provides a basic version of the "Bulls and Cows" games. Following is an illustrated explanation of how the program works:

  • Defining Functions:
    • extract_digits(number): This method accepts a number that is an integer and outputs a list of its digits. For instance, the function extract_digits(1234) will provide [1, 2, 3, 4].
    • has_unique_digits(number): This function checks if the given number has all unique digits. It uses the extract_digits function to get the list of digits and then compares the length of this list with the length of the set (which removes duplicates) of these digits. If both lengths are equal, the number has unique digits; otherwise, it doesn't.
    • create_secret_code(): This method creates a random four-digit number with each digit distinct. It creates arbitrary numbers in the range of 1000 to 9999 until it discovers one unique digit using the has_unique_digits function. The first number that meets the criteria is returned as the secret code.
    • evaluate_bulls_and_cows(secret_code, user_guess): This function evaluates the number of "bulls" and "cows" for a given guess compared to the secret code.
      • "Bulls" are digits in the guess that are in the correct position.
      • "Cows" are digits in the guess that are in the secret code but not in the correct position.
    • It uses the extract_digits function to convert both the secret code and the user guess into lists of digits. It then iterates through these lists to count bulls and cows and returns the counts as a list [bulls, cows].
  • Generate Secret Code:
    • secret_code = create_secret_code(): This line generates a random secret code using the create_secret_code function.
    • Get Number of Attempts = int(input('Enter the number of attempts: ')): This section allows users to specify the number of attempts they'd like to make at identifying the secret code.
    • Game Loop: A while loop runs as long as there are attempts left (attempts > 0).
    • Inside the loop: The user is prompted to enter their guess. The software determines if the estimate contains distinct characters and is a four-digit number. If the prediction is correct, the software calls the evaluate_bulls_and_cows method to count the number of bulls and cows. It then outputs the total amount of bulls and cows. If the total amount of bulls is four, the user successfully guesses the secret code, and the software praises the user before exiting the loop. If the estimate is inaccurate, the total number of attempts is reduced by one. If the consumer does not guess the secret code after a certain number of tries, the software displays it.

The game requires the player to figure out a randomly generated 4-digit password containing unique digits. After every guess, the person making the guess is given a certain number of attempts and gets response in a picture of bulls (correct digit and position) or cows (correct digit but incorrect position). The game continues unless the user correctly guesses the secret code or runs exhausted tries.

Word Guessing Game

Python is a very adaptable language for programming that is utilized by many of the the globe's leading technology businesses. Its syntax is simple and easy to understand, making it a great option for novices who are just beginning out with coding. Python is a high-level language with an emphasis on code readability, enabling programmers to express their thoughts with a smaller amount of code.

In this section, we'll look at how to use Python's random module to create a word guessing game. This game is designed for beginners that are beginning to code and will teach you essential ideas like strings, loops, and expressions with conditions (such as if and then).

The Random Module: Say you need the machine to choose an amount at random, a product from a list, or perhaps flip a coin. The random module in Python offers functions to handle these tasks. One of its handy functions is random.choice(), which can pick a random element from a list, tuple, or string. This method will be used in our game to choose the word at random from the list which we have created.

You're going to begin this game by providing your name. Following that, at random, an item from the list will be chosen. Your objective is to determine the characters that make up the word. If the character you choose is in the word, it will be presented in the appropriate spot following each guess. If a particular letter is not found in the word, you will be invited to attempt another letter. You have up to twelve tries to precisely guess the complete word.

Here's how you can implement this game in Python:

Code:

Output:

 
What's your name? honey
Good ,  honey
Guess the letters!
_ _ _ _ _ _ 
Guess a letter: a
Incorrect guess.
You have 11 attempts remaining.
_ _ _ _ _ _ 
Guess a letter: y
Incorrect guess.
You have 10 attempts remaining.
_ _ _ _ _ _ 
Guess a letter: e
_ _ _ _ e _ 
Guess a letter: a
Incorrect guess.
You have 9 attempts remaining.
_ _ _ _ e _ 
Guess a letter: t
Incorrect guess.
You have 8 attempts remaining.
_ _ _ _ e _ 
Guess a letter: w
Incorrect guess.
You have 7 attempts remaining.
_ _ _ _ e _ 
Guess a letter: r
_ _ _ _ e r 
Guess a letter: w
Incorrect guess.
You have 6 attempts remaining.
_ _ _ _ e r 
Guess a letter: e
_ _ _ _ e r 
Guess a letter: t
Incorrect guess.
You have 5 attempts remaining.
_ _ _ _ e r 
Guess a letter: r
_ _ _ _ e r 
Guess a letter: a
Incorrect guess.
You have 4 attempts remaining.
_ _ _ _ e r 
Guess a letter: b
Incorrect guess.
You have 3 attempts remaining.
_ _ _ _ e r 
Guess a letter: c
Incorrect guess.
You have 2 attempts remaining.
_ _ _ _ e r 
Guess a letter: d
Incorrect guess.
You have 1 attempts remaining.
_ _ _ _ e r 
Guess a letter: e
_ _ _ _ e r 
Guess a letter: f
Incorrect guess.
You have 0 attempts remaining.
Sorry, you've lost.
The word was:  summer   

Time Complexity: O(k)

  • Here, k represents the length of the word being processed.

Auxiliary Space: O(n)

  • In this case, n is the size of the list used in the program.

Code Explanation:

  • import random: This line of code loads Python's built-in random module, containing methods for creating random numbers and creating random choices.
  • user_name = input("what's your name?"): The following line invites people to provide a username, which is stored in a variable called user_name.
  • print("Good, ", user_name): This line of code displays a welcome a message, which includes a user's name.
  • ['winter','summer', 'lion','seasons', 'weather']: The following statement generates a list of phrases from which of them will be picked at random for use in the course of play.
  • The line selected_word = random.choice(word_list) selects at random a single word out of the word_list and puts it as the value of the value of the variable selected_word.
  • print("Guess the letters!"): The following line displays a prompt asking the person using it to begin guessing each letter of the chosen word.
  • guessed_letters = '': This creates a string with no characters to keep track of the characters that that the individual has guessed thus far.
  • attempts_left = 12: This specifies the number of attempts that the individual must make to properly identify the word.The user starts with 12 attempts.
  • while attempts_left > 0: This starts a loop that continues as long as the user has attempts remaining.
  • incorrect_guesses = 0: Inside the loop, this initializes a counter to track the number of incorrect guesses for the current round.
  • for letter in selected_word: This loop goes through each letter in the selected_word.
  • if letter in guessed_letters: This checks if the current letter has been guessed correctly by the user.
  • print(letter, end=""): If the word was correctly predicted, it is written; else, nothing is printed.
  • print("_", end=" "): If the initial letter is not guessed, a space is displayed to denote the missing letter.
  • incorrect_guesses += 1: If a particular letter was not guessed, the incorrect_guesses counter is increased by one.
  • if incorrect_guesses == 0: After checking all letters, this condition checks if all letters have been guessed correctly.
  • print("\nCongratulations! You've won!"): If all letters are guessed correctly, this line prints a winning message.
  • print("The word was: ", selected_word): This prints the word that was guessed correctly.
  • break: This exits the loop if the user has guessed all letters correctly.
  • print(): This prints a newline for formatting purposes.
  • user_guess = input("Guess a letter: "): This invites the user to guess the letter and saves the result in the user_guess attribute.
    The user's estimate is added to the guessed_letters string by using the += operator.
  • If the user_guess is not in the selected_word: This determines if your guessed character is present in the chosen word.
  • attempts_left -= 1: If the estimate is wrong, this section reduces the total amount of remaining tries by one.
  • print("Incorrect guess."): This prints a message indicating that the guess was incorrect.
  • print("You have", attempts_left, "attempts remaining."): This displays the number of attempts the user has left.
  • if attempts_left == 0: This checks if the user has run out of attempts.
  • print("Sorry, you've lost."): If no attempts are left, this line prints a losing message.
  • print("The word was: ", selected_word): This reveals the selected word to the user.

Number Guessing Game in Python

In this match, the player chooses a range of integers from which the computer selects a random number. The user's aim is to estimate how many there are in the fewest number of attempts feasible. The process begins with the consumer selecting a range, such as from A to B, wherein A and B are numbers. The computer selects an amount at random from A to B. The user then begins to estimate this figure.

Example 1:

In Example 1, suppose a user selects a range of 1 to 100. The value of 42 is selected at random by the machine in question. Here's how the competition may go:

  • First Guess: The user guesses 50. The computer responds, "Try Again! You guessed too high." This indicates 42 is less than 50, hence the individual may conclude whether the real number falls between 1 and 49.
  • Second Guess: The user then guesses 25. The computer says, "Try Again! You guessed too small." So now the user knows the number is between 26 and 49.
  • Third Guess: The user tries 37. The computer replies, "Try Again! You guessed too small." The range is now narrowed down to between 38 and 49.
  • Fourth Guess: Next, the user guesses 43. The computer says, "Try Again! You guessed too high." This means the number must be between 38 and 42.
  • Fifth Guess: The user guesses 40. The computer replies, "Try Again! You guessed too small." So, the number is between 41 and 42.
  • Sixth Guess: The user guesses 41. The computer says, "Try Again! You guessed too small." Now the only possibility is 42.
  • Seventh Guess: The user finally guesses 42 correctly.
  • In this example, it took 7 guesses to find the number.

Example 2:

Assume that the individual selects a range of 1 to 50, and the computer chooses a value of 42. Here's another possible sequence of guesses:

  • First Guess: The user guesses 25. The computer says, "Try Again! You guessed too small." Now the range is between 26 and 50.
  • Second Guess: The user guesses 37. The computer replies, "Try Again! You guessed too small." The range is now 38 to 50.
  • Third Guess: The user tries 43. The computer says, "Try Again! You guessed too high." The range narrows down to 38 to 42.
  • Fourth Guess: The user guesses 40. The computer replies, "Try Again! You guessed too small." The range is now 41 to 42.
  • Fifth Guess: The user tries 41. The computer says, "Try Again! You guessed too small." The only remaining possibility is 42.
  • Sixth Guess: The user guesses 42 and wins.
  • In this case, it took 6 guesses to find the number.

Calculating Minimum Guesses

The minimum number of guesses needed depends on the range. To estimate this, you can use the formula:

Step-by-Step Algorithm

  1. User Input: The user's input specifies both the lower and higher limits of the range.
  2. Random Number Generation: The machine selects an arbitrary number from the specified range.
  3. Guessing Loop: The game runs a loop where the user keeps guessing.
    1. If the guess is too high, the computer says, "Try Again! You guessed too high."
    2. If the guess is too low, the computer says, "Try Again! You guessed too small."
    3. If the user makes the correct guess, the machine congratulates them.
  4. Outcome: If users fail to guess a certain amount in the projected minimal number of guesses, the computer exclaims, "Better Luck Next Time!"

Users may use this game to improve their guess abilities and learn the importance of narrowing up alternatives with each guess.

Code:

Output:

 
Enter the minimum boundary: 20
Enter the maximum boundary: 50
You have only  5  attempts to guess the number!
Guess a number: 21
Your guess is too low!
Guess a number: 34
Your guess is too high!
Guess a number: 26
Your guess is too low!
Guess a number: 27
Your guess is too low!
Guess a number: 28
Your guess is too low!
The number was 32
	Better luck next time!   

Code Explanation:

Here's a breakdown of the code:

  • Import Required Libraries:
    • random: Used to generate random numbers.
    • math: Used for mathematical operations.
  • Get User Input for Boundaries:
    • min_bound = int(input("Enter the minimum boundary: ")): Asks the consumer to specify the minimal border of the range and transforms it into a single integer.
    • max_bound = int(input("Enter the maximum boundary: ")): Asks the user to specify the range's highest border, which is then converted to an integers.
  • Generate Target Number:
    • target_number = random.randint(min_bound, max_bound): The desired number is chosen at randomly from the range of min_bound to max_bound (inclusive).
  • Calculate Maximum Attempts:
    • max_attempts = math.ceil(math.log(max_bound - min_bound + 1, 2)): Determines the greatest number of authorized tries depending on the range of integers. It estimates the number of guesses required for a binary search technique using the logarithm base 2 and adjusts it up to make sure there are sufficient attempts.
  • Inform User About Attempts:
    • print("\n\tYou have only ", max_attempts, " attempts to guess the number!"): The amount of attempts required for the user to estimate how many is displayed.
  • Initialize Variables:
    • attempt_count = 0: Keeps track of the number of attempts the user has made.
    • success = False: Flag to indicate if the user has successfully guessed the number.
  • Start Guessing Loop:
    • while attempt_count < max_attempts: Loops until the user runs out of attempts or guesses the number correctly.
  • Process User Guess:
    • attempt_count += 1: Increments the attempt counter.
    • user_guess = int(input("Guess a number:")): Asks the consumer to guess a number, which is then converted to an integers.
    • If target_number matches user_guess: Inspections to see whether the estimated number is right.
    • If correct, prints a congratulatory message, updates the success flag to True, and breaks out of the loop.
    • elif target_number > user_guess: Checks if the guessed number is too low and informs the user.
    • elif target_number > user_guess: Checks if the guessed number is too high and informs the user.
  • End of Loop:
    • If not success: If the user did not guess the number within the allowed attempts. Prints the target number and a message indicating the user failed.

The code essentially creates a number guessing game in which each player has a restricted number of chances to correctly guess a randomly generated number within a given range.

Time Complexity:

The time complexity of the above code is O(log2n), where n is the variance among the lower and higher bounds of the range.

Space Complexity:

This code has a space complexity of O(1) since every variable is the same size and no additional space is required to store data.

Pokémon Training Game

As a Pokémon instructor, you go on an exciting trip in which each Pokémon that meet has an individual strength level, denoted by a positive number. Your goal is to keep track of these strength ratings while you capture Pokémon. After each catch, you need to display the highest and lowest power levels of the Pokémon you've caught so far. To achieve this efficiently, you'll need to ensure your solution runs in linear time complexity-meaning sorting the data isn't an option. Additionally, aim to minimize extra space usage.

Here's how you can do it:

Example:

Suppose you catch Pokémon with power levels 1, 2, 3, and 4 in that order. After each catch, you should print the minimum and maximum power levels observed up to that point. The output should look like this:

  • After catching Pokémon with power 1: 1 1
  • After catching Pokémon with power 2: 1 2
  • After catching Pokémon with power 3: 1 3
  • After catching Pokémon with power 4: 1 4

Input:

A single line listing the power levels of the Pokémon caught in sequence.

Output:

For each Pokémon caught, output two numbers on a new line: the minimum and maximum power levels seen so far, separated by a space.

Code:

Output:

 
1 1
1 2
1 3
1 4   

Code Explanation:

Here's a step-by-step explanation of the code:

  • Initialize List and Variables:
    • strengths = [1, 2, 3, 4]: This refers to a list of numbers that indicate specific values.
    • lowest, highest = 0, 0: Both variables, lowest and highest, have been set to zero.
  • Loop Through the List:
    • for strength in strengths: The loop iterates over each element in the strengths list.
  • First Iteration Check:
    • if lowest == 0 and highest == 0: Checks if both lowest and highest are still 0. This condition holds only during the initial iteration (when the two variables are originally set to 0).
    • lowest, highest = strengths[0]: The smallest and greatest values have been set to the first member of the strengths list (which in this case is 1).
    • print(lowest, highest): Returns the present values for lowest and the greatest, the two of which are 1.
  • Subsequent Iterations:
    • else: This block runs for the rest of the iterations after the first one.
    • lowest = min(lowest, strength): Updates lowest to the minimum of the current lowest and the current strength.
    • highest = max(highest, strength): Updates highest to the maximum of the current highest and the current strength.
    • print(lowest, highest): Prints the updated values of lowest and highest. During the first iteration, it prints 1 1 (as both lowest and highest are initially set to 1). In subsequent iterations, it prints the updated values of lowest and highest as the loop progresses through the strengths list.

In summary, the code iterates through the list, updates lowest and highest to reflect the minimum and maximum values encountered so far and prints these values at each step.

FLAMES Game

Python is an extremely adaptable language that can handle a variety of jobs, include game creation. In this post, we will step through the process of constructing a simple FLAMES game in Python without the use of any additional gaming frameworks such as PyGame.

FLAMES is an entertaining game that stands for Friends, Lovers, Affectionate, Marriage, Enemies, and Siblings. Although it is not scientifically reliable in evaluating marital reliability, it may be entertaining for playing with friends. This is what a game works.

How to Play FLAMES?

  1. Start with Two Names
    Begin by taking two names. For example, let's use "HONEY" and "LASYA."
  2. Remove Common Characters
    Next, you'll eliminate the common characters between the two names. This means you'll compare the characters and remove those that appear in both names, taking into account their frequency.
  3. Count the Remaining Characters
    After removing the common characters, count how many characters are left in both names combined.
  4. Use the FLAMES Acronym
    FLAMES stands for Friends, Lovers, Affectionate, Marriage, Enemies, and Sibling. Begin with this list and start removing letters based on the count you got from the previous step.
    Count around the FLAMES list in a circular fashion. For instance, if your count is 5, start counting from "F," and the letter in the 5th position is removed. Continue this process with the remaining letters until only one letter remains.

Example Walkthrough

  • Let's apply this with names "HONEY" and "LASYA."
  • Common letters between "HONEY" and "LASYA" are "A" and "Y."
  • Remove these common characters:
  • "HONEY" becomes "HONE."
  • "LASYA" becomes "LSY."
  • The total remaining characters are 5 (HONE + LSY = 5 letters).
  • Apply FLAMES:
    • Start with FLAMES: ["F", "L", "A", "M", "E", "S"].
    • Count 5 positions in a circular manner:
    • From "F," count 5 letters: "E" is removed.
    • Now we have ["F", "L", "A", "M", "S"].
    • Count 5 positions again: "M" is removed.
    • Now we have ["F", "L", "A", "S"].
  • Continue this process:
    • Remove "S," then "L," leaving us with "F" and "A."
    • Remove "A," leaving "F."
    • The final letter is "F," which stands for "Friends."

In Python, you can implement this with a function to handle the character removal and the FLAMES counting. Here's a basic example:

Code:

Output:

 
Enter the first name: honey
Enter the second name: lasy
Relationship status: Enemy   

Code Explanation:

Here's a breakdown of the code in a point-by-point manner:

  • Function Definition:
    • eliminate_matching_chars(first_list, second_list): The above function accepts a pair of characters and removes every character that are identical in both.
  • Nested Loops for Comparison:
    • The nested loops for i in range(len(first_list)) and for j in range(len(second_list)) go over every word in first_list and second_list, accordingly.
  • Matching Character Check:
    • If first_list[i] == second_list[j]: If a compatible character is detected, delete it out of both lists.
  • Updating Lists:
    • first_list.remove(char) and second_list.remove(char): Remove the matching character from both lists.
  • Combine Lists with Separator:
    • combined_list = first_list + ["*"] + second_list: Combine the modified first_list and second_list with a separator *.
  • Return Results:
    • return [combined_list, True]: If a match was found and removed, return the combined list and True.
    • If no match was found, combine the lists with a separator and return [combined_list, False].
  • Main Section:
    • name1 and name2: Request that the user provide two names, which will subsequently be transformed to lowercase, and spaces eliminated.
    • list1 and list2: Convert the cleaned names into lists of characters.
  • Processing Loop:
    • while continue_processing: Continuously process the lists until no more matching characters can be removed.
    • result = eliminate_matching_chars(list1, list2): Call the function and update the lists based on the result.
  • Separator Index:
    • separator_index = combined_list.index("*"): Obtain the value of the index of the separator * in the merged list.
    • list1 = combined_list[:separator_index], and list2 = combined_list[separator_index + 1]: Divide the entire list into two sections: current list1 and updated list2.
  • Calculate Total Count:
    • total_count = len(list1) + len(list2): Compute the total number of characters remaining.
  • FLAMES Calculation:
    • flames_categories: A list of relationship categories.
    • while len(flames_categories) > 1: Keep reducing the list until only one category remains.
    • split_index = (total_count % len(flames_categories) - 1): Determine the index to split the list.
      Update flames_categories based on the split index.
  • Display Result:
    • print("Relationship status:", flames_categories[0]): Print the final relationship status based on the remaining category.

In essence, this code is an implementation of the "FLAMES" game, which determines the relationship status between two names based on the number of remaining characters after eliminating matches.

Conclusion

Exploring Python projects such as the Cow-Bulls Game, FLAMES Game, Number Guessing Game, Word Guessing Game, and Pokémon Training Game offers engineering students a hands-on approach to learning programming and problem-solving. Each project is designed to address different aspects of coding and logic.

The Cow-Bulls Game challenges students to implement algorithms for guessing a secret number based on hints, which enhances their skills in string manipulation and logical reasoning. Similarly, the FLAMES Game requires students to create a program that calculates relationship status based on name inputs, providing practical experience with list operations and control flow.

The Number Guessing Games is a traditional way to learn about fundamental programming concepts including loops, conditionals, and input from users processing. This project emphasizes creating an engaging user experience while implementing fundamental coding techniques. The Word Guessing Game builds on this by requiring students to manage word lists and handle various game states, pushing them to develop more sophisticated logic and user interface designs.

Finally, the Pokémon Training Game introduces students to more advanced concepts like object-oriented programming and data management. Students may use their skills by modeling a Pokémon training scenario to develop a complicated, interactive game that integrates several methods of programming.

These projects work together to provide a full educational experience, allowing students to reinforce their Python knowledge while also improving problem-solving abilities. They additionally lay the groundwork for future projects that will include more complicated coding issues.