Python Program to Print Hello world!
A simple program that displays “Hello, World!”. It's often used to illustrate the syntax of the language.
# This program prints Hello, world!
print('Hello, world!')
Output
Hello, world!
In this program, we have used the built-in print() function to print the string Hello, world! on our screen.
Python Program to Add Two Numbers
In this program, you will learn to add two numbers and display it using print() function.
In the program below, we've used the + operator to add two numbers.
# This program adds two numbers
num1 = 1.5
num2 = 6.3
# Add two numbers
sum = num1 + num2
# Display the sum
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))
Output
The sum of 1.5 and 6.3 is 7.8
The program below calculates the sum of two numbers entered by the user..
Add Two Numbers With User Input
# Store input numbers
num1 = input('Enter first number: ')
num2 = input('Enter second number: ')
# Add two numbers
sum = float(num1) + float(num2)
# Display the sum
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))
Output
Enter first number: 1.5
Enter second number: 6.3
The sum of 1.5 and 6.3 is 7.8
In this program, we asked the user to enter two numbers and this program displays the sum of two numbers entered by user.
We use the built-in function input() to take the input. Since, input() returns a string, we convert the string into number using the float() function. Then, the numbers are added.
Python Program to Find the Square Root
In this program, you'll learn to find the square root of a number using exponent operator and cmath module
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))
Output
The square root of 8.000 is 2.828
In this program, we store the number in num and find the square root using the ** exponent operator. This program works for all positive real numbers. But for negative or complex numbers, it can be done as follows.
Python Program to Calculate the Area of a Triangle
In this program, you'll learn to calculate the area of a triangle and display it.
If a, b and c are three sides of a triangle. Then,
s = (a+b+c)/2
area = √(s(s-a)*(s-b)*(s-c))
Source Code
# Python Program to find the area of triangle
a = 5
b = 6
c = 7
# Uncomment 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)
Output
The area of the triangle is 14.70
In this program, area of the triangle is calculated when three sides are given using Heron's formula.