Python Program To Print Hello World!
Python Program To Print Hello World!
Python Program To Print Hello World!
print('Hello, world!')
Output
Hello, world!
num1 = 1.5
num2 = 6.3
Output
The program below calculates the sum of two numbers entered by the user..
1
num2 = input('Enter second number: ')
Output
Output
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!
2
s = (a+b+c)/2
area = √(s(s-a)*(s-b)*(s-c))
Source Code
a = 5
b = 6
c = 7
Output
In this program, area of the triangle is calculated when three sides are given using Heron's formula.
If you need to calculate area of a triangle depending upon the input from the user, input() function can be
used.
3
Python Program to Solve Quadratic Equation
ax2 + bx + c = 0, where
a, b and c are real numbers and
a ≠ 0
(-b ± (b ** 2 - 4 * a * c) ** 0.5) / 2 * a
Source Code
a = 1
b = 5
c = 6
Output
Enter a: 1
4
Enter b: 5
Enter c: 6
The solutions are (-3+0j) and (-2+0j)
We have imported the cmath module to perform complex square root. First, we calculate the discriminant
You can change the value of a, b and c in the above program and test this program.
x = 5
y = 10
Output
In this program, we use the temp variable to hold the value of x temporarily. We then put the value
5
Source Code: Without Using Temporary Variable
In Python, there is a simple construct to swap variables. The following code does the same as above but
x = 5
y = 10
x, y = y, x
print("x =", x)
print("y =", y)
If the variables are both numbers, we can use arithmetic operations to do the same. It might not look
intuitive at first sight. But if you think about it, it is pretty easy to figure it out. Here are a few examples
x = x + y
y = x - y
x = x - y
x = x * y
y = x / y
x = x / y
XOR swap
x = x ^ y
y = x ^ y
x = x ^ y
6
Python Program to Generate a Random Number!
To understand this example, you should have the knowledge of the following Python programming topics:
module.
Source Code
print(random.randint(0,9))
Output
Note that we may get different output because this program generates random number in range 0 and
random.randint(a,b)
This returns a number N in the inclusive range [a,b], meaning a <= N <= b, where the endpoints are
7
Python Program to Convert Kilometers to Miles!
# 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
Here, the user is asked to enter kilometers. This value is stored in the kilometers variable.
Since 1 kilometer is equal to 0.621371 miles, we can get the equivalent miles by multiplying kilometers
Your turn: Modify the above program to convert miles to kilometers using the following formula and run it.
8
Python Program to Convert Celsius To Fahrenheit
In the program below, we take a temperature in degree Celsius and convert it into degree Fahrenheit.
Source Code
# calculate fahrenheit
fahrenheit = (celsius * 1.8) + 32
print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit' %
(celsius,fahrenheit))
Output
We encourage you to create a Python program to convert Fahrenheit to Celsius on your own using the
following formula
In this example, you will learn to check whether a number entered by the user is positive, negative or
zero. This problem is solved using if...elif...else and nested if...else statement.
9
Source Code: Using if...elif...else
Here, we have used the if...elif...else statement. We can do the same thing using nested if statements as
follows.
Output 1
Enter a number: 2
Positive number
Output 2
Enter a number: 0
Zero
A number is positive if it is greater than zero. We check this in the expression of if. If it is False, the
number will either be zero or negative. This is also tested in subsequent expression.
10
Python Program to Check if a Number is Odd or Even
In this example, you will learn to check whether a number entered by the user is even or odd.
A number is even if it is perfectly divisible by 2. When the number is divided by 2, we use the remainder
operator % to compute the remainder. If the remainder is not zero, the number is odd.
Source Code
Output 1
Enter a number: 43
43 is Odd
Output 2
Enter a number: 18
18 is Even
In this program, we ask the user for the input and check if the number is odd or even.
In the program below, the three numbers are stored in num1, num2 and num3 respectively. We've used
the if...elif...else ladder to find the largest among the three and display it.
11
Source Code
# Python program to find the largest number among the three input numbers
Output
Example to check whether an integer is a prime number or not using for loop and if...else statement. If the
number is not prime, it's explained in output why it is not a prime number.
A positive integer greater than 1 which has no other factors except 1 and the number itself is called a
prime number. 2, 3, 5, 7 etc. are prime numbers as they do not have any other factors. But 6 is not prime
12
Example 1: Using a flag variable
num = 29
In this program, we have checked if num is prime or not. Numbers less than or equal to 1 are not prime
We check if num is exactly divisible by any number from 2 to num - 1. If we find a factor in that range, the
Note: We can improve our program by decreasing the range of numbers where we look for factors.
13
We could have used the range, range(2,num//2) or range(2,math.floor(math.sqrt(num))) . The latter range
is based on the fact that a composite number must have a factor less than the square root of that number.
You can change the value of variable num in the above source code to check whether a number is prime
additional flag variable.
num = 407
Output
14
Here, we have used a for..else statement to check if num is prime.
It works on the logic that the else clause of the for loop runs if and only if we don't break out the for loop.
That condition is met only when no factors are found, which means that the given number is prime.
In this program, you'll learn to find the numbers divisible by another number and display it.
In the program below, we have used anonymous (lambda) function inside the filter() built-in function to
Source Code
Output
15
Python Program to Find the Factors of a Number!
In this program, you'll learn to find the factors of a number using the for loop.
Source Code
num = 320
print_factors(num)
Output
Note: To find the factors of another number, change the value of num.
16
In this program, the number whose factor is to be found is stored in num, which is passed to
In the function, we use the for loop to iterate from i equal to x. If x is perfectly divisible by i, it's a factor
of x.
In this example you will learn to create a simple calculator that can add, subtract, multiply or divide
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
while True:
# Take input from the user
17
choice = input("Enter choice(1/2/3/4): ")
if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))
Output
Select operation.
1.Add
2.Subtract
3.Multiply
4.Divide
Enter choice(1/2/3/4): 3
Enter first number: 15
Enter second number: 14
15.0 * 14.0 = 210.0
In this program, we ask the user to choose an operation. Options 1, 2, 3, and 4 are valid. If any other
input is given, Invalid Input is displayed and the loop continues until a valid option is selected.
Two numbers are taken and an if...elif...else branching is used to execute a particular section. User-
output.
18
Python Program to Create Pyramid Patterns!
In this example, you will learn to print half pyramids, inverted pyramids, full pyramids, inverted full
* *
* * *
* * * *
* * * * *
Source Code
for i in range(rows):
for j in range(i+1):
print("* ", end="")
print("\n")
1 2
1 2 3
1 2 3 4
19
1 2 3 4 5
Source Code
for i in range(rows):
for j in range(i+1):
print(j+1, end=" ")
print("\n")
B B
C C C
D D D D
E E E E E
Source Code
ascii_value = 65
for i in range(rows):
for j in range(i+1):
alphabet = chr(ascii_value)
print(alphabet, end=" ")
ascii_value += 1
print("\n")
20
Programs to print inverted half pyramid using * and numbers
* * * * *
* * * *
* * *
* *
Source Code
print("\n")
1 2 3 4 5
1 2 3 4
1 2 3
1 2
21
Source Code
print("\n")
* * *
* * * * *
* * * * * * *
* * * * * * * * *
Source Code
k = 0
while k!=(2*i-1):
print("* ", end="")
k += 1
k = 0
22
print()
2 3 2
3 4 5 4 3
4 5 6 7 6 5 4
5 6 7 8 9 8 7 6 5
Source Code
k = 0
count=0
count1=0
while k!=((2*i)-1):
if count<=rows-1:
print(i+k, end=" ")
count+=1
else:
count1+=1
print(i+k-(2*count1), end=" ")
k += 1
count1 = count = k = 0
print()
23
Example 8: Inverted full pyramid of *
* * * * * * * * *
* * * * * * *
* * * * *
* * *
Source Code
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
24
Source Code
2 3
4 5 6
7 8 9 10
Source Code
Write a python program to find the largest number among the two input numbers.
a = float(input(" Please Enter the First Value a:"))
25
b = float(input(" Please Enter the Second Value b:"))
else:
Write a Python program to calculate a circle’s area and circumference from the given radius (in cm).
Output
Input the radius of the circle: 1.1
The area of the circle with radius 1.1 is: 3.8013271108436504
Output
seconds value in hours: 2
seconds value in minutes: 46
Time in preferred format :- 02:46:40
26
Write a Python program to calculate a bike’s average consumption from the given total distance traveled
(in km) and spent fuel (in liters).
int main()
int x;
float y;
scanf("%d",&x);
scanf("%f", &y);
printf("\n");
return 0;
Copy
Sample Output:
h = float(hrs)
x = float(xx)
if h<=40:
print(h*x)
print(40*x+(h-40)*1.5*x)
Output
enter hours:4
27
enter the rate:5
20.0
28