0% found this document useful (0 votes)
8 views5 pages

Python Programs for Basic Calculations

Uploaded by

yadavramendra567
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)
8 views5 pages

Python Programs for Basic Calculations

Uploaded by

yadavramendra567
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

Program 1: Sum of Two Numbers

Question: Write a Python program to calculate the sum of two numbers.

# Program to calculate the sum of two numbers

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

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

sum_result = num1 + num2

print(f"The sum of {num1} and {num2} is {sum_result}.")

Example Output:

Enter the first number: 12

Enter the second number: 8

The sum of 12.0 and 8.0 is 20.0

Program 2: Find the Average of Three Numbers

Question : Write a Python program to calculate the average of three


numbers.

Ans

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

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

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

average = (num1 + num2 + num3) / 3

print(f"The average of {num1}, {num2}, and {num3} is {average}.")

Example Output:

Enter the first number: 10

Enter the second number: 20

Enter the third number: 30

The average of 10.0, 20.0, and 30.0 is 20.0.


Program 3: Check Even or Odd

Question: Write a Python program to check if a number is even or odd.

# Program to check if a number is even or odd

num = int(input("Enter a number: "))

if num % 2 == 0:

print(f"{num} is an even number.")

else:

print(f"{num} is an odd number.")

Example Output:

Enter a number: 15

15 is an odd number.

Program 4: Find the Largest of Three Numbers

Question: Write a Python program to find the largest of three numbers.

# Program to find the largest of three numbers

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

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

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

largest = max(num1, num2, num3)

print(f"The largest number among {num1}, {num2}, and {num3} is


{largest}.")

Example Output:

Enter the first number: 25

Enter the second number: 12

Enter the third number: 45

The largest number among 25.0, 12.0, and 45.0 is 45.0.

Program 5: Print Multiplication Table

Question: Write a Python program to display the multiplication table of a


given number.

# Program to display the multiplication table


num = int(input("Enter a number: "))

print(f"Multiplication table for {num}:")

for i in range(1, 11):

print(f"{num} × {i} = {num * i}")

Example Output:

Enter a number: 5

Multiplication table for 5:

5×1=5

5 × 2 = 10

...

5 × 10 = 50

Program 6: Find Factorial

Question: Write a Python program to calculate the factorial of a number.

num = int(input("Enter a number: "))

factorial = 1

for i in range(1, num + 1):

factorial *= i

print(f"The factorial of {num} is {factorial}.")

Example Output:

Enter a number: 5

The factorial of 5 is 120.

Program 7: Check if a Number is Positive, Negative, or Zero

Question: Write a Python program to check whether a number is positive,


negative, or zero.

num = float(input("Enter a number: "))

if num > 0:

print(f"{num} is positive.")

elif num < 0:

print(f"{num} is negative.")
else:

print("The number is zero.")

Example Output:

Enter a number: -7

-7.0 is negative.

Program 8: Reverse a String

Question: Write a Python program to reverse a string entered by the user.

# Program to reverse a string

text = input("Enter a string: ")

reversed_text = text[::-1]

print(f"The reversed string is: {reversed_text}")

Example Output:

Enter a string: python

The reversed string is: nohtyp

Program 9: Convert Celsius to Fahrenheit

Question: Write a Python program to convert temperature from Celsius to


Fahrenheit.

# Program to convert Celsius to Fahrenheit

celsius = float(input("Enter temperature in Celsius: "))

fahrenheit = (celsius * 9/5) + 32

print(f"{celsius}°C is equal to {fahrenheit}°F.")

Example Output:

Enter temperature in Celsius: 25

25.0°C is equal to 77.0°F.

Program 10: Check Leap Year

Question: Write a Python program to check if a given year is a leap year.

# Program to check leap year

year = int(input("Enter a year: "))

if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):


print(f"{year} is a leap year.")

else:

print(f"{year} is not a leap year.")

Example Output:

Enter a year: 2024

2024 is a leap year.

Common questions

Powered by AI

Checking whether a number is positive, negative, or zero is a fundamental operation that can be integrated into larger applications in data analysis, algorithms requiring numeric categorization, error handling, and input validation. For example, financial applications can use such checks to determine profit or loss scenarios, while scientific computations might need such logic to categorize growth rates or changes .

Using functions enhances clarity and reusability by encapsulating logic, reducing redundancy, and improving maintainability. For instance, a function to calculate the average of numbers can be defined as `def calculate_average(nums): return sum(nums) / len(nums)`, allowing any list of numbers to be averaged. Similarly, reversing strings can be defined as `def reverse_string(s): return s[::-1]`. These functions can then be reused without repeating code, and changes to logic need only be made in one place .

To determine if a number is even or odd in Python, the program follows these steps: (1) Accept input from the user and convert it to an integer. (2) Use the modulo operator (%) to divide the number by 2. (3) If the remainder is 0, the number is even, otherwise, it is odd. The modulo operator is essential because it returns the remainder of a division operation, which is the basis for determining the evenness or oddness of a number .

For-loops offer clear advantages for generating multiplication tables due to their clarity, ease of setting up a fixed range of iterations, and direct control of iteration variables. A for-loop clearly defines the start, end, and increment of iterations. Compared to while-loops, for-loops reduce complexity by eliminating the need for manually managing iteration variables, lowering chances of errors like infinite loops. List comprehensions could achieve similar tasks but lack the inherent readability when the loop involves more than simple operations .

The factorial of a number can be computed using a recursive function that multiplies the number by the factorial of the number minus one, with a base case of the factorial of zero being one. This approach might be preferable in cases where recursive solutions are more natural to express or understand conceptually. However, it's important to note that due to stack limitations, recursion is not suitable for very large numbers without optimizations like tail-call optimization, which Python does not support natively .

To convert a temperature from Celsius to Fahrenheit, the program first prompts the user to input a temperature in Celsius. It then applies the formula \(F = C \times \frac{9}{5} + 32\), where \(C\) is the Celsius temperature. This conversion is significant in providing temperatures in a format that is commonly used in several countries, enhancing understanding and communication of temperature-related information .

To extend the program to handle four or more numbers, you would collect additional numbers as input. Then, instead of using the max() function with a fixed count of arguments, you could pass a list of all entered numbers to max(). This allows max() to evaluate any number of inputs. For example, if you handle four numbers, you could use max(num1, num2, num3, num4) or, more generally, max([num1, num2, num3, num4, ...]) to find the largest value .

A Python program to calculate compound interest would involve user inputs for principal, rate, number of times interest applied per time period, and the number of periods. Using the formula \(A = P \times (1 + \frac{r}{n})^{nt}\), where \(A\) is the amount after time \(t\), \(P\) is the principal, \(r\) is the annual interest rate, \(n\) is the number of times interest applied, and \(t\) is the time in years, the program calculates the future value. Implementing this in a function allows easy computation and integration of financial calculations within larger systems or for repeated evaluations with varying inputs .

The logic to determine whether a year is a leap year involves two main conditions: (1) The year must be divisible by 4, not divisible by 100, unless (2) it is also divisible by 400. This logic addresses all possible cases: Years divisible by 400 are leap years, addressing the century years exception, whereas other century years that are not divisible by 400 are not leap years. This ensures proper leap year determination per the Gregorian calendar rules .

Reversing a string is useful in scenarios such as palindrome checking, encoding algorithms, or simply formatted output where backward representation is needed. In Python, a concise method to reverse a string is by utilizing slicing. A string can be reversed by using the slicing syntax `string[::-1]`, which effectively steps through the string backward one element at a time. This approach is both efficient and easy to implement .

You might also like