What is Python | Python Introduction| Beginners guide-Python

Python is a general purpose, object-oriented, high level programming language. It was developed by Guido van Rossum and first released in 1991. Python is an interpreted programming language known for its simplicity and readability. It is easy to learn compared to other programming languages.

Python is one of the most influential programming languages in the world. It consists of easier syntax and dynamic typing to help programmers gain more control over the language. Python is considered as one of the most versatile programming languages.

Python is used for a variety of applications such as data analytics, AI and machine learning, software development, web development, Game development, software engineering, automation tools, etc.It can easily connect with the database system to store and modify crucial data. It can perform complex algorithms and solve real time problems quickly.

Applications of Python Programming:

Web Development:  Python can be used to develop scalable and secure web applications. Python has frameworks like Django, Flask and Pyramid that can be used for web development. These frameworks provide a proper structure and architecture to our web development project following standards and making it easier even for beginners to code good web applications.

Desktop GUI: Desktop GUI offers many toolkits and frameworks using which we can build desktop applications. PyQt, PyGtk, PyGUI are some of the GUI frameworks.

Computer Software or Desktop Applications: As python can be used to develop GUI too, hence it is a great choice for developing desktop applications. Tk is an open-source widget toolkit which can be used to develop desktop applications with python. Kivy is another such platform.

Game Development: PySoy and PyGame are two python libraries that are used for game development

Artificial Intelligence and Machine Learning: Python is at the fore front of the paradigm shift towards Artificial Intelligence and Machine Learning. There is a large number of open-source libraries which can be used while developing AI/ML applications.

Scientific Computing Application: For its amazing computational power and simple syntax, python is used for scientific computing applications. Python libraries like SciPy and NumPy are best suited for scientific computations.

Image Processing: Python is known for its image processing capabilities, which includes traversing and analysing any image pixel by pixel. There are numerous python libraries available for image processing, for example: Pillow, scikit-image etc.

Data science and Machine learning: Python is the most popular language when it comes to data science and machine learning. There are libraries like NumPy, Pandas, Matplotlib, etc. that make it easy to work with and do analysis on data.

Features of Python Language:

Easy to learn: Python is the easiest programming language to learn. It has few keywords, simple, simple structure and a clearly defined syntax. This allows the student to pick up the language quickly.

Easy to read: Python code is more clearly defined and visible to the eyes.

Easy to maintain: Python’s source code is fairly easy to maintain.

Python is a beginner’s language: Python is a great language for the beginner and supports the development of a wide range of applications. It’s syntax is simple, and straightforward, hence for beginners, it is the best choice.

Versatile language: Python is a general-purpose programming language that can be used for a lot of different purposes like web development, scientific computation, data analysis, etc.

Interpreted Language: Python is an interpreted language, which means that code is executed line by line by an interpreter, rather than being compiled into machine code beforehand. This allows for rapid development and testing, as changes to code can be immediately executed.

Python is Object-Oriented: Python supports object-oriented style or technique of programming that encapsulates code within objects.

Dynamic Typing: Python is dynamically typed, meaning that you don’t need to declare the type of a variable before using it. The type of a variable is determined at runtime based on the value assigned to it.

Python Programming

To get started with Python programming, we’ll need to install Python on our computer. We can download and install Python from the official Python website (python.org). Once installed, we can write Python code using a text editor or an integrated development environment (IDE) such as PyCharm, VS Code, or Jupyter Notebook.
Here’s a simple “Hello, World!” program in Python:
print(“Hello, World!”)

Python Syntax

Python’s syntax emphasizes readability and simplicity, making it an ideal language for beginners and experienced programmers alike.
Python Syntax Rules:
  • Python is case sensitive. Hence a variable with name roll is not same as Roll.
  • In python, there is no command terminator, which means no semicolon; or anything. So if we want to print something as output, all we have to do is:

print (“Hello, World!”)

  • In one line, only a single executable statement should be written and the line change act as command terminator in python.

To write two separate executable statements in a single line, we should use a semicolon (;) to separate the commands. For example,

X=20; print(X)

  • In python, we can use single quotes '', double quotes "" to represent string literals.
  • Comments in Python: In python, we can write comments using a hash sign (#) at the start. A comment is ignored by the python interpreter.

# this is a comment

print (“Hello, World!”)

Multi-Line Statements:
Statements in Python typically end with a new line. Python does, however, allow the use of the line continuation character (\) to denote that the line should continue. For example,
itemOne=23
itemTwo=40
itemThree=50
total=itemOne + \
itemTwo + \
itemThree
print(total);

Code Indentation:

Indentation is used to define code blocks. This is the most important rule of python programming. In programming language like Java, C or C++, generally curly brackets { } are used to define a code block, but python doesn’t use brackets to indicate blocks of code. Python used indentation for this. It is recommended to use tab for indentation. In Python, wrong indentation can lead to syntax errors.

//Using indentation in conditional statement

x = 10

if x > 10:

    print(“x is greater than 10”)

elif x < 10:

    print(“x is less than 10”)

else:

    print(“x is equal to 10”)

The ‘sep’ and ‘end’ parameters in Python print statement

In python, the sep parameter is used as a separator and the end parameter specifies the string that is printed at the end of the line.

The end parameter is used to append any string at the end of the output of the print statement in python while the sep parameter determines the separator between the values passed to the print() function.

In Python, the sep parameter is actually an argument within the print() function. It specifies the separator between the values being printed in Python. By default, it is set to a space character, but you can customize it.

Example:

print(’14’,’11’,’2011’,sep=’-‘)

print(‘Hello’,end=’ ‘)

Variables in Python

Variables are reserved memory locations to store values. Variables are like containers that are used to store values. In Python, variables are case sensitive and consist of letters, numbers, and underscores. The first character in variable’s name cannot be a number.

Python variables do not need explicit declaration to reserve memory space. The declaration happens automatically when we assign a value to a variable. The equal sign (=) is used to assign values to variables.

For example:

x = 10    # An integer assignment

kilometer =1.5 # A Floating point

name = ”Eliza” # String assignment

Multiple assignment:

Python allows us to assign a single value to several variables simultaneously. In following example value 5 is assigned to multiple variables.

a=b=c=5

print(a)

print(b)

print(c)

Data Types in Python

Data types represent the type of data. In python, every value has a datatype, but we need not declare the datatype of variables.  Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the reserved memory.

There are different types of data types in Python, such as integer, float, string , Booleans, list, tuple, dictionary , etc. 

Integers and Boolean

This set comprises of all the Integers like 1, 2, 3,…, 0, -1, -2, -3,… and Boolean values (the one that computer understands) which are true or false (1 or 0 respectively).

Floating Point Numbers

This set deals with the numbers having decimal point values (or any real number). For example, 1.24.768328.0 are all floating-point numbers.

String

Strings in python are set of characters. They are enclosed in single quotes (‘ ‘) or double quotes (” “). The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator. Python does not support a character type; these are treated as strings of length one.

str = “Hello”

Here, we have assigned a value “Hello” to a variable str. This is basically a string data type in Python.

Exercise:

str=”Assam is very beautiful place”

print(str)  # prints the string

print(str[0])  # Prints the first character

print(str[2:5]) # Prints characters starting from 3rd to 5th

print(str[2:])  # Prints characters starting from 3rd character

print(str*2)  # repeats to 2 times

print(str + “ in India”) # Prints concatenated string

Output:

Assam is very beautiful place

A

sam

sam is very beautiful place

Assam is very beautiful placeAssam is very beautiful place

Assam is very beautiful place in India

Triple Quotes:

In Python, triple quotes (either single triple quotes ”’ or double triple quotes “””) are used to create multiline strings. They allow you to define strings that span multiple lines without needing to use escape characters like ‘\n’ for newlines.

While triple quotes are typically used for multi-line strings, they can also serve as a way to create multi-line comments because Python ignores string literals that aren’t assigned to a variable or used in an expression. Therefore, you can use triple quotes to create multi-line strings that effectively act as comments.

Here’s an example of using triple quotes to create a multiline string:

multi_str = ”’

This is a multiline string.

It spans multiple lines.

”’

print(multi_str)

Output:

This is a multiline string.

It spans multiple lines.

String Methods:

Python includes the following built-in methods to manipulate strings:

capitalize(): Returns a copy of the string with the first character capitalized and the rest lowercase.

s = “hello students”

print(s.capitalize()) 

Output:

Hello students

lower(): Returns a copy of the string with all characters converted to lowercase.

s = “HELLO STUDENTS”

print(s.lower()) 

Output:

hello students

upper(): Returns a copy of the string with all characters converted to uppercase.

s = “hello students”

print(s.upper()) 

Output:

HELLO STUDENTS

find(): The find() method finds the first occurrence of the specified value.

s = “Hello, welcome to Assam.”
x = s.find(“welcome”)
print(x)

Output:

7

count(): Return the number of times the value “Assam” appears in the string.

s = “I love Assam, Assam is my birthplace”
x = s.count(“Assam”)
print(x)

Output:

2

isalpha(): The isalpha() method returns True if all the characters are alphabet letters (a-z).

s = “Assam”

x = s.isalpha()

print(x)

Output:

True

isalnum(): The isalnum() method returns True if all the characters are alphanumeric, meaning alphabet letter (a-z) and numbers (0-9).

s = “Assam123”
x = s.isalnum()
print(x)
Output:

True

Lists

Lists are the most versatile of Python’s compound data types. Lists are sequence of values of any type. Values in the list are called elements or items. Lists are mutable and indexed or ordered. A list contains items separated by commas. The list is enclosed in square brackets [ ]. For example, [2, 6, 8, 3, 1] or ["Python", "Java", "C++"] are both lists.

The values stored in list can be accessed using the slice operator ([ ] and [:]) with indexes starting at 0 in the beginning of the list and working their way to end  -1. The plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator.

Example:

list = [‘Assam’, ‘Delhi’, ‘Bihar’, 1205, 5042, 50.452]

smallList = [“Bristee”, “Yashmin”]

print(list)  # Prints the list

print(list[0])   # Prints the first element of the list

print(list[1:3])   # Prints elements starting from 2 till 3rd.

print(list[2:])   # Prints elements starting from 3rd element.

print(smallList *2)   # repeats small list two times

print(list + smallList)   # Prints concatenated list.

Output:

[‘Assam’, ‘Delhi’, ‘Bihar’, 1205, 5042, 50.452]

Assam

[‘Delhi’, ‘Bihar’]

[‘Bihar’, 1205, 5042, 50.452]

[‘Bristee’, ‘Yashmin’, ‘Bristee’, ‘Yashmin’]

[‘Assam’, ‘Delhi’, ‘Bihar’, 1205, 5042, 50.452, ‘Bristee’, ‘Yashmin’]

Tuples

A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by commas. Tuples are enclosed within parentheses (). Tuples are also pretty much like Lists, except that they are immutable, hence once we assign it some value, we cannot change it later. At the same time, it is faster in implementation than List.

The main difference between lists and tuples are:

Lists are enclosed in brackets [ ] and their elements and size can be changed (mutable), while tuples are enclosed in parentheses ( ) and cannot be updated (immutable). Tuples can be thought of as read-only lists.

Example:

tuple=(“Assam”, 1205.12, “Arunachal”, “Manipur”, 152)

smallTuple=(“India”, “Pakistan”)

print(tuple)  #prints tuple

print(tuple[0])  #prints the first element of the tuple

print(tuple[1:3])  #prints the element starting from 2nd till 3rd

print(tuple[2:])  #prints tuple starting from 3rd element

print(smallTuple*2)  #prints tuple twice

print(smallTuple + tuple)  #concatenates tuple

Output:

(‘Assam’, 1205.12, ‘Arunachal’, ‘Manipur’, 152)

Assam

(1205.12, ‘Arunachal’)

(‘Arunachal’, ‘Manipur’, 152)

(‘India’, ‘Pakistan’, ‘India’, ‘Pakistan’)

(‘India’, ‘Pakistan’, ‘Assam’, 1205.12, ‘Arunachal’, ‘Manipur’, 152)

Dictionary:

In Python, a dictionary is a data type that stores a collection of key-value pairs. Dictionaries are mutable, unordered, and indexed collections. Each key in a dictionary must be unique and immutable (such as strings, numbers, or tuples), and it is used to access its corresponding value. Dictionaries are enclosed by curly brackets { } and values can be assigned and accessed using square brakets [ ]

Example:

# Creating a dictionary
dict = {‘name’: ‘Raja’, ‘age’: 30, ‘city’: ‘Mumbai’, ‘dept’: ‘Sales’}

# Accessing values using keys
print(“Name:”, dict[‘name’])
print(“Age:”, dict[‘age’])
print(“City:”, dict[‘city’])
print(“Dept:”, dict[‘dept’])

# Adding a new key-value pair
dict[‘occupation’] = ‘Engineer’


# Iterating over keys
print(“\nKeys:”)
for key in dict.keys():
    print(key)

# Iterating over values
print(“\nValues:”)
for value in dict.values():
    print(value)

# Iterating over items (key-value pairs)
print(“\nItems:”)
for key, value in dict.items():
    print(key, “:”, value) 

# Checking if a key exists
if ‘name’ in dict:
    print(“\n’name’ exists in the dictionary.”) 

# Removing a key-value pair
del dict[‘age’]

# Iterating over keys
print(“\nKeys:”)
for key in dict.keys():
    print(key)

# Clearing the dictionary
dict.clear()

# Iterating over items (key-value pairs)
print(“\nItems:”)
for key, value in dict.items():
    print(key, “:”, value)

# Deleting the dictionary
del dict  

Output:

Name: Raja

Age: 30

City: Mumbai

Dept: Sales

Keys:

name

age

city

dept

occupation

Values:

Raja

30

Mumbai

Sales

Engineer

Items:

name : Raja

age : 30

city : Mumbai

dept : Sales

occupation : Engineer

‘name’ exists in the dictionary.

Keys:
name
city
dept
occupation

Items:

Sets:

A set is an unordered collection of data with no duplicate elements. A set supports operations like union, intersection or difference.
A set is an unordered collection of unique elements. Sets are mutable, meaning their elements can be changed after the set is created, but the set itself is mutable.
Sets in Python are particularly useful when you need to store unique elements and perform operations like finding intersections, unions, etc
Creating a Set: We can create a set in Python using curly braces { } or by using the set() function.
# Creating a set using curly braces
set1= {1, 2, 3, 4}
 # Creating a set using set() function
set2 = set([1, 2, 3, 4])
Adding Elements: We can add elements to a set using the add() method.
set1.add(5)
Removing Elements: We can remove elements from a set using the remove() or discard() methods.
set1.remove(3)
Example:

set1= {1, 2, 3, 4}
print(“Set1: “,set1)
set1.add(5)
print(“Set1: “,set1)
set1.remove(3)
print(“Set1: “,set1)  

Output: 

Set1:  {1, 2, 3, 4}S

et1:  {1, 2, 3, 4, 5}

Set1:  {1, 2, 4, 5}

Operations on Sets: Python sets support various operations like union, intersection, difference, and symmetric difference.
set1 = {1, 2, 3}
set2 = {3, 4, 5}

print(“Union: “,set1 | set2)
print(“Intersection: “,set1 & set2)
print(“Difference: “,set1 – set2)
print(“Symmetric Difference: “,set1 ^ set2)

Output:
Union:  {1, 2, 3, 4, 5}
Intersection:  {3}
Difference:  {1, 2}
Symmetric Difference:  {1, 2, 4, 5}

Operators 

In Python, operators are special symbols that perform operations on operands. In every programming language, operators are used for performing various types of operations on any given operand(s). They are used to evaluate different types of expressions and to manipulate the values of operands or variables by performing different operations on them. Operators are used to carry out arithmetic, comparison, logical, and other operations in a program.
Python language supports the following types of operator.
  1. Arithmetic Operators
  2. Comparison (Relational) Operators
  3. Assignment Operators
  4. Logical Operators
  5. Bitwise Operators
  6. Membership Operators
  7. Identity Operators

While the first five are commonly used operators the last two i.e Membership and Identity operators are exclusive to python.

Here’s an overview of different types of operators in Python:

Arithmetic Operators:

These operators are used to perform arithmetic operations such as addition, subtraction, multiplication, division, modulus, and exponentiation.

Following are different arithmetic operators:

  • Addition (+) : Adds values on either side of the operator
  • Subtraction (-): Subtracts right hand operand from left hand operand
  • Multiplication (*): Multiplies values on either side of the operator
  • Division (/) : Divides left hand operand by right hand operand
  • Modulus (%): Divides left hand operand by right hand operand and returns remainder
  • Exponent (**): Performs exponential (power) calculation on operators
  • Floor Division (//): The division of operands where the result is the quotient in which the digits after the decimal point are removed

Example:

a=6

b=3

add=a+b

print(add) #Output: 9

sub=a-b

print(sub) #Output: 3

mul=a*b

print(mul) #Output: 18

div=a/b

print(div) #Output: 2

mod=a%b

print(mod) #Output: 0

exp=a**b

print(exp) #Output: 216

floor_div=17//5

print(floor_div) #Output: 3

Comparison Operators

These operators are used to compare two values. These operators return True or False Boolean values. They return True if the comparison is true, otherwise False.

Comparison operators in python include:

  • Equal to ==
  • Not equal to !=, <>
  • Greater than >
  • Less than <
  • Greater than or equal to >=
  • Less than or equal to <=

Example:

x = 5
y = 2

# Using the eqaul to comparison operator
if x == y:
    print(‘x is equal to y’)
else:
    print(‘x is not equal to y’)

# Using the not eqaul to comparison operator
if x != y:
    print(‘\nx is not equal to y’)
else:
    print(‘\nx is equxl to y’)

# Using the greater than comparison operator
if x > y:
    print(‘\nx is greater than y’)
else:
    print(‘\nx is not greater thab y’)

# Using the less than comparison operator
if x < y:
    print(‘\nx is less than y’)
else:
    print(‘\nx is not less than y’)

# Using the greater than or equal to  comparison operator
if x >= y:
    print(‘\nx is greater than or equal to y’)
else:
    print(‘\nx is not greater than or equal to y’)

# Using the less than or equal to  comparison operator
if x <= y:
    print(‘\nx is lesser than or equal to y’)
else:
    print(‘\nx is not lesser than or equal to y’)

Output:

x is not equal to y

x is not equal to y

x is greater than y

x is not less than y

x is greater than or equal to y

x is not lesser than or equal to y

Assignment Operators

These operators are used to assign values to variables. The equal to (=) operator is used to assign a value to an operand directly, if we use any arithmetic operator (+-/, etc.) along with the equal to operator then it will perform the arithmetic operation on the given variable and then assign the resulting value to that variable itself.

Basic Assignment Operator:

=Assigns a value to a variable

Compound Assignment Operators:

+=Addition assignment
-=Subtraction assignment
*=Multiplication assignment
/=Division assignment
%=Modulus assignment
//=Floor division assignment
**=Exponentiation assignment

Example:

a = 5
b = 2
c = a + b
print(c)

a += b
print(a)

a -= b
print(a)

a *= b
print(a)

a /= b
print(a)

a %= b
print(a)

a //= b
print(a)

 

Output:

7

7

5

10

2.0

1.0

2.0

Logical Operators

The logical operators are used to perform logical operations (like andornot) and to combine two or more conditions to provide a specific result i.e. true or false.

Bitwise Operators

These operators perform bitwise operations on integers.

Following are different bitwise operators:

Membership Operators

These operators are used to test whether a value or variable is found in a sequence (e.g., strings, lists, tuples, etc.). It returns True or False as output.

Identity Operators

These operators are used to compare the memory locations of two objects.

If statement:

In Python, the if statement is used for conditional execution of code. It allows you to execute a block of code only if a certain condition is true. Here’s the basic syntax:
if condition:
    code block to execute if condition is true

 

We can also extend the if statement with elif (short for “else if”) and else clauses to handle multiple conditions:
if condition1:
    code block to execute if condition1 is true
elif condition2:
    code block to execute if condition2 is true
else:
    code block to execute if none of the above conditions are true

 

Here’s an example demonstrating the usage of if, elif, and else:
x = 10
 if x > 10:
    print(“x is greater than 10”)
elif x < 10:
    print(“x is less than 10”)
else:
    print(“x is equal to 10”)

 

In this example, the code checks the value of x. If x is greater than 10, it prints “x is greater than 10”. If x is less than 10, it prints “x is less than 10”. If neither of these conditions is true (i.e., if x is equal to 10), it prints “x is equal to 10”.

 

Loops 

Python supports loops to help execute a block of code repeatedly. The two main types of loops in Python programming are for and while loops.

 

For loop in Python

In Python, for loop is used to iterate over elements in tuples, list etc in a sequential manner. The syntax of Python loops is given in the table below. Check the example below.

animals = [“cow”, “dog”, “goat”, “cat”]

for i in animals:

print (i)

Output:

cow

dog

goat

cat

While loop in Python

These loops are used to execute a block of code repeatedly until a given condition is true. The basic syntax of the while loop is given in the table below with the help of an example.

Example:

count = 0

while count<5:

         print (count)

         count+=1

Output:

0

1

2

3

4

Functions in Python

Functions in Python are defined using ‘def’ keyword. Functions are made to execute a specific task and are reusable, which eliminates the need to write same line of code again and again.

Example.

def factorial (n):

if n == 0:

return 1

else:

        return factorial (n-1) * n

print(factorial(5))  # Output: 120






1 thought on “What is Python | Python Introduction| Beginners guide-Python”

  1. Thanks for the sensible critique. Me & my neighbor were just preparing to do some research about this. We got a grab a book from our local library but I think I learned more clear from this post. I am very glad to see such fantastic info being shared freely out there.

    Reply

Leave a Comment