# Basic Programs in Python
# This program prints Hello, world!
print('Hello, world!')
=========
In the program below, we've used the + operator to add two numbers.
Example 1: Add Two Numbers
# This program adds two numbers
num1 = 15
num2 = 63
# Add two numbers
sum = num1 + num2
# Display the sum
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))
=============
#Example 2: Add Two Numbers With User Input
# Store input numbers
n1 = input('Enter first number: ')
n2 = input('Enter second number: ')
# Add two numbers
sum = float(n1) + float(n2)
# Display the sum
print('The sum of {0} and {1} is {2}'.format(n1, n2, sum))
============
Example: For positive numbers
# Python Program to calculate the square root
# Note: change this value for a different result
num = 8
# To take the input from the user
#num = float(input('Enter a number: '))
num_sqrt = num ** 0.5
print('The square root of %0.3f is %0.3f'%(num ,num_sqrt))
==========
# Python Program to find the area of triangle
# below to take inputs from the user
a = float(input('Enter first side: '))
b = float(input('Enter second side: '))
c = float(input('Enter third side: '))
# calculate the semi-perimeter
s = (a + b + c) / 2
# calculate the area
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is %0.2f' %area)
===============
The standard form of a quadratic equation is:
ax2 + bx + c = 0, where
a, b and c are real numbers and
a ≠ 0
#The solutions of this quadratic equation is given by:
(-b ± (b ** 2 - 4 * a * c) ** 0.5) / (2 * a)
#Source Code
# Solve the quadratic equation ax**2 + bx + c = 0
# import complex math module
import cmath
a = 1
b = 5
c = 6
# calculate the discriminant
d = (b**2) - (4*a*c)
# find two solutions
qsol1 = (-b-cmath.sqrt(d))/(2*a)
qsol2 = (-b+cmath.sqrt(d))/(2*a)
print('The solution are {0} and {1}'.format(qsol1,qsol2))
Output
Enter a: 1
Enter b: 5
Enter c: 6
The solutions are (-3+0j) and (-2+0j)
=============
# swap 2 variables
x = 5
y = 10
x, y = y, x
print("x =", x)
print("y =", y)
===========
#To generate random number in Python, randint() function is used. This function is
defined in random module.
Source Code
# Program to generate a random number between 0 and 9
# importing the random module
import random
print(random.randint(0,9))
=============
#Example: Kilometers to Miles
# Taking kilometers input from the user
kilometers = float(input("Enter value in kilometers: "))
# conversion factor
conv_fac = 0.621371
# calculate miles
miles = kilometers * conv_fac
print('%0.2f kilometers is equal to %0.2f miles' %(kilometers,miles))
Output
Enter value in kilometers: 3.5
3.50 kilometers is equal to 2.17 miles