You are on page 1of 28

PYTHON BASICS

Python Program to Print Hello world!

print('Hello, world!')

Output

Hello, world!

Python program to add two numbers!

In the program below, we've used the + operator to add two numbers.

Example 1: 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..

Example 2: Add Two Numbers With User Input

# Store input numbers


num1 = input('Enter first number: ')

1
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

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!

If a, b and c are three sides of a triangle. Then,

2
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.

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

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


sol1 = (-b-cmath.sqrt(d))/(2*a)
sol2 = (-b+cmath.sqrt(d))/(2*a)

print('The solution are {0} and {1}'.format(sol1,sol2))

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

and then find the two solutions of the quadratic equation.

You can change the value of a, b and c in the above program and test this program.

Python Program to Swap Two Variables

Source Code: Using a temporary variable

# Python program to swap two variables

x = 5
y = 10

# To take inputs from the user


#x = input('Enter value of x: ')
#y = input('Enter value of y: ')

# create a temporary variable and swap the values


temp = x
x = y
y = temp

print('The value of x after swapping: {}'.format(x))


print('The value of y after swapping: {}'.format(y))

Output

The value of x after swapping: 10


The value of y after swapping: 5

In this program, we use the temp variable to hold the value of x temporarily. We then put the value

of y in x and later temp in y. In this way, the values get exchanged.

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

without the use of any temporary variable.

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

Addition and Subtraction

x = x + y
y = x - y
x = x - y

Multiplication and Division

x = x * y
y = x / y
x = x / y

XOR swap

This algorithm works for integers only

x = x ^ y
y = x ^ y
x = x ^ y

6
Python Program to Generate a Random Number!

In this example, you will learn to generate a random number in Python.

To understand this example, you should have the knowledge of the following Python programming topics:

 Python Input, Output and Import

 Python Random Module

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))

Output

Note that we may get different output because this program generates random number in range 0 and

9. The syntax of this function is:

random.randint(a,b)

This returns a number N in the inclusive range [a,b], meaning a <= N <= b, where the endpoints are

included in the range.

7
Python Program to Convert Kilometers to Miles!

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

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

with this factor.

Your turn: Modify the above program to convert miles to kilometers using the following formula and run it.

kilometers = miles / conv_fac

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.

They are related by the formula:

celsius * 1.8 = fahrenheit - 32

Source Code

# Python Program to convert temperature in celsius to fahrenheit

# change this value for a different result


celsius = 37.5

# calculate fahrenheit
fahrenheit = (celsius * 1.8) + 32
print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit' %
(celsius,fahrenheit))

Output

37.5 degree Celsius is equal to 99.5 degree Fahrenheit

We encourage you to create a Python program to convert Fahrenheit to Celsius on your own using the

following formula

celsius = (fahrenheit - 32) / 1.8

Python Program to Check if a Number is Positive, Negative or 0

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

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


if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")

Here, we have used the if...elif...else statement. We can do the same thing using nested if statements as

follows.

Source Code: Using Nested if

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


if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")

The output of both programs will be the same.

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

# Python program to check if the input number is odd or even.


# A number is even if division by 2 gives a remainder of 0.
# If the remainder is 1, it is an odd number.

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


if (num % 2) == 0:
print("{0} is Even".format(num))
else:
print("{0} is Odd".format(num))

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.

Python Program to Find the Largest Among Three Numbers!

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

# change the values of num1, num2 and num3


# for a different result
num1 = 10
num2 = 14
num3 = 12

# uncomment following lines to take three numbers from user


#num1 = float(input("Enter first number: "))
#num2 = float(input("Enter second number: "))
#num3 = float(input("Enter third number: "))

if (num1 >= num2) and (num1 >= num3):


largest = num1
elif (num2 >= num1) and (num2 >= num3):
largest = num2
else:
largest = num3

print("The largest number is", largest)

Output

The largest number is 14.0

Python Program to Check Prime Number!

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

(it is composite) since, 2 x 3 = 6.

12
Example 1: Using a flag variable

# Program to check if a number is prime or not

num = 29

# To take input from the user


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

# define a flag variable


flag = False

# prime numbers are greater than 1


if num > 1:
# check for factors
for i in range(2, num):
if (num % i) == 0:
# if factor is found, set flag to True
flag = True
# break out of loop
break

# check if flag is True


if flag:
print(num, "is not a prime number")
else:
print(num, "is a prime number")

In this program, we have checked if num is prime or not. Numbers less than or equal to 1 are not prime

numbers. Hence, we only proceed if the num is greater than 1.

We check if num is exactly divisible by any number from 2 to num - 1. If we find a factor in that range, the

number is not prime, so we set flag to True and break out of the loop.

Outside the loop, we check if flag is True or False.

 If it is True, num is not a prime number.

 If it is False, num is a prime number.

Note: We can improve our program by decreasing the range of numbers where we look for factors.

In the above program, our search range is from 2 to num - 1.

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.

Otherwise, the number is prime.

You can change the value of variable num in the above source code to check whether a number is prime

or not for other integers.

In Python, we can also use the for...else statement to do this task without using an

additional flag variable.

Example 2: Using a for...else statement

# Program to check if a number is prime or not

num = 407

# To take input from the user


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

# prime numbers are greater than 1


if num > 1:
# check for factors
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
print(i,"times",num//i,"is",num)
break
else:
print(num,"is a prime number")

# if input number is less than


# or equal to 1, it is not prime
else:
print(num,"is not a prime number")

Output

407 is not a prime number


11 times 37 is 407

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.

So, in the else clause, we print that the number is prime.

Python Program to Find Numbers Divisible by Another Number

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

find all the numbers divisible by 13 in the list.

Source Code

# Take a list of numbers


my_list = [12, 65, 54, 39, 102, 339, 221,]

# use anonymous function to filter


result = list(filter(lambda x: (x % 13 == 0), my_list))

# display the result


print("Numbers divisible by 13 are",result)

Output

Numbers divisible by 13 are [65, 39, 221]

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

# Python Program to find the factors of a number

# This function computes the factor of the argument passed


def print_factors(x):
print("The factors of",x,"are:")
for i in range(1, x + 1):
if x % i == 0:
print(i)

num = 320

print_factors(num)

Output

The factors of 320 are:


1
2
4
5
8
10
16
20
32
40
64
80
160
320

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

the print_factors() function. This value is assigned to the variable x in print_factors().

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.

Python Program to Make a Simple Calculator!

In this example you will learn to create a simple calculator that can add, subtract, multiply or divide

depending upon the input from the user.

Example: Simple Calculator by Using Functions

# Program make a simple calculator

# This function adds two numbers


def add(x, y):
return x + y

# This function subtracts two numbers


def subtract(x, y):
return x - y

# This function multiplies two numbers


def multiply(x, y):
return x * y

# This function divides two numbers


def divide(x, y):
return x / y

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): ")

# Check if choice is one of the four options


if choice in ('1', '2', '3', '4'):
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))

if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))

elif choice == '2':


print(num1, "-", num2, "=", subtract(num1, num2))

elif choice == '3':


print(num1, "*", num2, "=", multiply(num1, num2))

elif choice == '4':


print(num1, "/", num2, "=", divide(num1, num2))
break
else:
print("Invalid Input")

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-

defined functions add(), subtract(), multiply() and divide() evaluate respective operations and display the

output.

18
Python Program to Create Pyramid Patterns!

In this example, you will learn to print half pyramids, inverted pyramids, full pyramids, inverted full

pyramids, Pascal's triangle, and Floyd's triangle in Python Programming .

Programs to print triangles using *, numbers and characters

Example 1: Program to print half pyramid using *

* *

* * *

* * * *

* * * * *

Source Code

rows = int(input("Enter number of rows: "))

for i in range(rows):
for j in range(i+1):
print("* ", end="")
print("\n")

Example 2: Program to print half pyramid a using numbers

1 2

1 2 3

1 2 3 4

19
1 2 3 4 5

Source Code

rows = int(input("Enter number of rows: "))

for i in range(rows):
for j in range(i+1):
print(j+1, end=" ")
print("\n")

Example 3: Program to print half pyramid using alphabets

B B

C C C

D D D D

E E E E E

Source Code

rows = int(input("Enter number of rows: "))

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

Example 4: Inverted half pyramid using *

* * * * *

* * * *

* * *

* *

Source Code

rows = int(input("Enter number of rows: "))

for i in range(rows, 0, -1):


for j in range(0, i):
print("* ", end=" ")

print("\n")

Example 5: Inverted half pyramid using numbers

1 2 3 4 5

1 2 3 4

1 2 3

1 2

21
Source Code

rows = int(input("Enter number of rows: "))

for i in range(rows, 0, -1):


for j in range(1, i+1):
print(j, end=" ")

print("\n")

Programs to print full pyramids

Example 6: Program to print full pyramid using *

* * *

* * * * *

* * * * * * *

* * * * * * * * *

Source Code

rows = int(input("Enter number of rows: "))

k = 0

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


for space in range(1, (rows-i)+1):
print(end=" ")

while k!=(2*i-1):
print("* ", end="")
k += 1

k = 0

22
print()

Example 7: Full Pyramid of Numbers

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

rows = int(input("Enter number of rows: "))

k = 0
count=0
count1=0

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


for space in range(1, (rows-i)+1):
print(" ", end="")
count+=1

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

rows = int(input("Enter number of rows: "))

for i in range(rows, 1, -1):


for space in range(0, rows-i):
print(" ", end="")
for j in range(i, 2*i-1):
print("* ", end="")
for j in range(1, i-1):
print("* ", end="")
print()

Example 9: Pascal's Triangle

1 1

1 2 1

1 3 3 1

1 4 6 4 1

1 5 10 10 5 1

24
Source Code

rows = int(input("Enter number of rows: "))


coef = 1

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


for space in range(1, rows-i+1):
print(" ",end="")
for j in range(0, i):
if j==0 or i==0:
coef = 1
else:
coef = coef * (i - j)//j
print(coef, end = " ")
print()

Example 10: Floyd's Triangle

2 3

4 5 6

7 8 9 10

Source Code

rows = int(input("Enter number of rows: "))


number = 1

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


for j in range(1, i+1):
print(number, end=" ")
number += 1
print()

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:"))

if(a > b):

print("{0} is Greater than {1}".format(a,b))

elif(b > a):

print("{0} is Greater than {1}".format(b,a))

else:

print("Both a and b are Equal")

Write a Python program to calculate a circle’s area and circumference from the given radius (in cm).

Formula is: πr2


from math import pi
r = float(input ("Input the radius of the circle : "))
print ("The area of the circle with radius " + str(r) + " is: " + str(pi *
r**2))

Output
Input the radius of the circle: 1.1
The area of the circle with radius 1.1 is: 3.8013271108436504

Write a Python program to convert a given number (in hours) to seconds.


def convert_to_preferred_format(sec):
   sec = sec % (24 * 3600)
   hour = sec // 3600
   sec %= 3600
   min = sec // 60
   sec %= 60
   print("seconds value in hours:",hour)
   print("seconds value in minutes:",min)
   return "%02d:%02d:%02d" % (hour, min, sec)
 
n = 10000
print("Time in preferred format :-",convert(n))

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;

printf("Input total distance in km: ");

scanf("%d",&x);

printf("Input total fuel spent in liters: ");

scanf("%f", &y);

printf("Average consumption (km/lt) %.3f ",x/y);

printf("\n");

return 0;

Copy
Sample Output:

Input total distance in km: 350


Input total fuel spent in liters: 5
Average consumption (km/lt) 70.000
Q1: Write a Python program that accepts an employee's total worked hours of a month and the amount
he receives per hour. Print the employee's salary of a particular month.

hrs = input("enter hours:")

h = float(hrs)

xx = input("enter the rate:")

x = float(xx)

if h<=40:

print(h*x)

elif h < 40:

print(40*x+(h-40)*1.5*x)

Output
enter hours:4

27
enter the rate:5

20.0

28

You might also like