[go: up one dir, main page]

0% found this document useful (0 votes)
22 views12 pages

Codes Output

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)
22 views12 pages

Codes Output

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/ 12

All 15 python codes with explanation and output

1) Here is a python programme to guess a number from


between 1 to 10 import random
number_to_guess = random.randint(1, 10)
guess = None
while guess != number_to_guess:
guess = int(input("Guess a number between 1 and 10: "))
print("You won!")

# Execution of the code by line by line


#Generate a random number:
number_to_guess = random.randint(1, 10)
*This generates a random number between 1 and 10 (inclusive).*
# Initialize the variable:
guess = None
*guess is initialized to None so it doesn't match number_to_guess at the start.*
# Set up a loop
while guess != number_to_guess:
*The loop continues as long as the guess does not equal the randomly generated number.*
# Take user input:
guess = int(input("Guess a number between 1 and 10: "))
*The program asks the user for a guess, which is converted to an integer.*
# End the game
print("You won!")
*When the user guesses the correct number, the loop exits, and the program congratulates the user.*
import random
choices = ["rock", "paper", "scissors"]

2) Python code for basic "Rock, Paper, Scissors" game, where a user competes against the
computer

Code:-
computer_choice = random.choice(choices)
user_choice = input("Enter rock, paper, or scissors: ")
if user_choice == computer_choice:
print("Tie!")
elif (user_choice == "rock" and computer_choice == "scissors") or \
(user_choice == "scissors" and computer_choice == "paper") or \
(user_choice == "paper" and computer_choice == "rock"):
print("You win!")
else:
print("Computer wins!")

Code Functionality:

1. Random Choice for the Computer:


o The computer randomly selects one of the three options: "rock", "paper", or "scissors".
2. User Input:
o The user inputs their choice.
3. Comparison Logic:
o If the user's choice matches the computer's, the result is a tie.
o If the user's choice beats the computer's according to the game rules, the user wins.
o Otherwise, the computer wins.
Sample Output:

If the user enters "rock" and the computer chooses "scissors",


the output will be:
You win!
If both choose "paper",
the output will be:
Tie!
If the user enters "scissors" and the computer selects "rock",
the output will be:
Computer wins!

3) Python calculator program that performs basic arithmetic operations: addition, subtraction,
multiplication, and division. It takes user input to choose the operation and the numbers to
operate on.
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
if y == 0:
return "Error: Division by zero"
return x / y
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
choice = input("Enter choice (1/2/3/4): ")
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))
elif choice == '2':
print(num1, "-", num2, "=", subtract(num1, num2))
elif choice == '3':
print(num1, "*", num2, "=", multiply(num1, num2))
elif choice == '4':
print(num1, "/", num2, "=", divide(num1, num2))
else:
print("Invalid choice")

How It Works:

1. Functions for Operations:


o The program defines four functions (add, subtract, multiply, divide) to handle the respective
operations.
o The divide function includes a check to prevent division by zero.
2. User Interaction:
o The user selects an operation by enterin0g a number (1-4) corresponding to the desired operation.
o The program then asks for two numbers to perform the chosen operation.
3. Conditional Execution:
o Based on the user's choice, the program calls the corresponding function and prints the result.
o An invalid choice triggers an error message.
Sample Output Scenarios:

Valid Input:

If the user enters 1 (Add), 5 (first number), and 3 (second number):


5.0 + 3.0 = 8.0
If the user enters 4 (Divide), 6 (first number), and 0 (second number):
6.0 / 0.0 = Error: Division by zero
Invalid Input:
If the user enters 5 as the choice:
Invalid choice

4) Python programme to generates the Fibonacci sequence up to the specified number of terms
(n).
n = int(input("Enter number of terms: "))
a, b = 0, 1
for i in range(n):
print(a)
a, b = b, a + b

Code Explanation:

1. User Input:
o The program prompts the user to enter the number of terms (n) for the Fibonacci sequence.
2. Initial Values:
o The first two terms of the Fibonacci sequence are initialized: a = 0 and b = 1.
3. Loop to Generate the Sequence:
o A for loop iterates n times.
o In each iteration:
 The current term (a) is printed.
 The next term is computed by updating a and b to b and a + b, respectively.

Sample Output:

Input:
Enter number of terms: 6
Output:
0
1
1
2
3
5

5) Python programme to check if a number is prime or not


num = int(input("Enter a number: "))
if num > 1:
for i in range(2, num):
if num % i == 0:
print(num, "is not a prime number")
break
else:
print(num, "is a prime number")
else:
print(num, "is not a prime number")
How the Code Works:

1. User Input:
o The program prompts the user to input a number.
2. Prime Number Definition:
o A prime number is greater than 1 and only divisible by 1 and itself.
3. Logic:
o If the number is greater than 1:
 The program iterates from 2 to num-1 using a for loop.
 If any number in this range divides num evenly (remainder is 0), the number is not prime,
and the loop exits with a break.
 If the loop completes without finding a divisor, the else block executes, confirming that the
number is prime.
o If the number is 1 or less, it is directly declared not a prime number.

Sample Output:
Input:
Enter a number: 7
Output:
7 is a prime number
Input:
Enter a number: 10
Output:
10 is not a prime number

6) Python dictionaries, including accessing, modifying, and adding data


student = {
"name": "John",
"age": 20,
"grades": [90, 85, 95]
}
print(student)
print(student["name"])
print(student.get("age"))
student["country"] = "USA"
print(student)
code demonstrates basic operations with Python dictionaries, including accessing, modifying, and adding data.
Here's a breakdown:

Code Explanation:

1. Dictionary Initialization:
o A dictionary student is created with the following key-value pairs:
 "name": "John"
 "age": 20
 "grades": [90, 85, 95]
2. Accessing the Entire Dictionary:
o print(student) displays the full dictionary content.
3. Accessing Specific Values:
o print(student["name"]): Directly retrieves the value of the "name" key.
o print(student.get("age")): Uses the get() method to fetch the value of "age". This method is
safer because it returns None instead of raising a KeyError if the key does not exist.
4. Adding a New Key-Value Pair:
o student["country"] = "USA" adds a new key "country" with the value "USA" to the dictionary.
5. Displaying the Updated Dictionary:
o The final print(student) shows the modified dictionary.
Sample Output:
{'name': 'John', 'age': 20, 'grades': [90, 85, 95]}
John
20
{'name': 'John', 'age': 20, 'grades': [90, 85, 95], 'country': 'USA'}

Enhancements:

1. Using get() with Default Value:


o If you access a key that might not exist, you can provide a default value:
2. print(student.get("major", "Not specified"))

Output:

Not specified

3. Updating Existing Values:


o You can modify an existing key's value:
4. student["age"] = 21
5. print(student)

Output:

{'name': 'John', 'age': 21, 'grades': [90, 85, 95], 'country': 'USA'}

6. Removing a Key:
o Use pop() to remove a key-value pair:
7. student.pop("country")
8. print(student)

Output:

{'name': 'John', 'age': 20, 'grades': [90, 85, 95]}

9. Iterating Over a Dictionary:


o Display all keys and values:
10. for key, value in student.items():
11. print(f"{key}: {value}")

Output:

name: John
age: 20
grades: [90, 85, 95]
country: USA

12. Adding Multiple Entries:


o Use update() to add or update multiple key-value pairs:
13. student.update({"major": "Computer Science", "year": "Sophomore"})
14. print(student)

Output:

{'name': 'John', 'age': 20, 'grades': [90, 85, 95], 'country': 'USA', 'major':
'Computer Science', 'year': 'Sophomore'}
7) Python task management program with added functionality

todos = []

while True:

print("\n=== Task Manager ===")

print("1. Add task")

print("2. View tasks")

print("3. Exit")

choice = input("Enter choice: ")

if choice == '1':

task = input("Enter task: ").strip()

if task:

todos.append(task)

print(f"Task '{task}' added successfully!")

else:

print("Task cannot be empty.")

elif choice == '2':

if todos:

print("\nYour tasks:")

for idx, task in enumerate(todos, start=1):

print(f"{idx}. {task}")

else:

print("No tasks available.")

elif choice == '3':

print("Exiting Task Manager. Goodbye!")

break

else:

print("Invalid choice. Please enter 1, 2, or 3.")

Code Improvements:

1. Enhanced Display for Tasks:


o Format the task list for readability.
o Handle the case when there are no tasks.
2. Task Numbering:
o Number tasks when displaying them.
3. Edge Cases:
o Validate user input for better error handling.
Sample Output:

When Adding a Task:

=== Task Manager ===


1. Add task
2. View tasks
3. Exit
Enter choice: 1
Enter task: Buy groceries
Task 'Buy groceries' added successfully!

When Viewing Tasks:

=== Task Manager ===


1. Add task
2. View tasks
3. Exit
Enter choice: 2

Your tasks:
1. Buy groceries

When No Tasks Are Available:

=== Task Manager ===


1. Add task
2. View tasks
3. Exit
Enter choice: 2
No tasks available.

When Exiting:

=== Task Manager ===


1. Add task
2. View tasks
3. Exit
Enter choice: 3
Exiting Task Manager. Goodbye!

8) Write a python programme to checks whether a given string is a palindrome or not.

def is_palindrome(s):
return s == s[::-1]
string = input("Enter a string: ")
if is_palindrome(string):
print(string, "is a palindrome")
else:
print(string, "is not a palindrome")

The is_palindrome function compares the string s with its reverse (s[::-1]) and returns True if they are the same.

It uses the input function to take a string from the user.

It checks if the input string is a palindrome using the is_palindrome function and prints the appropriate message.

Output:

Enter a string: hello

> hello is not a palindrome


9. Data Analysis with Pandas
import pandas as pd
data = {'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 28]}
df = pd.DataFrame(data)
print(df)
print(df.head())
print(df.describe())

Explanation and Output:

1. print(df)

This prints the entire DataFrame df.

Output:

Name Age
0 Alice 25
1 Bob 30
2 Charlie 28

2. print(df.head())

The head() method prints the first 5 rows of the DataFrame. Since this DataFrame has only 3 rows, it will print all
of them.

Output:

Name Age
0 Alice 25
1 Bob 30
2 Charlie 28

3. print(df.describe())

The describe() method provides summary statistics for numeric columns (e.g., Age).

Output:

Age
count 3.000000
mean 27.666667
std 2.516611
min 25.000000
25% 26.500000
50% 28.000000
75% 29.000000
max 30.000000

Summary:

 The DataFrame contains names and ages of three people.


 The head() method displays the first few rows of the DataFrame.
 The describe() method calculates statistical details like mean, standard deviation, minimum, and
maximum for numeric columns.
10. Python programme to print all the prime numbers between the given range.
lower = int(input("Enter lower range: "))
upper = int(input("Enter upper range: "))
print("Prime numbers between", lower, "and", upper, "are:")
for num in range(lower, upper + 1):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num)
program correctly identifies and prints all prime numbers in the specified range.

Enter lower range: 10


Enter upper range: 50
Prime numbers between 10 and 50 are:
11
13
17
19
23
29
31
37
41
43
47

11. Programe File Input/Output (data handling)


with open("file.txt", "w") as f:
f.write("Hello, World!")
with open("file.txt", "r") as f:
print(f.read())
code meaning
with open("file.txt", "w") as f: # Open 'file.txt' in write mode

f.write("Hello, World!") # Write "Hello, World!" to the file

with open("file.txt", "r") as f: # Open 'file.txt' in read mode

print(f.read()) # Read and print the contents of the file

code demonstrates how to write to a file and then read its contents in Python. Here's a detailed explanation and
example of how it works:
Explanation:

1. File Writing:
o The with open("file.txt", "w") as f: line opens a file named file.txt in write mode ("w").
o If file.txt does not exist, it is created. If it exists, its content is overwritten.
o The f.write("Hello, World!") line writes "Hello, World!" to the file.
2. File Reading:
o The with open("file.txt", "r") as f: line opens the same file in read mode ("r").
o The f.read() method reads the file's content, which is then printed.
3. The with Statement:
o Automatically closes the file after the block of code is executed, ensuring resources are released
properly.

Output:
Hello, World!

12. Remove Duplicates


Write a Python program to remove duplicate elements from a list
def remove_duplicates(numbers):
unique_numbers = []
for num in numbers:
if num not in unique_numbers:
unique_numbers.append(num)
return unique_numbers
# Example usage:
input_list = [1, 2, 3, 1, 2, 4, 5, 4]
output_list = remove_duplicates(input_list)
print(output_list)
function remove_duplicates works perfectly for removing duplicates while maintaining the original order of the
elements in the list

Output:

[10, 20, 30, 40]

13. greatest common divisor and the least common multiple of two integers.
num1=int(input('Enter First Number: ' ))
num2=int(input('Enter Second Number: '))
a=num1
b=num2
lcm=0
while(num2!=0):
temp=num2
num2=num1%num2
num1=temp
gcd=num1
lcm=((a*b)/gcd)
print('\n HCF or GCD of',a, 'and',b,'is=',gcd)
print('\n LCM of',a, 'and',b,'is=',lcm)
program calculates both the GCD (Greatest Common Divisor) and LCM (Least Common Multiple) of two numbers using the
Euclidean algorithm

Enter First Number: 20

Enter Second Number: 40

HCF or GCD of 20 and 40 is= 20

LCM of 20 and 40 is= 40.0

14 code generates a pyramid pattern using asterisks (*).


n = int(input("Enter the number of rows for the pyramid: "))
for i in range(n): # Loop for each row
for j in range(n - i - 1): # Print spaces for alignment
print(" ", end="")
for j in range(i + 1): # Print stars in each row
print("*", end=" ")
print() # Move to the next line after completing a row

Explanation:

1. Outer Loop (for i in range(n)):


o Controls the number of rows.
o The value of i determines the current row (0-indexed).
2. First Inner Loop (for j in range(n - i - 1)):
o Prints spaces (" ") for alignment.
o The number of spaces decreases as i increases.
3. Second Inner Loop (for j in range(i + 1)):
o Prints asterisks (*) followed by a space (" ").
o The number of asterisks increases as i increases.
4. print():
o Moves the cursor to the next line after printing each row.

Sample Execution:
Input:
Enter the number of rows for the pyramid: 5
Output:
*
* *
* * *
* * * *
* * * * *

15. Python programme to cheque if the number is equal to the sum of the
cubes of its digits
num = int(input("Enter a number: ")) # Input a number
sum = 0
temp = num
# Calculate the sum of the cubes of the digits
while temp > 0:
modulus = temp % 10 # Extract the last digit
sum += modulus ** 3 # Add the cube of the digit to sum
temp //= 10 # Remove the last digit
# Check if the sum is equal to the original number
if sum == num:
print("The number is equal to the sum of the cubes of its digits and it is an Armstrong number.")
else:
print("The number is not equal to the sum of the cubes of its digits and it is not an Armstrong number.")

Explanation:

1. Input: A number is provided by the user.


2. Initialization:
o sum: Used to store the sum of the cubes of the digits.
o temp: A copy of the original number to preserve its value for comparison.
3. Processing:
o The while loop iterates over the digits of the number by repeatedly extracting the last digit
(modulus) using the modulus operator % and dividing by 10 to remove it (temp //= 10).
o For each digit, its cube is added to sum.
4. Comparison:
o After processing all digits, the program checks whether sum is equal to the original number (num).
o If true, it prints that the number is an Armstrong number; otherwise, it states that it is not.

Example Execution:

Input:

Enter a number: 153

Output:

The number is equal to the sum of the cubes of its digits and it is an Armstrong number.

You might also like