0% found this document useful (0 votes)
3 views

Programming 4

The document outlines a programming assignment for CS 1101, which involves creating a function to calculate the hypotenuse of a right triangle using the Pythagorean theorem and implementing a random password generator. It details the steps for importing necessary libraries, defining functions, validating inputs, and generating passwords with optional special characters. The assignment includes code snippets and instructions for testing the functions created.

Uploaded by

shumbapraise71
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Programming 4

The document outlines a programming assignment for CS 1101, which involves creating a function to calculate the hypotenuse of a right triangle using the Pythagorean theorem and implementing a random password generator. It details the steps for importing necessary libraries, defining functions, validating inputs, and generating passwords with optional special characters. The assignment includes code snippets and instructions for testing the functions created.

Uploaded by

shumbapraise71
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 34

CS 1101 - Programming Assignment Unit 4

Course:

Programming Fundamentals (CS 1101)


NAME: PRAISEGOD SHUMBA
University: University of the People
Part1.
Step 1: Understanding the Task

The task is to develop a function that calculates the length of the hypotenuse of a right triangle given the lengths of

the other two sides (legs). The formula for this calculation is derived from the Pythagorean theorem: \(c = \sqrt{a^2

+ b^2}\), where \(c\) is the length of the hypotenuse, and \(a\) and \(b\) are the lengths of the other two sides.

Step 2: Importing Necessary Libraries

To perform mathematical calculations such as square root, we need to import Python's built-in `math` library. This

library provides functions for various mathematical operations.

Screenshot.
Step # 2:

Defining the Function.

Screenshot.

Let's define a simple function called `calculate_hypotenuse` that takes the lengths of the two legs (`a` and `b`) as

arguments.

```

def calculate_hypotenuse(a, b):

# Function body will go here

pass

```
Step 3:

Implementing the Pythagorean Theorem

Now, we'll add the Pythagorean theorem formula to the function using Python's `math.sqrt()` function to calculate

the square root.

```

def calculate_hypotenuse(a, b):

hypotenuse = math.sqrt(a**2 + b**2)

return hypotenuse

```

This function calculates the length of the hypotenuse given the lengths of the other two sides.

Screenshot
Screenshot.

Step 4:

Testing the Function

Let's test the `calculate_hypotenuse` function with the provided arguments (3, 4), which represent the lengths of the

two legs of a right triangle.

```

import math

def calculate_hypotenuse(a, b):

hypotenuse = math.sqrt(a**2 + b**2)

return hypotenuse
Test the function

result = calculate_hypotenuse(3, 4)

print("The length of the hypotenuse is:", result)

```

This code will calculate and print the length of the hypotenuse for a right triangle with legs of length 3 and 4.

Screenshot

Output screenshot.
Additional calls.

Call 1 screenshot.

Screenshot.

Output screenshot.
Call 2

Screenshot.

Output screenshot

Part 2.

Step 1:
Importing Necessary Libraries

To create a random password generator, we'll use Python's built-in `random` and `string` libraries.
- `random`: Provides functionality for generating random numbers and selections, which we'll use to pick random

characters for the password.

- `string`: Offers predefined constants like `ascii_letters`, `digits`, and `punctuation`, making it easy to define

character sets for the password.

```

import random

import string

```

Screenshot.
Step#2.

Core function to generate password.

Screenshot.

Screenshot
Step 3:

Defining Character Sets

We'll define different sets of characters that will be used to build the password. These sets include:

- `letters`: All uppercase and lowercase letters

- `digits`: Numbers from 0 to 9

- `symbols`: Special characters (if `include_symbols` is True)

```

characters = string.ascii_letters + string.digits

if include_symbols:

characters += string.punctuation

```

This code combines the character sets based on the `include_symbols` parameter, allowing us to generate

passwords with or without special characters.

Screenshot.
Step 3: Defining Character Sets

We'll define the character sets as follows:

- `letters`: `string.ascii_letters` (both lowercase and uppercase alphabets)

- `digits`: `string.digits` (digits from 0 to 9)

- `symbols`: `string.punctuation` if `include_symbols` is True, otherwise an empty string

```

letters = string.ascii_letters

digits = string.digits

symbols = string.punctuation if include_symbols else ""

characters = letters + digits + symbols

```

This code sets up the character sets based on the `include_symbols` parameter, determining whether special

symbols are included in the password generation.


Step 4:

Combining Character Sets

To generate a password with a mix of alphabets, numbers, and special symbols (if included), we'll combine the

character sets:

```

characters = string.ascii_letters + string.digits + (string.punctuation if include_symbols else "")

```

This combined character set will be used to randomly select characters and generate the password.

Screenshot.

Screenshot.
Step 5.

Validating Password Length

We'll check if the password length is valid. If the length is less than 1, we'll raise an error.

```

if length < 1:

raise ValueError("Password length must be at least 1")

```

This validation ensures that the password length is reasonable and prevents potential issues during password

generation.

Screenshot.
Step 6.

Generating the Password

We'll use a loop to select random characters from the combined character

set and generate the password.

```

password = ''.join(random.choice(characters) for _ in range(length))

```

This code generates a password of the specified length by randomly choosing characters from the combined set of

letters, digits, and symbols (if included).

Screenshot.

Here's the breakdown:


- `random.choice(characters)`: Picks a random character from the combined set.

- `for _ in range(length)`: Ensures the password has the correct length by repeating the random selection process.

- `''.join(...)`: Concatenates the randomly selected characters into a single string, creating the final password.

Step 7.

Creating the Main Function

Here's the main function that interacts with the user:

```

def main():

print("Welcome to the Random Password Generator!")

while True:

try:

length = int(input("Enter the length of the password: "))

if length < 1:

print("Password length must be at least 1. Please try again.")

else:

break

except ValueError:

print("Invalid input. Please enter a valid number.")

include_symbols = input("Include special symbols? (yes/no): ").lower() == "yes"

# Call the password generation function here .


This main function:

- Displays a welcome message

- Asks the user for the password length and validates the input

- Asks the user if they want to include special symbols

- Prepares to call the password generation function with the user's input.

Screenshot.
The loop ensures the user enters a valid length by:

- Repeatedly asking for input until a valid length is entered

- Using a try-except block to catch and handle invalid inputs (like non-numeric values)

- Breaking out of the loop once a valid length is provided.

Step 8

Asking for Special Characters

We'll ask the user if they want to include special characters in their password:

```

include_symbols = input("Include special symbols? (yes/no): ").lower() == "yes"

This code:

- Asks the user for input

- Converts the input to lowercase for case-insensitive comparison

- Sets `include_symbols` to `True` if the user enters "yes", and `False` otherwise.

Screenshot.
Step 9

The password is generated using the generate password function.

Screenshot

Step 10.

Screenshot.
Three outputs of the function.

Screenshot.

Screenshot
Screenshot.
Reference.

Downey, A. (2015). Think Python: How to think like a computer scientist. Needham,

Massachusetts: Green Tree

Press. htps:/igreenteapress.com/thinkpython2/thinkpython2. pdf

https://docS,pvthon.org/3Aibrary/random.htmlhttps:docs.pvthon.org31ibrary/string.htmlhttps:/

realpython.com'documenting-python-code

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy