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

phython codes

Uploaded by

Sandeep Koppula
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

phython codes

Uploaded by

Sandeep Koppula
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

# Function to find the largest of three numbers

def find_largest(num1, num2, num3):

if num1 >= num2 and num1 >= num3:

return num1

elif num2 >= num1 and num2 >= num3:

return num2

else:

return num3

# Input from the user

num1 = float(input("Enter the first number: "))

num2 = float(input("Enter the second number: "))

num3 = float(input("Enter the third number: "))

# Finding the largest number

largest = find_largest(num1, num2, num3)

# Output the result

print("The largest number is:", largest)

Enter the first number: 10

Enter the second number: 25

Enter the third number: 15

The largest number is: 25.0


Python program to display all prime numbers within a specified interval, along with an
example:

python
Copy code
# Function to check if a number is prime
def is_prime(num):
if num <= 1:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True

# Input interval from the user


start = int(input("Enter the starting number of the interval: "))
end = int(input("Enter the ending number of the interval: "))

# Display prime numbers in the interval


print(f"Prime numbers between {start} and {end} are:")
for number in range(start, end + 1):
if is_prime(number):
print(number)

Example Usage:

Input:

mathematica
Copy code
Enter the starting number of the interval: 10
Enter the ending number of the interval: 30

Output:

sql
Copy code
Prime numbers between 10 and 30 are:
11
13
17
19
23
29
Here’s a Python program to swap two numbers without using a temporary variable, along
with an example:

python
Copy code
# Function to swap two numbers
def swap_numbers(a, b):
print(f"Before swapping: a = {a}, b = {b}")
a = a + b # Step 1: Sum both numbers
b = a - b # Step 2: Subtract the new b from the sum to get the
original a
a = a - b # Step 3: Subtract the new b from the sum to get the
original b
print(f"After swapping: a = {a}, b = {b}")

# Input from the user


num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))

# Swap the numbers


swap_numbers(num1, num2)

Example Usage:

Input:

mathematica
Copy code
Enter the first number: 5
Enter the second number: 10

Output:

less
Copy code
Before swapping: a = 5.0, b = 10.0
After swapping: a = 10.0, b = 5.0

Explanation:

 The program takes two numbers (5 and 10) from the user.
 It then swaps them using arithmetic operations without a temporary variable and
prints the results before and after the swap.
Certainly! Here’s a demonstration of various operators in Python with suitable examples:

i) Arithmetic Operators

Operator Description Example


+ Addition 5 + 3→8
- Subtraction 5 - 3→2
* Multiplication 5 * 3 → 15
/ Division 5 / 3 → 1.67
// Floor Division 5 // 3 → 1
% Modulus 5 % 3→2
** Exponentiation 5 ** 3 → 125
python
Copy code
a = 5
b = 3
print(a + b) # Output: 8
print(a - b) # Output: 2
print(a * b) # Output: 15
print(a / b) # Output: 1.666...
print(a // b) # Output: 1
print(a % b) # Output: 2
print(a ** b) # Output: 125

ii) Relational Operators

Operator Description Example


== Equal to 5 == 3 → False
!= Not equal 5 != 3 → True
> Greater than 5 > 3 → True
< Less than 5 < 3 → False
>= Greater than or equal 5 >= 3 → True
<= Less than or equal 5 <= 3 → False
python
Copy code
print(a == b) # Output: False
print(a != b) # Output: True
print(a > b) # Output: True
print(a < b) # Output: False
print(a >= b) # Output: True
print(a <= b) # Output: False

iii) Assignment Operators

Operator Description Example


= Assign a = 5
+= Add and assign a += 3 → 8
-= Subtract and assign a -= 2 → 6
Operator Description Example
*= Multiply and assign a *= 2 → 12
/= Divide and assign a /= 4 → 3
python
Copy code
a = 5
a += 3
print(a) # Output: 8
a -= 2
print(a) # Output: 6
a *= 2
print(a) # Output: 12
a /= 4
print(a) # Output: 3.0

iv) Logical Operators

Operator Description Example


and Logical AND True and False → False
or Logical OR True or False → True
not Logical NOT not True → False
python
Copy code
a = True
b = False
print(a and b) # Output: False
print(a or b) # Output: True
print(not a) # Output: False

v) Bitwise Operators

Operator Description Example


& Bitwise AND 5 & 3 → 1
` ` Bitwise OR
^ Bitwise XOR 5 ^ 3 → 6
~ Bitwise NOT ~5 → -6
<< Left Shift 5 << 1 → 10
>> Right Shift 5 >> 1 → 2
python
Copy code
a = 5 # 101 in binary
b = 3 # 011 in binary
print(a & b) # Output: 1
print(a | b) # Output: 7
print(a ^ b) # Output: 6
print(~a) # Output: -6
print(a << 1) # Output: 10
print(a >> 1) # Output: 2

vi) Ternary Operator


The ternary operator is a shorthand for if-else statements.

python
Copy code
a = 5
b = 3
max_value = a if a > b else b
print(max_value) # Output: 5

vii) Membership Operators

Operator Description Example


in Checks if a value is in a sequence 3 in [1, 2, 3] → True
not in Checks if a value is not in a sequence 3 not in [1, 2, 3] → False
python
Copy code
my_list = [1, 2, 3, 4, 5]
print(3 in my_list) # Output: True
print(6 not in my_list) # Output: True

viii) Identity Operators

Operator Description Example


is Checks if two variables refer to the same object a is b
is not Checks if two variables do not refer to the same object a is not b
python
Copy code
a = [1, 2, 3]
b = a
c = [1, 2, 3]

print(a is b) # Output: True


print(a is c) # Output: False
print(a is not c) # Output: True

i) Arithmetic Operators

Description: Used for basic mathematical operations.

Example: Calculating Prices

python
Copy code
# Prices of items
apple_price = 2.50
banana_price = 1.20
total_price = apple_price + banana_price # Total cost
print("Total Price:", total_price) # Output: 3.70

ii) Relational Operators


Description: Used to compare values.

Example: Checking Eligibility

python
Copy code
age = 18
is_eligible = age >= 18 # Check if eligible to vote
print("Is eligible to vote:", is_eligible) # Output: True

iii) Assignment Operators

Description: Used to assign values to variables.

Example: Bank Account Balance

python
Copy code
balance = 1000
balance += 500 # Deposit
print("Balance after deposit:", balance) # Output: 1500
balance -= 200 # Withdrawal
print("Balance after withdrawal:", balance) # Output: 1300

iv) Logical Operators

Description: Used to combine conditional statements.

Example: User Authentication

python
Copy code
username = "user"
password = "pass"
is_authenticated = (username == "user") and (password == "pass")
print("Is authenticated:", is_authenticated) # Output: True

v) Bitwise Operators

Description: Used to perform bit-level operations.

Example: Network Addresses

python
Copy code
a = 5 # 0101 in binary
b = 3 # 0011 in binary
print("Bitwise AND:", a & b) # Output: 1 (0001 in binary)
vi) Ternary Operator

Description: A shorthand for if-else statements.

Example: Grading System

python
Copy code
marks = 85
grade = "Pass" if marks >= 50 else "Fail"
print("Grade:", grade) # Output: Pass

vii) Membership Operators

Description: Check for membership in a sequence (like lists or strings).

Example: Checking Inventory

python
Copy code
inventory = ["apple", "banana", "orange"]
is_in_stock = "banana" in inventory
print("Is banana in stock?", is_in_stock) # Output: True

viii) Identity Operators

Description: Check if two variables refer to the same object.

Example: Object Comparison

python
Copy code
a = [1, 2, 3]
b = a # b points to the same list as a
c = [1, 2, 3] # c is a different object

print(a is b) # Output: True (same object)


print(a is c) # Output: False (different objects)

Python program to add and multiply complex numbers:

python
Copy code
# Function to add two complex numbers
def add_complex(num1, num2):
return num1 + num2

# Function to multiply two complex numbers


def multiply_complex(num1, num2):
return num1 * num2

# Input complex numbers from the user


num1 = complex(input("Enter the first complex number (e.g., 2+3j): "))
num2 = complex(input("Enter the second complex number (e.g., 1+4j): "))

# Perform addition and multiplication


sum_result = add_complex(num1, num2)
product_result = multiply_complex(num1, num2)

# Output the results


print(f"The sum of {num1} and {num2} is: {sum_result}")
print(f"The product of {num1} and {num2} is: {product_result}")

Example Usage:

Input:

c
Copy code
Enter the first complex number (e.g., 2+3j): 2+3j
Enter the second complex number (e.g., 1+4j): 1+4j

Output:

python
Copy code
The sum of (2+3j) and (1+4j) is: (3+7j)
The product of (2+3j) and (1+4j) is: (-10+11j)

Explanation:

 The program takes two complex numbers as input.


 It calculates their sum and product and prints the results.

Here’s a Python program to print the multiplication table of a given number:

python
Copy code
# Function to print multiplication table
def print_multiplication_table(num):
print(f"Multiplication Table for {num}:")
for i in range(1, 11):
print(f"{num} x {i} = {num * i}")

# Input from the user


number = int(input("Enter a number to print its multiplication table: "))

# Print the multiplication table


print_multiplication_table(number)

Example Usage:

Input:

css
Copy code
Enter a number to print its multiplication table: 5

Output:

css
Copy code
Multiplication Table for 5:
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50

Explanation:

 The program takes a number from the user and prints its multiplication table from 1 to
10.

Here’s a Python program that defines a function with multiple return values, using a real-
world example of calculating the area and perimeter of a rectangle.

python
Copy code
# Function to calculate area and perimeter of a rectangle
def rectangle_properties(length, width):
area = length * width
perimeter = 2 * (length + width)
return area, perimeter # Returning both area and perimeter

# Input from the user


length = float(input("Enter the length of the rectangle: "))
width = float(input("Enter the width of the rectangle: "))

# Calling the function and unpacking the returned values


area, perimeter = rectangle_properties(length, width)

# Output the results


print(f"Area of the rectangle: {area}")
print(f"Perimeter of the rectangle: {perimeter}")

Example Usage:

Input:

mathematica
Copy code
Enter the length of the rectangle: 5
Enter the width of the rectangle: 3

Output:

mathematica
Copy code
Area of the rectangle: 15.0
Perimeter of the rectangle: 16.0

Explanation:

 The function rectangle_properties takes the length and width of a rectangle and
returns both the area and perimeter.
 The program captures the user input and calls the function, unpacking the returned
values into area and perimeter, which are then printed.

# Function to calculate volume of a box with a default height

def calculate_volume(length, width, height=5):

volume = length * width * height


return volume

# Input from the user

length = float(input("Enter the length of the box: "))

width = float(input("Enter the width of the box: "))

# Calling the function without specifying height (uses default)

volume_default = calculate_volume(length, width)

# Calling the function with a specified height

height = float(input("Enter the height of the box (or press Enter to use
default): ") or 5)

volume_with_custom_height = calculate_volume(length, width, height)

# Output the results

print(f"Volume with default height: {volume_default}")

print(f"Volume with specified height: {volume_with_custom_height}")

Enter the length of the box: 4

Enter the width of the box: 3

Enter the height of the box (or press Enter to use default): 2

Volume with default height: 60.0

Volume with specified height: 24.0

Here’s a Python program to find the length of a string without using any library functions:

python
Copy code
# Function to calculate the length of a string
def string_length(input_string):
count = 0
for char in input_string:
count += 1 # Increment count for each character
return count

# Input from the user


user_input = input("Enter a string: ")

# Calculate the length


length = string_length(user_input)

# Output the result


print(f"The length of the string is: {length}")

Example Usage:

Input:

c
Copy code
Enter a string: Hello, World!

Output:

csharp
Copy code
The length of the string is: 13

Explanation:

 The string_length function iterates through each character in the input string and
increments a counter for each character.
 Finally, it returns the count, which represents the length of the string.

Here’s a Python program to check if a substring is present in a given string:

python
Copy code
# Function to check if a substring is present in the given string
def is_substring_present(main_string, substring):
# Iterate through the main string
for i in range(len(main_string) - len(substring) + 1):
# Check if the substring matches
if main_string[i:i + len(substring)] == substring:
return True
return False

# Input from the user


main_string = input("Enter the main string: ")
substring = input("Enter the substring to check: ")

# Check for substring


if is_substring_present(main_string, substring):
print(f"The substring '{substring}' is present in the main string.")
else:
print(f"The substring '{substring}' is not present in the main
string.")

Example Usage:

Input:

mathematica
Copy code
Enter the main string: Hello, World!
Enter the substring to check: World

Output:

csharp
Copy code
The substring 'World' is present in the main string.

Explanation:

 The program defines a function is_substring_present that checks if the specified


substring exists within the main string by comparing slices of the main string.
 It iterates through the main string and checks for a match with the substring, returning
True if found, or False otherwise.

Here’s a Python program that demonstrates addition, insertion, and slicing operations on a list
with examples:

python
Copy code
# Initialize an empty list
my_list = []

# Function to add elements to the list


def add_elements(elements):
my_list.extend(elements) # Add multiple elements

# Function to insert an element at a specific position


def insert_element(position, element):
my_list.insert(position, element)

# Function to slice the list


def slice_list(start, end):
return my_list[start:end]

# Example operations

# Adding elements
add_elements([1, 2, 3, 4, 5])
print("List after addition:", my_list) # Output: [1, 2, 3, 4, 5]

# Inserting an element
insert_element(2, 10) # Insert 10 at index 2
print("List after insertion:", my_list) # Output: [1, 2, 10, 3, 4, 5]

# Slicing the list


sliced = slice_list(1, 4) # Slice from index 1 to 3
print("Sliced list:", sliced) # Output: [2, 10, 3]

Example Usage:

1. Adding elements:
o Adding [1, 2, 3, 4, 5] to the list results in:

less
Copy code
List after addition: [1, 2, 3, 4, 5]

2. Inserting an element:
o Inserting 10 at index 2 results in:

less
Copy code
List after insertion: [1, 2, 10, 3, 4, 5]

3. Slicing the list:


o Slicing from index 1 to 4 results in:

less
Copy code
Sliced list: [2, 10, 3]

Full Example Output:


less
Copy code
List after addition: [1, 2, 3, 4, 5]
List after insertion: [1, 2, 10, 3, 4, 5]
Sliced list: [2, 10, 3]

Here’s a Python program that demonstrates five built-in list functions using a sample list:

python
Copy code
# Sample list
my_list = [10, 20, 30, 40, 50]

# 1. append(): Adds an element to the end of the list


my_list.append(60)
print("After append:", my_list) # Output: [10, 20, 30, 40, 50, 60]

# 2. insert(): Inserts an element at a specified position


my_list.insert(2, 25)
print("After insertion:", my_list) # Output: [10, 20, 25, 30, 40, 50, 60]

# 3. remove(): Removes the first occurrence of a specified value


my_list.remove(30)
print("After removal:", my_list) # Output: [10, 20, 25, 40, 50, 60]

# 4. sort(): Sorts the list in ascending order


my_list.sort()
print("After sorting:", my_list) # Output: [10, 20, 25, 40, 50, 60]

# 5. reverse(): Reverses the order of the list


my_list.reverse()
print("After reversing:", my_list) # Output: [60, 50, 40, 25, 20, 10]

Example Output:
less
Copy code
After append: [10, 20, 30, 40, 50, 60]
After insertion: [10, 20, 25, 30, 40, 50, 60]
After removal: [10, 20, 25, 40, 50, 60]
After sorting: [10, 20, 25, 40, 50, 60]
After reversing: [60, 50, 40, 25, 20, 10]

Explanation of Functions Used:

1. append(): Adds an element to the end of the list.


2. insert(index, element): Inserts an element at a specified index.
3. remove(element): Removes the first occurrence of the specified element from the
list.
4. sort(): Sorts the list in ascending order.
5. reverse(): Reverses the elements of the list in place.

You might also like