Python Exercise 1

Mannan Ul Haq
0

Objective:

  1. Introduction to Python
  2. How to compile Python code
  3. Simple arithmetic problems solving


Activity 1:

Take two inputs from user (keyboard) length and breadth of rectangle. Compute the area of rectangle given by: area = length*breadth


Solution:

length = float(input("Enter Length of Rectangle: "))
breadth = float(input("Enter Breadth of Rectangle: "))

area = length * breadth

print("The Area is =", area)


Activity 2:

Write Python code to solve the second-degree equation aX^2 + bX + c= 0 for any real numbers a, b and c. The program takes the values of a, b and c as input from the user, and calculates X.

Note: real numbers are taken in float.

Solution:

import cmath  # cmath handles complex numbers, useful in case the equation has complex solutions

a = float(input("Enter value for a: "))
b = float(input("Enter value for b: "))
c = float(input("Enter value for c: "))

# Using quadratic formula
discriminant = cmath.sqrt(b**2 - 4*a*c)

# Getting the two possible values for X
x1 = (-b - discriminant) / (2 * a)
x2 = (-b + discriminant) / (2 * a)

print("The First value of X is =", x1.real)
print("The Second value of X is =", x2.real)

# If there's an imaginary part, display it
if x1.imag:
      print("The First value of X also has an imaginary part =", x1.imag, "i")
if x2.imag:
      print("The Second value of X also has an imaginary part =", x2.imag, "i")


Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !