Introduction to Python Programming Basics
Introduction to Python Programming Basics
UNIT-I
Basics of Python
Syllabus:
Learning Outcomes:
At the end of this unit, the student will be able to
1. Understand the programming in Python using the REPL(Shell).
2. Categorize the types, operators and expressions in python programming.
Introduction:
Python is a widely used programming language that offers several unique features and
advantages compared to languages like Java and C++.
In the late 1980s, Guido van Rossum dreamed of developing Python. The first version
of Python 0.9.0 was released in 1991. Since its release, Python started gaining popularity.
According to reports, Python is now the most popular programming language among
developers because of its high demands in the tech realm.
What is Python?
Python is a general-purpose, dynamically typed, high-level, compiled and interpreted, garbage-
collected, and purely object-oriented programming language that supports procedural, object-
oriented, and functional programming.
Features of Python:
• Easy to use and Read - Python's syntax is clear and easy to read, making it an ideal
language for both beginners and experienced programmers. This simplicity can lead to
faster development and reduce the chances of errors.
• Dynamically Typed - The data types of variables are determined during run-time. We
do not need to specify the data type of a variable during writing codes.
• High-level - High-level language means human readable code.
• Compiled and Interpreted - Python code first gets compiled into bytecode, and then
interpreted line by line. When we download the Python in our system form org we
download the default implement of Python known as CPython. CPython is considered to
be Complied and Interpreted both.
• Garbage Collected - Memory allocation and de-allocation are automatically managed.
Programmers do not specifically need to manage the memory.
• Purely Object-Oriented - It refers to everything as an object, including numbers and
strings.
History of Python
Python was created by Guido van Rossum. In the late 1980s, Guido van Rossum, a Dutch
programmer, began working on Python while at the Centrum Wiskunde & Informatica (CWI) in
the Netherlands. He wanted to create a successor to the ABC programming language that
would be easy to read and efficient.
In February 1991, the first public version of Python, version 0.9.0, was released. This
marked the official birth of Python as an open-source project. The language was named after
the British comedy series "Monty Python's Flying Circus".
Now, you can enter a single statement and get the result. For example, enter a simple expression
like 3 + 2, press enter and it will display the result in the next line, as shown below.
Python Variables
A variable is the name given to a memory location. Since Python is an infer language that is
smart enough to determine the type of a variable, we do not need to specify its type in Python.
Variable names must begin with a letter or an underscore, but they can be a group of both
letters and digits. The name of the variable should be written in lowercase. Python is case-
sensitive language.
Ex:1 Ex:2
type(“SRIT”) type(252)
Output: <class 'str'> Output: <class 'int'>
Multiple Assignment
Multiple assignments, also known as assigning values to multiple variables in a single statement,
is a feature of Python.
Ex: a, b, c = 5,10,15
The values will be assigned in the order in which variables appear.
Comments in Python
Comments are textual descriptions that are ignored by python interpreter. Python supports
three style of comments
• Single-line Comments
• Multi-line Comments
• Documentation Strings
Single-Line Comments
A single-line comment of Python is the one that has a hashtag # at the beginning of it and
continues until the finish of the line. If the comment continues to the next line, add a hashtag to
the subsequent line.
Multi-Line Comments
Python does not provide the facility for multi-line comments. In Python, we may use hashtags
(#) multiple times to construct multiple lines of comments.
The strings enclosed in triple quotes that come immediately after the defined function are called
Python docstring. It's designed to link documentation developed for Python modules, methods,
classes, and functions together. It's placed just beneath the function, module, or class to explain
what they perform. The docstring is then readily accessible in Python using the __doc__
attribute.
Python Keywords
Every scripting language has designated words or keywords, with particular definitions and
usage guidelines. Python is no exception. The fundamental constituent elements of any Python
program are Python keywords.
Python keywords are unique words reserved with defined meanings and functions that we can
only apply for those functions.
The following table shows some keywords for the reference, some keywords are added or
deleted according to the versions.
as elif in try
To retrieve the collection of keywords in the version you are working on.
Import keyword
print([Link])
OR
help(“keywords”)
In this we will see different ways of reading input from the user and displaying output to the
user
The input() function is used to take user input at some point in the program.
Syntax:
import(‘prompt’)
Here prompt is an optional string that is displayed on the string at the time of taking input.
Python provides the print() function to display output to the standard output devices.
Syntax:
Parameters:
value(s): Any value, and as many as you like. Will be converted to string before printed
sep=’separator’: (Optional) Specify how to separate the objects, if there is more than one.
Default :’ ‘
end=’end’: (Optional) Specify what to print at the end. Default : ‘\n’
file : (Optional) An object with a write method. Default :[Link]
flush : (Optional) A Boolean, specifying if the output is flushed (True) or buffered (False).
Default: False
Example 1: Python script to get user input and display with a message
Python takes all the input as a string input by default. To convert it to any other data type we
have to convert the input explicitly. For example, to convert the input to int or float we have to
use the int() and float() method respectively.
add = num + 1
# Output
print(add)
Output:
Enter a number: 45
46
We can take multiple inputs of the same data type at a time in python, using map() method in
python.
Output:
Programming
Programming Language
Example: Python Print output with custom sep and end parameter
Output:
Python@P#y#t#h#o#n
Python Indentation
Indentation is a very important concept of Python because without properly indenting the
Python code, you will end up seeing IndentationError and the code will not get compiled.
Python indentation refers to adding white space before a statement to a particular block of code.
In another word, all the statements with the same space to the right, belong to the same code
block.
Python indentation is a way of telling a Python interpreter that the group of statements belongs
to a particular block of code. A block is a combination of all these statements. Block can be
regarded as the grouping of statements for a specific purpose. Most programming languages
like C, C++, and Java use braces { } to define a block of code.
Whitespace is used for indentation in Python. All statements with the same distance to the right
belong to the same block of code. If a block has to be more deeply nested, it is simply indented
further to the right.
Example:
Animals
--------- Domestic Animals
------------------- Cat
------------------- Dog
---------- Wild Animals
------------------- Tiger
------------------- Lion
------------------- Deer
A variable can contain a variety of values. The following is a list of the Python-defined data
types.
• Numbers
• Sequence Type
• Boolean
• Set
• Dictionary
Numbers
Numeric values are stored in numbers. The whole number, float, and complex qualities have a
place with a Python Numbers datatype. Python offers the type() function to determine a
variable's data type. When a number is assigned to a variable, Python generates Number
objects.
Python supports three kinds of numerical data.
• int: Whole number worth can be any length, like numbers 10, 2, 29, - 20, - 150, and so
on.
• float: Float stores drifting point numbers like 1.9, 9.902, 15.2, etc. It can be accurate to
within 15 decimal places.
• complex: An intricate number contains an arranged pair, i.e., x + iy, where x and y signify
the real and imaginary parts separately. The complex numbers like 2.14j, 2.0 + 2.3j, etc.
Example:
a=5
print("The type of a", type(a))
b = 40.5
print("The type of b", type(b))
c = 1+3j
print("The type of c", type(c))
Output:
The type of a <class 'int'>
The type of b <class 'float'>
The type of c <class 'complex'>
Boolean
True and False are the two default values for the Boolean type. These qualities are utilized to
decide the given assertion valid or invalid. The class bool indicates this. False can be
represented by the 0 or the letter "F," while true can be represented by any value that is non-
zero.
Example:
Sequence Type
Set
The data type's unordered collection is Python Set. It is iterable, mutable(can change after
creation), and has remarkable components. The elements of a set have no set order; It might
return the element's altered sequence. Either a sequence of elements is passed through the
curly braces and separated by a comma to create the set or the built-in function set() is used to
create the set. It can contain different kinds of values.
Operators in Python
The operator is a symbol that performs a specific operation between two operands, according to
one definition. Python has some operators, and these are given below –
• Arithmetic operators
• Comparison operators (Relational Operators)
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators
Arithmetic Operators
Arithmetic operators used between two operands for a particular operation. It includes the
exponent (**), + (addition), - (subtraction), * (multiplication), / (divide), % (reminder), and //
(floor division) operators.
Operator Description
It is used to add two operands.
+ (Addition)
For example, if a = 10, b = 10 => a+b = 20
It is used to subtract the second operand from the first operand.
- (Subtraction)
For example, if a = 20, b = 5 => a - b = 15
It returns the quotient after dividing the first operand by the second operand.
/ (divide)
For example, if a = 25, b = 2 => a/b = 12.5
It is used to multiply one operand with the other.
* (Multiplication)
For example, if a = 20, b = 4 => a * b = 80
It returns the reminder after dividing the first operand by the second
% (reminder) operand.
For example, if a = 20, b = 10 => a%b = 0
Source Code:
Output:
Comparison operators mainly use for comparison purposes. Comparison operators compare the
values of the two operands and return a true or false Boolean value.
Consider the following table for a detailed explanation of comparison operators.
Operator Description
== If the value of two operands is equal, then the condition becomes true.
!= If the value of two operands is not equal, then the condition becomes true.
The condition is met if the first operand is smaller than or equal to the
<=
second operand.
The condition is met if the first operand is greater than or equal to the
>=
second operand.
If the first operand is greater than the second operand, then the condition
>
becomes true.
If the first operand is less than the second operand, then the condition
<
becomes true.
Source Code:
a = int(input(“Enter first number:”))
b = int(input(“Enter Second number:”))
print(“Two numbers are equal or not:”, a==b)
print(“Two numbers are not equal or not:”, a!=b)
print(“a is less than or equal to b:”, a<=b)
print(“a is greater than or equal to b:”, a>=b)
print(“a is greater b:”, a>b)
print(“a is less than b:”, a<b)
Output:
Enter first number: 32
Enter first number: 6
Two numbers are equal or not: False
Two numbers are not equal or not: True
a is less than or equal to b: False
a is greater than or equal to b: True
a is greater b: True
a is less than b: False
Assignment Operators
Using the assignment operators, the right expression's value is assigned to the left operand.
There are some examples of assignment operators like =, +=, -=, *=, %=, **=, //=.
Consider the following table for a detailed explanation of assignment operators.
Operator Description
It assigns the value of the right expression to the left operand.
=
For example, a = 10
By adding the value of the right operand to the value of the left operand, the left
operand receives a changed value.
+=
For example, if a = 10, b = 20 => a+ = b will be equal to a = a+ b and therefore, a =
30.
It decreases the value of the left operand by the value of the right operand and
assigns the modified value back to left operand.
-=
For example, if a = 20, b = 10 => a- = b will be equal to a = a- b and therefore, a =
10.
It multiplies the value of the left operand by the value of the right operand and
assigns the modified value back to then the left operand.
*=
For example, if a = 10, b = 20 => a* = b will be equal to a = a* b and therefore, a =
200.
It divides the value of the left operand by the value of the right operand and
assigns the reminder back to the left operand.
%=
For example, if a = 20, b = 10 => a % = b will be equal to a = a % b and therefore, a
= 0.
a**=b will be equal to a=a**b,
**=
For example, if a = 4, b =2, a**=b will assign 4**2 = 16 to a.
a//=b will be equal to a = a// b,
//=
For example, if a = 4, b = 3, a//=b will assign 4//3 = 1 to a.
Bitwise Operators
The two operands' values are processed bit by bit by the bitwise operators. The examples of
Bitwise operators are bitwise OR (|), bitwise AND (&), bitwise XOR (^), negation (~), Left shift
(<<), and Right shift (>>). Consider the case below.
Operator Description
A 1 is copied to the result if both bits in two operands at the same location
& (binary and)
are 1. If not, 0 is copied.
The resulting bit will be 0 if both the bits are zero; otherwise, the resulting
| (binary or)
bit will be 1.
^ (binary xor) If the two bits are different, the outcome bit will be 1, else it will be 0.
The operand's bits are calculated as their negations, so if one bit is 0, it will
~ (negation)
change to 1, and vice versa.
The left operand is moved left by the number of shifts given in the right
<< (left shift)
operand.
The left operand is moved right by the number of shifts given in the right
>> (right shift)
operand.
Logical Operators
The assessment of expressions to make decisions typically uses logical operators. The
examples of logical operators are and, or, and not. Python supports the following logical
operators. Consider the following table for a detailed explanation of logical operators.
Operator Description
and The condition will be True, if both expressions are True only.
not If an expression is true, then not (a) will be false and vice versa.
Membership Operators
The membership of a value inside a Python data structure can be verified using Python
membership operators. The result is true if the value is in the data structure; otherwise, it
returns false.
Operator Description
If the first operand is a member of the second operand, it is evaluated to be true
in
(list, tuple, or dictionary).
If the first operand is not a member of the second operand, the evaluation is
not in
true (list, tuple, or dictionary).
Source Code:
fruits = [“Apple”, “Mango”, “Banana”]
print("Orange" in fruits)
print("Orange" not in fruits)
print("Mango" in fruits)
print("Mango" not in fruits)
Output:
False
True
True
False
Identity Operators
Operator Description
If the references on both sides point to the same object, it is determined to
is
be true.
If the references on both sides do not point at the same object, it is
is not
determined to be true.
Source Code:
names1 = ["Raju","Ravi","Rani"]
names2 = ["Raju","Ravi","Rani"]
names3 = names1
print(names3 is names1)
print(names1 is names2)
print(names1 is not names2)
print(names3 is not names1)
Output:
True
False
True
False
Statement Description
The if statement is used to test a specific condition. If the condition is
if Statement
true, a block of code (if-block) will be executed.
The if-else statement is similar to if statement except that, it also
provides the block of the code for the false case of the condition to be
if - else
Statement checked. If the condition provided in the if statement is false, then the
else statement will be executed.
Nested if statements enable us to use if - else statement inside an
Nested if
statement outer if statement.
Indentation in Python
For the ease of programming, python doesn't allow the use of parentheses for the block level
code. It is the most used part of the python language since it declares the block of code. All the
statements of one block are intended at the same level indentation.
The if statement
The if statement is used to test a particular condition and if the condition is true, it
executes a block of code known as if-block. The condition of if statement can be any valid logical
expression which can be either evaluated to true or false.
Example 1:
# Simple Python program to understand the if statement
num = int(input("enter the number:"))
if num%2 == 0:
print("The Given number is an even number")
Output:
enter the number: 10
The Given number is an even number
if expression 1:
# block of statements
elif expression 2:
# block of statements
elif expression 3:
# block of statements
else:
# block of statements
Example 1
number = int(input("Enter the number?"))
if number==10:
print("The given number is equals to 10")
elif number==50:
print("The given number is equal to 50")
elif number==100:
print("The given number is equal to 100")
else:
print("The given number is not equal to 10, 50 or 100")
Output:
Enter the number?15
The given number is not equal to 10, 50 or 100
Example 2
marks = int(input("Enter the marks? "))
if marks > 85 and marks <= 100:
print("Congrats ! you scored grade A ...")
elif marks > 60 and marks <= 85:
print("You scored grade B + ...")
elif marks > 40 and marks <= 60:
The following looping statements are available in the Python programming language.
S. No. Name of the loop Loop Type & Description
Repeats a statement or group of statements while a given
1 while loop condition is TRUE. It tests the condition before executing the
loop body.
This type of loop executes a code block multiple times and
2 for loop
abbreviates the code that manages the loop variable.
3 Nested loops We can iterate a loop inside another loop.
Statements used to control loops and change the course of iteration are called control
statements.
Python provides the following loop control statements.
Name of the
S. No. Description
control statement
In this case, the variable value is used to hold the value of every item present in the sequence
before the iteration begins until this particular iteration is completed. Loop iterates until the
final item of the sequence are reached.
Code
# Python program to show how the for loop works
numbers = [4, 2, 6, 7, 3, 5, 8, 10, 6, 1, 9, 2]
square = 0
squares = []
for value in numbers:
square = value ** 2
squares. append(square)
print("The list of squares is", squares)
Output:
The list of squares is [16, 4, 36, 49, 9, 25, 64, 100, 36, 1, 81, 4]
Code
# Python program to show the working of range() function
print(list(range(15)))
print(list(range(4, 9)))
print(list(range(5, 25, 4)))
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
[4, 5, 6, 7, 8]
[5, 9, 13, 17, 21]
To iterate through a sequence of items, we can apply the range() method in for loops. We can
use indexing to iterate through the given sequence by combining it with an iterable's len()
function.
Code
# Python program to iterate over a sequence with the help of indexing
tuple_ = ("Python", "Loops", "Sequence", "Condition", "Range")
# iterating over tuple_ using range() function
for iterator in range(len(tuple_)):
print(tuple_[iterator].upper())
Output:
PYTHON
LOOPS
SEQUENCE
CONDITION
RANGE
While Loop
While loops are used in Python to iterate until a specified condition is met. The while loop is
terminated once the condition changes to false.
Syntax of the while loop is:
while <condition>:
{ code block }
Code
# Python program to show how to use a while loop
counter = 0
# Initiating the loop
while counter < 10: # giving the condition
counter = counter + 3
print("Python Loops")
Output:
Python Loops
Python Loops
Python Loops
Python Loops
pass statement
Pass statements are used to create empty loops. Pass statement is also employed for classes,
functions, and empty control statements.
Code
# Python program to show how the pass statement works
for string in "Python Loops":
pass
print( 'Last Letter:', string)
Output:
Last Letter: s
*****