0% found this document useful (0 votes)
5 views25 pages

Mca306 A1 PDF

The document provides a comprehensive guide on installing Python and PyCharm, testing a basic Python program in both interactive and script modes, and implementing a basic calculator program. It also includes examples of string manipulation functions, finding the longest word in a list, and counting occurrences of an element in a list. Each section contains code snippets and explanations to facilitate understanding and implementation.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views25 pages

Mca306 A1 PDF

The document provides a comprehensive guide on installing Python and PyCharm, testing a basic Python program in both interactive and script modes, and implementing a basic calculator program. It also includes examples of string manipulation functions, finding the longest word in a list, and counting occurrences of an element in a list. Each section contains code snippets and explanations to facilitate understanding and implementation.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Assignment

NAME – Md Shadab
ROLL NO. -2723760002

SUBJECT – Programming with Python


SUBJECT CODE – MCA306
Assignment - 0 1
Q1 : Installation of python and Pycharm (IDEforPython) and test a
basic python program in both Script and Interactive mode
ANS: Installation of Python and PyCharm (IDE for Python)

Here's a step-by-step guide to install Python and PyCharm, followed by


testing a basic Python program in both script and interactive modes.

1. Install Python

1. Download Python:
- Go to the official [Python
website](https://www.python.org/downloads/).
- Choose the appropriate version for your operating system
(Windows, macOS, or Linux).
- For most users, the latest stable version (e.g., Python 3.x) is
recommended.

2. Install Python:
Windows:
- Run the installer and check the box "Add Python to PATH" before
clicking Install Now.
- This ensures Python is accessible from the command line.
-macOS/Linux:
- Python is usually pre-installed, but you can install the latest version
using a package manager (like `brew` for macOS or `apt` for Linux).
- On macOS: `brew install python3`
- On Linux (Debian/Ubuntu): `sudo apt install python3`

3. Verify Installation:
- Open the terminal (or Command Prompt on Windows) and run:
```bash
python --version
```
You should see the installed version of Python.

2. Install PyCharm (IDE for Python)

1. Download PyCharm:
- Go to the [PyCharm download
page](https://www.jetbrains.com/pycharm/download/).
- You can choose between the Professional version (paid) or the
Community version (free). For most basic Python development, the
Community edition is sufficient.

2. Install PyCharm:
- Follow the installer instructions for your operating system:
- Windows: Run the `.exe` installer.
- macOS: Open the `.dmg` file and drag PyCharm into your
Applications folder.
- Linux: Extract the tarball and follow the setup instructions.

3. Launch PyCharm:
- After installation, launch PyCharm.
- When first opening PyCharm, it may ask you to configure some
settings (e.g., theme, plugins). You can use the default settings.

4. Configure Python Interpreter in PyCharm:


- Open PyCharm and create a new project.
- Go to File > Settings > Project: [Your Project Name] > Python
Interpreter.
- Select the Python interpreter (usually Python 3.x) that you installed
earlier.

---

3. Test a Basic Python Program in Both Script and Interactive Mode

a. Interactive Mode (Python Shell)


1. Open Python Shell:
- Open a terminal (or Command Prompt) and type:
```bash
python
```
This opens the interactive Python shell where you can type and
execute Python code line-by-line.

2. Run a Simple Program:


- Type the following:
```python
print("Hello, World!")
```
- Press Enter. The output will be:
```
Hello, World!
```

3. Exit the Shell:


- To exit the Python shell, type `exit()` or press `Ctrl+D` on
Linux/macOS or `Ctrl+Z` on Windows.
b. Script Mode (Running a Python File)

1. Create a Python Script:


- Open PyCharm.
- Create a new project if you haven't already, then create a new
Python file. Right-click on the project folder, select New > Python File,
and name it (e.g., `hello_world.py`).

2. Write the Python Program:


- Inside the `hello_world.py` file, type:
```python
print("Hello, World!")
```

3. Run the Script:


- Click the Run button in PyCharm (usually a green triangle icon in the
top-right corner).
- You should see the output in the Run window at the bottom of
PyCharm:
```
Hello, World!
```
4. Run the Script from the Command Line (Optional):
- You can also run the script from the command line. Navigate to the
folder where your `.py` file is saved and type:
```bash
python hello_world.py
```
- The output will be:
```
Hello, World!
```
Summary:

- Python: Installed and verified through terminal or command prompt.


- PyCharm: Installed and configured as the IDE for Python
development.
- Interactive Mode: You ran a Python script directly in the Python shell.
- Script Mode: You wrote and ran a Python script using PyCharm.

You now have Python and PyCharm set up and have tested a basic
program in both interactive and script modes.
Q2: Write a Program to perform basic functions of a calculator
using functions.
ANS: Python program to implement a basic calculator with functions
for addition, subtraction, multiplication, and division. The program will
prompt the user to input two numbers and then select an operation
(addition, subtraction, multiplication, or division).

Python Code for a Basic Calculator:

```python
Function to add two numbers
def add(x, y):
return x + y

Function to subtract two numbers


def subtract(x, y):
return x - y

Function to multiply two numbers


def multiply(x, y):
return x y

Function to divide two numbers


def divide(x, y):
if y == 0:
return "Error! Division by zero."
else:
return x / y

Function to display the menu and get user's choice


def display_menu():
print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Exit")

Main program
def calculator():
while True:
Display the menu
display_menu()

Take the user's choice


choice = input("Enter choice (1/2/3/4/5): ")

Check if user wants to exit


if choice == '5':
print("Exiting the calculator.")
break

Check if the choice is valid


if choice in ['1', '2', '3', '4']:
Input two numbers
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
except ValueError:
print("Invalid input! Please enter numerical values.")
continue

Perform the calculation based on the user's choice


if choice == '1':
print(f"{num1} + {num2} = {add(num1, num2)}")
elif choice == '2':
print(f"{num1} - {num2} = {subtract(num1, num2)}")
elif choice == '3':
print(f"{num1} {num2} = {multiply(num1, num2)}")
elif choice == '4':
print(f"{num1} / {num2} = {divide(num1, num2)}")
else:
print("Invalid input! Please choose a valid option.")

Run the calculator program


if __name__ == "__main__":
calculator()
```

Explanation of the Program:

1. Functions:
- `add(x, y)`: Returns the sum of `x` and `y`.
- `subtract(x, y)`: Returns the difference between `x` and `y`.
- `multiply(x, y)`: Returns the product of `x` and `y`.
- `divide(x, y)`: Returns the quotient of `x` divided by `y`, with an error
message if division by zero is attempted.

2. Main Calculator Function (`calculator()`):


- The program runs in a loop, repeatedly showing the user the
available operations (Add, Subtract, Multiply, Divide, Exit).
- It takes the user's choice and performs the corresponding operation.
- It validates the user's input and checks if the numbers entered are
valid (`float` type).
- If the user chooses "5", the program exits.

3. Menu Display:
- `display_menu()` function shows the list of operations available to
the user.

4. Input Validation:
- If the user enters invalid input (like a string when a number is
expected), the program will prompt them again for valid input.

Sample Output:

```
Select operation:
1. Add
2. Subtract
3. Multiply
4. Divide
5. Exit
Enter choice (1/2/3/4/5): 1
Enter first number: 10
Enter second number: 5
10.0 + 5.0 = 15.0

Select operation:
1. Add
2. Subtract
3. Multiply
4. Divide
5. Exit
Enter choice (1/2/3/4/5): 4
Enter first number: 10
Enter second number: 2
10.0 / 2.0 = 5.0

Select operation:
1. Add
2. Subtract
3. Multiply
4. Divide
5. Exit
Enter choice (1/2/3/4/5): 5
Exiting the calculator.
```

Features:
- Error handling for division by zero.
- Input validation to ensure the user enters valid numerical values.
- Ability to repeat calculations until the user chooses to exit.

Q3: Write….
a program to demonstrate the following string functions:

Print odd length words in a string

Remove all duplicates in a string.

Convert the case of each character. Calculate the length of a string.


ANS: Python program that demonstrates the following string functions:

1. Print odd length words in a string.


2. Remove all duplicates in a string.
3. Convert the case of each character.
4. Calculate the length of a string.

Python Program:

```python
Function to print odd length words in a string
def print_odd_length_words(string):
words = string.split() Split the string into words
print("Odd length words are:")
for word in words:
if len(word) % 2 != 0:
print(word)

Function to remove duplicates in a string


def remove_duplicates(string):
unique_chars = set(string) Convert the string to a set to remove
duplicates
return ''.join(unique_chars)

Function to convert the case of each character


def convert_case(string):
return string.swapcase() Swap lowercase to uppercase and vice
versa

Function to calculate the length of a string


def calculate_length(string):
return len(string)

Main program
if __name__ == "__main__":
input_string = input("Enter a string: ")

Print odd length words


print_odd_length_words(input_string)

Remove duplicates
no_duplicates = remove_duplicates(input_string)
print("\nString after removing duplicates:", no_duplicates)

Convert case
converted_case = convert_case(input_string)
print("\nString after converting case:", converted_case)
Calculate the length of the string
string_length = calculate_length(input_string)
print("\nLength of the string:", string_length)
```

Explanation of the Functions:

1. `print_odd_length_words(string)`:
- Splits the input string into words using `split()`.
- Iterates through each word and checks if its length is odd (using
`len(word) % 2 != 0`).
- Prints all words with an odd length.

2. `remove_duplicates(string)`:
- Converts the string to a `set`, which automatically removes any
duplicate characters (since sets do not allow duplicates).
- Then, it joins the characters back into a string using `''.join()` and
returns it.

3. `convert_case(string)`:
- Uses the `swapcase()` method to convert each lowercase letter to
uppercase and vice versa in the string.
4. `calculate_length(string)`:
- Uses Python's built-in `len()` function to return the length of the
string.

Sample Output:

Input:
```
Enter a string: Hello world from Python
```

Output:

```
Odd length words are:
world
from
Python

String after removing duplicates: Helow rdfmPtyn

String after converting case: hELLO WORLD FROM pYTHON


Length of the string: 25
```

Details on the Output:

1. Odd length words:


- Words with an odd number of characters are printed (`world`,
`from`, and `Python`).

2. Removing duplicates:
- The program removes any duplicate characters in the string. For
example, "Hello" becomes "Helo".

3. Converting case:
- It swaps the case of each character in the string. For example,
"Hello" becomes "hELLO".

4. Length of the string:


- The length of the original string is calculated using `len()`, which in
this case is 25.
Q4: Write a Python function that takes a list of words and return the
longest word and the length of the longest one.
ANS: Python function that takes a list of words and returns the longest
word along with its length:

Python Function:

```python
def longest_word(words):
Check if the list is empty
if not words:
return None, 0 Return None and length 0 if the list is empty

Find the longest word in the list


longest = max(words, key=len)

Return the longest word and its length


return longest, len(longest)

Example usage
words_list = ["apple", "banana", "cherry", "pineapple", "kiwi"]
longest, length = longest_word(words_list)
print(f"The longest word is: {longest}")
print(f"The length of the longest word is: {length}")
```

Explanation:

1. Input:
- The function `longest_word` takes a list of words as input.

2. Check for empty list:


- Before proceeding, we check if the list is empty using `if not words`.
If the list is empty, we return `None` and a length of `0`.

3. Find the longest word:


- The `max()` function is used with the `key=len` argument, which tells
Python to find the element in the list with the maximum length.
- `max(words, key=len)` returns the longest word in the list.

4. Return the result:


- The function returns the longest word along with its length using
`len(longest)`.

Example Usage:
For the list `["apple", "banana", "cherry", "pineapple", "kiwi"]`, the
output would be:

```
The longest word is: pineapple
The length of the longest word is: 9
```

Edge Case Handling:

- If the input list is empty (`[]`), the function will return `None` and `0`,
indicating there is no word in the list.

Q5: Here's a Python program that creates a list and counts the
occurrence of a specific element in that list:
ANS:
Python Program:

```python
Function to count the occurrence of an element in the list
def count_occurrence(lst, element):
return lst.count(element)

Example usage
if __name__ == "__main__":
Create a list of elements
my_list = [1, 2, 3, 4, 2, 5, 6, 2, 7]

Input the element to count


element_to_count = int(input("Enter the element to count its
occurrence: "))

Get the count of the element


count = count_occurrence(my_list, element_to_count)

Output the result


print(f"The element {element_to_count} occurs {count} times in the
list.")
```

Explanation:

1. Function `count_occurrence(lst, element)`:


- This function takes two arguments: the list `lst` and the `element`
whose occurrence is to be counted.
- It uses the built-in `.count()` method of a list, which returns the
number of occurrences of the `element` in the list.

2. Example Usage:
- The program first creates a list of numbers, `my_list = [1, 2, 3, 4, 2,
5, 6, 2, 7]`.
- It then prompts the user to input an element for which to count the
occurrences.
- The function `count_occurrence` is called with the list and the input
element, and the count is printed.

Sample Output:

Input:
```
Enter the element to count its occurrence: 2
```

Output:
```
The element 2 occurs 3 times in the list.
Edge Case Considerations:
- If the element is not found in the list, the `.count()` method will return
`0`, indicating that the element doesn't appear in the list.

You might also like