Codes Output
Codes Output
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:
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:
Valid Input:
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
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
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:
Output:
Not specified
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:
Output:
name: John
age: 20
grades: [90, 85, 95]
country: USA
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("3. Exit")
if choice == '1':
if task:
todos.append(task)
else:
if todos:
print("\nYour tasks:")
print(f"{idx}. {task}")
else:
break
else:
Code Improvements:
Your tasks:
1. Buy groceries
When Exiting:
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 checks if the input string is a palindrome using the is_palindrome function and prints the appropriate message.
Output:
1. print(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:
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!
Output:
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
Explanation:
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:
Example Execution:
Input:
Output:
The number is equal to the sum of the cubes of its digits and it is an Armstrong number.