Learn Python Programming




This is the best way for learning Python programming. From here you can easily learn Python programming. You will find all the programs for Python programming.All programs are checked. So lets Start learning…….


What is Python ?

Python is a interpreted high-level programming language for general purpose programming. Created by Guido van Rossum and first relesed in 1991, Python has a design philosophy that emphasizes code readability , notably using significant  whitespace.


Simple Python Programs

Python Program to Find the Sum of Natural Numbers


In this program, you'll learn to find the sum of a natural number using while loop and display it.


In the program below, we've used an if else statement in combination with a while loop to calculate the sum of natural upto num.

 # Python program to find the sum of natural up to n where is provided by user 

# change this value for a different result
num = 16

# uncomment to take input from the user 
# num = int(input("Enter a number :"))

if num < 0:
    print("Enter a positive number ")
else:
    sum = 0
   # use while loop to iterate un till zero
  while (num > 0)
        sum += num
        num -= 1
  print("The sum is",sum)


Output

The sum is 136


Note : To test the program , change the value of num.

Here, we store the number in num and display the sum of natural numbers up to that number. We use while loop to iterate until the number becomes zero.

We could have solved the above program without using any loop using any loops using any loops using a formula directly.

Your turn : Modify the above program to find the sum of natural numbers using the formula below.
n*(n+1)/2

For example, if n = 16, the sum would be (16 * 17)/2 = 136.




Python Program o Print Fibonacci Sequence


In this program, you'll learn to print the fibonacci  sequence using while loop.

A Fibonacci sequence is the integer sequence of 0,1,1,2,3,5,8.....

The first terms are 0 and 1. All other terms are obtained by adding the preceding two terms. This means to say the nth terms is the sum of (n-1)th and (n-2)th term.


# Program to display the Fibonacci sequence up to n-th term where is provided by user

# change this value for a different result
nterms = 10

# uncomment to take input from the user
# nterms = int(input("How many terms?"))

# first two terms
n1 = 0
n2 = 1
count = 0

# check if the number of terms is valid
if nterms <= 0:
     print("Please enter a positive integer")
elif nterms == 1:
    print("Fiboncci sequence upto",nterms,":")
    print(n1)
else:
    print("Fibonacci sequence upto",nterms,":")
   while count < nterms :
          print(n1,end=',')
          nth = n1 + n2


Output

Fibonacci sequence upto 10 :

0,1,1,2,3,5,8,13,21,34


Note : To test this program, change the value of nterms.

Here, we store the number of terms. We intilize the first term to 0 and the second term to 1.

If the number of terms in the sequence by adding the preceding two terms. We then interchange the variable (update it) and continue on with the process.

You can also solve this problem using recursion : Python program to print the Fibbonaci sequence using recursion.
   



Python Program to Display the multiplication Table


This program displays the multiplication table of variable num (from 1 to 10).

In the program below, we have used the for loop to display the multiplication table of 12.

# Python program to find the multiplication table (from 1 to 10)

num = 12

# To take input from the user 
# num = int(input("Display multiplication table of?"))

# use for loop to iterate 10 times 
for i in range (1, 11):
     print(num,'x',i,'=',num*i)


Output

12 x 1 = 12 
12 x 2 = 24 
12 x 3 = 36 
12 x 4 = 48 
12 x 5 = 60 
12 x 6 = 72 
12 x 7 = 84 
12 x 8 = 96
12 x 9 = 108
12 x 10 = 120


To iterate 10 times, for loop along with the range() function is used. The arguments inside range function is (1,11) meaning, greater than or equal to 1 and less than 11 (meaning 10).

We have displayed the multiplication table of variable num (which is 12 inour case). You can change the value of num in the above program to test out for other value.




Python Program to Find Factorial of a Number


In this Program, you'll learn to find the factorial of a number and display it.

The factorial of a number is the product of all the integer from 1 to that number.

For example, the factorial of 6 (denoted as 6) is 1*2*3*4*5*6 = 720. Factorial is not defined for negative numbers and the factorial of Zero is one, 0! = 1.

#Python program to find the factorial of a number provided by the user.

# change the value for a different result
num = 7

# uncomment to take input from the user 
# num = int(input("Enter a number:"))

factorial = 1

# check if the number is negative, positive or Zero
if num > 0:
   print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
   print("The factorial of 0 is 1")
else:
  for i in range (1,num + 1):
          factorial = factorial * i:
 print("The factorial of",num,"is",factorial)


Output

The factorial of 7 is 5040


Note : To set program , change the value of num. Try negative numbers as well.

Here the number whose factorial is to be found is stored in num and we check if the number is negative , Zero or positive using if...elif...else statement. If the number is positive, we use for loop and range() function to calculate the factorial.


Python Program to Print all Prime Numbers in an Interval


In this program, you'll learn to print all prime numbers within an interval using for loop and diplay it.

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 number as they do not have any other factors. But 6 is not prime (it is composite) Since, 2 * 3 = 6.


# Python program to display all the prime numbers within an interval

# change the values of lower and upper for a different result
lower = 900
upper = 1000

# uncomment the following lines to take input from the user 
# lower = int(input("Enter lower range:")) 
# upper = int(input("Enter upper range:")) 

print("Prime number between",lower,"and",upper,"are:")

for num in range(lower,upper + 1):
    # prime number are greater than 1
   if num> 1:
        for i in range (2,num):
              if(num % i) == 0:
              break
       else:
              print(num)

Output

Prime numbers between 900 and 1000 are :
907
911
919
929
937
941
947
953
967
971
977
983
991
997

Here, we store the interval as lower for lower interval and upper for upper interval, and find prime numbers in that range. Visit this page to understand the code to check for prime numbers.




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 a prime number, 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 number as they do not have any other factors. But 6 is not prime (it is composite) Since 2  * 3 = 6.

# Python program to check if the input number is prime or not 

num = 407

# 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


In this program, variable num is checked If it's prime or not. Number less than or equal to 1 are not prime number. 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. else the number is prime.

We can decrease the range of number where we look for factors.

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

We could have used range, [2, num / 2] or [2, num ** 0.5]. The later range is based on the fact that a composite number must have a factor less than square root of that number; otherwise the number is prime.

You can change the value of variable num in the above source code and test or other integer (if you want). 





Python Program to Find the Number Among Three Numbers


In this program, you'll learn to find the largest among thee numbers using if else and display it.

In the program  below, the three numbers are srored in num1,num2 and num3 respectively. We've used the if....else....else ladder to find the largest among the three and display it.

# 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 (num2 >= num2) and (num1 >= num3):
         largest = num1
if (num1 >= num1) and (num2 >= num3):
         largest = num2
else:
         largest = num3

print("The largest number between ","num1",""num2,"num3","is",largest)

Output

The largest number between 10, 14 and 12 is 14.0

Note : To test the program, change the values of num1, num2, num3.



Python Program to Check Leap year


In this program, you will learn to check whether a year is a leap year or not. We will use nested if... else to solve this problem.

#Python program to check if the input year is a leap year or not 

year = 2000

# To get year (integer input ) from the user 
# year = int(input("Enter s year:"))

if (year % 4) == 0:
     if(year % 100) == 0:
            if(year % 400) == 0:
                     print("{0} is a leap year" .format (year))
           else:
                    print("{0} is not a leap year" .format (year))
     else:
          print("{0} is a leap year" .format (year))
else:
    print("{0} is not a leap year" .format (year))


Output

2000 is a leap year




Python Program to Check if a Number is Even or Odd


#Python progran to check if the input number is odd or even
# A number is even if division by 2 give a remainder of 0 
# If remainder is 1, it is 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

Enter a number: 43
43 is Odd




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


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

Output

Enter a number : 2
Positive number


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

Output

Enter a number: 0
Zero







Python Program to convert Celsius TO Fahrenheit


# 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 




Python Program to Convert Kilometers to Miles


kilometers = 5.5

#To take kilometers from the user , uncomment the code below 
kilometers = input(''Enter values in kilometers'')

# conversion factor
conv_fac = 0.621371

#calculate miles 
miles = kilometers * conv_fac
print('%0.3f kilometers is equal to %0.3f miles ' %(kilometers , miles ))

Output

5.500 kilometers is equal to 3.418 miles 





Python Program to Generate a Random Number


# Program to generate a random number between 0 and 9

# import the random module 
import random

print(random,randint(0,9))


Output

5




Python program to Swap Two Values


#Python program to swap two values 

#To take input from the user 
#x = input('Enter value of x: ')
#y = input('Enter value of y: ')

x = 5
y = 10

#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


Source code : Without using third variable 

x,y = y,x

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

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




Python Program to Solve Quadratic Equation


# Solve the quadratic equation  ax**2 + bx + c = 0

#import complex math module 
import cmath

a = 1
b = 5
c = 6

# To take coefficient input from the users
# a = float (input ('Enter a: ' ))
# b = float (input ('Enter a: ' ))
# c = float (input ('Enter a: ' ))

#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

Enetr a: 1
Enetr b: 5
Enetr c: 6
The solution are (-3+0j) and (-2+0j)




Python program to Calculate The Area of Triangle


In this program, you'll learn to calculate the area of triangle and display it.

#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 - a)*(s - c)) ** 0.5
print('The area of triangle is %0.2f ' %aera)

Output

The area of triangle is 14.70





Python Program to Find the Square Root


In this program, you'll learn to find square root of a number using exponent operator and cmath module.

For positive numbers using exponent**

#Python program to calculate the square root

#Note : change this value for a different results
num = 8

#uncomment to take 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 works for all positive real numbers. But for negative or complex numbers, it can be as folows. 


For real or complex numbers using cmath module

#Find square root of real or complex numbers
#Import the complex math module
import cmath

#change this value for a different results
num = 1+2j

#uncomment to take input from the user
#num = eval (input('Enter a number:'))
num_sqrt = cmath.sqrt (num)
print('The square root of {0} is {1:0.3f}+{2:0.3f}'.format(num,num_sqrt.real,num_sqrt.imag))

Output

The square root of (1+2j) is 1.272+0.786j 

In this program, we use the sqrt() function in the cmath (complex math) module.

Notice that we have used eval() function instead of float() to convert complex numbers as well. Also notice the way in which the output is formatted.



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 airthmetic addition operator (+) to add two numbers. 

#This program add two numbers 

num1 = 1.5
num2 = 6.3


#Add two numbers 
sum = float(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


Changing this operator, we can subtract (-), multiply (*), divide(/) , floor divide (//) or find the reminder, (%) of two numbers.


Add two Numbers Provided by The User

# Store input numbers
num1 = input('Enter first number:')
num2 = input('Enter second number:')

#Add two nmbers
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.

In the program, we asked user to enter two numbers and this program display the sum of two numbers entered by user. 

We used the built-in function input() to take the input input() returns a string, so we covert in into number using the float () function.

Alternative to this, we can perform the addition in a single statement without using any variable as follows. 



Python Program to Print Hello World !


A simple program to displays "Hello World!" . Its 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.

String is a sequence of characters. In python string are enclosed inside single quotes, double quotes or triple quotes("",""").