Introduction to Python

History of Python

Python is a widely used general-purpose, high-level programming language. It was initially designed by Guido van Rossum in 1991 at CWI in the Netherlands as a successor to ABC capable of exception handling and developed by Python Software Foundation. It was mainly developed for emphasis on code readability, and its syntax allows programmers to express concepts in fewer lines of code.

When it was released, it used a lot fewer codes to express the concepts, when we compare it with Java, C++ & C. Its design philosophy was quite good too. Its main objective is to provide code readability and advanced developer productivity. When it was released it had more than enough capability to provide classes with inheritance, several core data types exception handling and functions.

 

Installing Python on PC

Python is available from its website, Python.org. Once there, hover your mouse over the Downloads menu, then over the Windows option, and then click the button to download the latest release.

Once the package is downloaded, open it to start the installer.

Install an IDE-

To write programs in Python, all you really need is a text editor, but it's convenient to have an integrated development environment (IDE). An IDE integrates a text editor with some friendly and helpful Python features. IDLE 3 and Pycharm (Community Edition) are two great open source options to consider.

IDLE 3

Python comes with an IDE called IDLE. You can write code in any text editor, but using an IDE provides you with keyword highlighting to help detect typos, a Run button to test code quickly and easily, and other code-specific features that a plain text editor like Notepad++ normally doesn't have.

 

To start IDLE, click the Start (or Window) menu and type python for matches. You may find a few matches, since Python provides more than one interface, so make sure you launch IDLE.

PyCharm IDE

To install it, visit the PyCharm IDE website, download the installer, and run it. The process is the same as with Python: start the installer, allow Windows to install a non-Microsoft application, and wait for the installer to finish.

 

Input Output Functoins

In Python, taking input can be done by input functions and show output by using output functions.

Taking input from users-

We can take input by using input() function.

Example-> x=input()

Taking input from user with a message-

Write message inside () with ‘ ’ or “ ”.

Example-> x=input(‘Enter your name: ‘)

                   print(“Hello ”+x)

          output-> Enter your name: Suman

                         Hello Suman

By default input() function takes the user’s input in a string. So, to take the input in the form of int, you need to use int() along with input function.

Example-> x= int(input(“Enter a number ”))

x=x+1

print(x)

          output-> Enter a number 4

                         5

Displaying output-

Python provides the print() function to display output to the console.

Example-> print("Hello")

         # code for disabling the softspace feature 

         print('H', 'E', 'L', 'L', 'O', sep="")

         # using end argument

         print("Python", end = '@')  

         print("Course")

output-> Hello

      HELLO

      Python@Course

 

Formatting Output

We can use formatted string literals, by starting a string with f or F before opening quotation marks or triple quotation marks. In this string, we can write Python expressions between { and } that can refer to a variable or any literal value.

Example-> name = "Jatin"

         print(f'Hello {name}! How are you?')

output-> Hello Jatin! How are you?

 

We can also use format() function to format our output to make it look presentable. The curly braces { } work as placeholders. We can specify the order in which variables occur in the output.

Example-> a = 20

b = 10

print('The value of a is {} and b is {}'.format(a,b))

output-> The value of a is 20 and b is 10

 

Variables

Variables are reserved memory locations to store values. Variables are containers for storing data values. This means that when you create a variable you reserve some space in memory.

Assigning values to variables

Python variables do not need explicit declaration to reserve memory space. The declaration happens automatically when you assign a value to a variable.

n = 100          # n is of type integer

m = 1000.0       # m is of type floating point

name = "John"    # name is of type string

You can also assign multiple objects to multiple variables. For example −

 

a,b,c = 1,2,"john"

 

Comments

Comments are lines in program which does not execute. Comments can be used to explain Python code.

Comments starts with a #, and Python will ignore them:

Example-> #This is a comment

print("Hello, World!")

We can also comment multi lines by using ''' '''

Example-> ''' Hello!

This is a comment written in more than one line

Print fuction will print Hello '''

print("Hello")

Data Types

The data stored in memory can be of many types, and different types can do different things. For example, a person's age is stored as a numeric value and his or her address is stored as alphanumeric characters.

Python has the following data types-

Text Type: str

Numeric Types:  int, float, complex

Sequence Types:          list, tuple, range

Mapping Type:   dict

Set Types:  set, frozenset

Boolean Type:    bool

Binary Types:      bytes, bytearray, memoryview

You can get the data type of any object by using the type() function.

Example-> x= 10

y = "Hello World"

print(type(x))

                    print(type(y))

output-> <class 'int'>

                 <class 'str'>

 

Loop

A for loop is used for iterating over a sequence.

Python has two primitive loop commands:

while loops

for loops

 

For loop

for loop can be used execute a set of statements, once for each item in a list, tuple, set etc.

Example-> li= [1,3,6,2]

for i in li: #for loop will print each element in the list

                   print(i)

output-> 1 3 6 2

 

Looping a string-

Example-> s= "Hello World"

for i in s:

    print(i, end="")

          output-> Hello World

 

Looping in a range-

To loop from a starting to ending point use range function, which will take starting and ending point (in case you don’t provide stating point it will take 0 as default starting point).

Example-> for i in range(0,7):

    print(i, end=" ")

          output-> 0 1 2 3 4 5 6

 

While loop

With the while loop we can execute a set of statements as long as a condition is true.

Example-> i = 1

while i < 6:   #print i until i is less than 6

  print(i)    

  i += 1

          output-> 1 2 3 4 5

 

 

 

 

Control Statements

Control statements in python are used to control the flow of execution of the program based on the specified conditions.Python supports 3 types of control statements such as, break, continue and pass.

 

Break Keyword

Loops iterate over a block of code until the condition becomes false, but sometimes we need to terminate the current iteration without checking test expression in that case we use break. The break statement terminates the loop containing it.

If the break statement is inside a nested loop (loop inside another loop), the break statement will terminate the innermost loop.

Example-> x= int(input("Enter a number"))

for i in range(0,x):

    if i==3:  #when i becomes 3 the for loop will terminate and we come out of the loop

        break

    print(i)   

          output-> Enter a number 5 

       0

       1

                 2

 

Continue Keyword

The continue statement is used to returns the control to the beginning of the loop.It is used to end the current iteration in a loop, and continues to the next iteration.

Example-> for i in range(9):

  if i == 3:  # if i becomes 3, it will skip printing 3 and will execute from next iteration

    continue

  print(i)

output-> 0 1 2 4 5 6 7 8

 

Pass Keyword

The pass statement is used as a placeholder for future code.

When the pass statement is executed, nothing happens, but you avoid getting an error when empty code is not allowed.

Empty code is not allowed in loops, function definitions, class definitions, or in if statements.

Example-> def function():

                             pass       #this function will do nothing

 

Some Programs in Python-

Q) Write a program in python to find sum of two numbers.

->      num1 = int(input("Enter first number "))

          num2 = int(input("Enter second number "))

          sum = num1 + num2

          print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))

output-> Enter first number 5

Enter second number 6

The sum of 5 and 6 is 11

 

Q) Write a Python program to calculate the area of a Triangle.

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

 

          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-> Enter first side: 2

       Enter second side: 3

       Enter third side: 4

       The area of the triangle is 2.90

 

Q) Given two numbers, write a Python code to find the Maximum of these two numbers.

a = 2

b = 4

if a >= b:

    print(a)

else:

    print(b)

output-> 4

 

Q) Write a program to find factorial of a number.

n=5

fact=1

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

    fact=fact*i

print("Factorial of {} is {}".format(n,fact))

 

Q) Write a python program to swap two variables.

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-> Enter value of x: 5

Enter value of y: 6

The value of x after swapping: 6

The value of y after swapping: 5

 

Q) Write a python Program to Find the Sum of Natural Numbers.

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

sum = 0 

# use while loop to iterate un till zero 

while(num > 0): 

   sum += num 

   num -= 1 

print("The sum is",sum) 

output-> Enter a number: 5

       The sum is 15