0% found this document useful (0 votes)
5 views55 pages

Python (Unit 1)

The document provides an introduction to Python, highlighting its characteristics as a high-level, versatile, object-oriented, interpreted, and open-source programming language. It covers the benefits of Python, installation steps, and essential programming concepts such as identifiers, keywords, statements, expressions, variables, operators, and data types. Additionally, it explains the rules for naming variables and the importance of operator precedence and associativity.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views55 pages

Python (Unit 1)

The document provides an introduction to Python, highlighting its characteristics as a high-level, versatile, object-oriented, interpreted, and open-source programming language. It covers the benefits of Python, installation steps, and essential programming concepts such as identifiers, keywords, statements, expressions, variables, operators, and data types. Additionally, it explains the rules for naming variables and the importance of operator precedence and associativity.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

MODULE 1

INPUT & OUTPUT

Dr. Surjeet Kumar


Assistant Professor
Computer Science and Engineering
Government Engineering College
Sheikhpura, Bihar
WHAT IS PYTHON

Python is a High-level, Versatile, Object-oriented, Interpreted and Open-source


programming language. It is widely used in Web Development, Data Analysis, Machine
Learning, Automation, and more.
❑ High Level -Its syntax is designed to be easy for humans to read and write. It more
accessible compared to lower-level, machine-focused languages.
❑ Versatile - That can be used for a wide variety of tasks and applications.
❑ Object-Oriented - Which allows developers to organize code into reusable objects that
contain data and methods.
❑ Interpreted - Which means the code is executed line by line, rather than being
compiled into machine code beforehand.
❑ Open-source - The original source code is made freely available for anyone to use,
modify, and distribute.
WHY NAME IS USED PYTHON

The programming language Python was developed in 1980 by Guido van Rossum.

He was also reading the published scripts from the BBC


comedy series "Monty Python's Flying Circus”.

Therefore, the name "Python" for the programming


language is a direct reference to the comedy cast, not the snake.
WHAT ARE THE BENEFITS OF PYTHON

• Developers can easily read and understand a Python program because it has basic,
English-like syntax.
• Python makes developers more productive because they can write a Python program
using fewer lines of code compared to many other languages.
• Python has a large standard library that contains reusable codes for almost any task.
• Developers can easily use Python with other popular programming languages such as
Java, C, and C++.
• The active Python community includes millions of supportive developers around the
globe. If you face an issue, you can get quick support from the community.
• Plenty of helpful resources are available on the internet if you want to learn Python. For
example, you can easily find videos, tutorials, documentation, and developer guides.
• Python is portable across different computer operating systems such as Windows,
macOS, Linux, and Unix.
FEATURES OF PYTHON
INSTALLATION PYTHON

• For Windows Operating System (Step by Step) –


Download Python
1. Visit [Link] and download the Windows installer.
2. Choose the appropriate version (32-bit or 64-bit) based on your system.
Install Python
1. Run the installer.
2. Check the box "Add Python to PATH" to make Python accessible from
the Command Prompt.
3. Choose Customize Installation for optional features like pip, IDLE, and
development tools.
4. Complete the installation process.
Verify Python and Pip Installation
Open Command Prompt and run:
python --version
pip --version

Install Essential Libraries


Use pip to install Python libraries.
Example-
Install libraries:
pip install numpy pandas matplotlib
IDENTIFIERS

• Identifiers - In Python, an identifier is a name used to identify a variable, function,


class, module or other entities within a program.
Allowed Characters:
• Identifiers can consist of uppercase letters (A-Z), lowercase letters (a-z), digits (0-9)
and the underscore character (\_).
Starting Character:
• An identifier must begin with a letter (uppercase or lowercase) or an underscore
(\_). It cannot start with a digit.
Valid: my_variable, count, _internal_value.
Invalid: 1st_number, 7days.
No Special Characters
Identifiers cannot contain special characters such as !, @, #, %, $ etc.
Valid: user_name, total_score.
Invalid: user@name, product#id
Case Sensitivity
Python identifiers are case-sensitive. This means myVar and myvar are treated as two
distinct identifiers.
No Reserved Keywords
Python's reserved keywords (e.g: if, else, for, while, True, False, none) cannot be used as
identifiers.
Valid: loop_count, is_active
Invalid: for, True
KEYWORDS

Keywords: Keywords in Python are predefined, reserved words that hold special
meaning and serve specific purposes within the language's syntax.
They cannot be used as identifiers (e.g., variable names,
function names, class names) because they are integral to the structure and functionality
of Python.
Key characteristics of Python keywords:
Reserved: They are reserved by the Python interpreter and have a fixed meaning.
Special Purpose: Each keyword performs a specific action or defines a particular
structure in the code.
Case-sensitive: Python keywords are case-sensitive. Example – True is a keyword but
true is not.
Cannot be used as identifiers: You cannot use keywords as names for variables, functions,
classes, or any other user-defined identifiers.
Examples of Python keywords:
1. Control Flow: if, else, for, while, break, continue, pass etc.
2. Function and Class Definition: def, class, lamda.
3. Module and Package Handling: import, from, as.
4. Boolean Values: True, False, None.
5. Error Handling: try, except, finally, raise, assert.
6. Variable Scope: global, nonlocal.
7. Other: and, or, not, in, is, with, yield, del.
You can obtain a list of all current Python keywords using the keyword module:
import keyword
print([Link])
STATEMENT AND EXPRESSIONS

Statements: A statement is an instruction that the Python interpreter can execute to perform
an action. Statements control the flow of a program or perform operations that modify the
program's state.
Example:
1. Assignment statements: x = 10 (assigns the value 10 to the variable x).
2. Conditional statements: if condition:…….else:……. (controls execution based on a
condition).
3. Looping statements: for item in list: …. or while condition:….(repeatedly executes a
block of code).
4. Function definitions: def my_function(): . . . . . (defines a new function).
5. Import statements: import math (imports a module).
Expression: An expression is a combination of values, variables, operators, and function
calls that the Python interpreter can evaluate to produce a single value. Expressions are
typically used to calculate or derive data.
Example:
1) 10 + 5 (evaluates to 15)
2) X * Y (evaluates to the product of x and y)
3) len (“hello”) (evaluates to 5)
4) True and False (evaluates to False)

❑ Statements and Expressions is fundamental to understanding how code executes.


VARIABLES

Variables: A variable is essentially a name that is assigned to a value. They are used to
store data that can be referenced and manipulated during program execution.
In Python, variables do not require explicit declaration of type. The type of
the variable is inferred based on the value assigned. They allow us to store and reuse
values in our program.
1. Explicit Declaration: It means specifying the data type of a variable when it is declared.
2. Inferred Variable: Inferred variable is also known as implicitly typed variables, whose
data type is automatically determined by the compiler based on the value assigned to
them.
Ex: x=5 # Variable 'x' stores the integer value 5
name = "Samantha" # Variable 'name' stores the string "Samantha"
print(x)
print(name)
RULES FOR NAMING VARIABLES

To use variables effectively, we must follow Python’s naming rules:


1. Variable names can only contain letters, digits and underscores (_).
2. A variable name cannot start with a digit.
3. Variable names are case-sensitive (myVar and myvar are different).
4. Avoid using Python keywords (e.g: if, else, for) as a variable names.
Ex: age = 21
_color = “lilac”
total_score = 90
OPERATOR

Operators are generally used to perform operations on values and variables. They consist
of common symbols used in both arithmetic and logical computations.
Python divides the operators in the following groups:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators
1. Arithmetic Operators: Arithmetic operators are used with numeric values to perform common
mathematical operations.

➢ Modulo - returns the remainder of a division. Ex: x = 10 % 3


Output: 1 (because 10 divided by 3 is 3 with a remainder of 1).
➢ Exponentiation - raises a number to a power. Ex: result = 2 ** 3 # This calculates 2 raised to
the power of 3 (2 * 2 * 2).
➢ Floor Division - returns the integer part of the quotient. Ex: print(7 // 2) # Output: 3 (7 / 2 =
3.5, rounded down to 3).
2. Assignment Operators: In Python, assignment operators are used to assign values to
variables. The most fundamental assignment operator is the equal sign (=).
Ex: x = 10, # Assigns the value 10 to the variable x.
1. = (Assignment): This operator assigns the value of the right-hand operand to the left-hand
operand (a variable).
2. += (Addition Assignment): Adds the right operand to the left operand and assigns the result
to the left operand.
x += 3, (Equivalent to x = x + 3);
3. Comparison operators: Python's comparison operators are used to compare two values and
return a Boolean result True / False. These operators are fundamental for controlling program flow
through conditional statements and loops.

Ex: Equal to (==): Checks if two values are equal.


4. Logical operators: Python logical operators are used to combine conditional statements,
allowing you to perform operations based on multiple conditions. Python includes three logical
operators: and, or, and not.

Ex:
5. Identity Operators: In Python, identity operators are used to determine if two variables
refer to the exact same object in memory or not.

Ex: a = [1, 2, 3]
b=a (b now refers to the same list object as a)
c = [1, 2, 3] (c is a new list object with the same values)
print(a is b) Output: True (a and b are the same object)
print(a is c) Output: False (a and c are different objects, even if values are identical)
6. Membership operators: Python's membership operators are used to test for the presence of a
value within a sequence. These operators return a Boolean value (True or False) based on the result
of the membership test. The two membership operators in Python are:

Ex: ‘apple’ in [‘banana’, ‘apple’, ‘orange’] would return True.


‘apple’ not in [‘banana’, ‘grape’, ‘orange’] would return True.
7. Bitwise operators: Python bitwise operators manipulate the individual bits of integers. These
operators treat integers as sequences of binary digits (0s and 1s) and perform operations
directly on these bits. The result of a bitwise operation is returned in decimal format.
The main bitwise operators in Python are:
a) AND (&): Returns 1 if both corresponding bits are 1; otherwise, it returns 0.
Ex: result = 5 & 3
5 (binary 101) & 3 (binary 011)
apply and operation = 1 (binary 001)
print(result)
b) OR (|): Returns 1 if at least one of the corresponding bits is 1; otherwise, it returns 0.
Ex: result = 5 | 3
5 (binary 101) | 3 (binary 011)
apply or operation = 7 (binary 111)
print(result)
c) XOR (^): Returns 1 if the corresponding bits are different; otherwise, it returns 0.
Ex: result = 5 ^ 3
5 (binary 101) ^ 3 (binary 011)
apply XOR operation = 6 (binary 110)
print(result)
d) NOT (~): Inverts all the bits of an integer. This is a unary operator.
Ex: result = ~5 (binary 0...0101)
print(result) # Output will be (-6) due to two's complement representation
e) Left Shift (<<): Shifts the bits of an integer to the left by a specified number of positions,
filling the vacated positions with zeros. This is equivalent to multiplying by powers of 2.
Ex: result = 5 << 1
Shifts bits of 5 (binary 101) one position left = 10 (binary 1010)
print(result)
f) Right Shift (>>): Shifts the bits of an integer to the right by a specified number of
positions. For positive numbers, it fills the vacated positions with zeros. This is equivalent to
integer division by powers of 2.
Ex: result = 5 >> 1
Shifts bits of 5 (binary 101) one position right = 2 (binary 010)
print(result)
PRECEDENCE AND ASSOCIATIVITY

In Python, operator precedence and associativity determine the order in which operations are
performed within an expression.
1. Operator Precedence: This is used in an expression with more than one operator with different
precedence to determine which operation to perform first. When multiple operators are present
in an expression, the ones with higher precedence are evaluated first. In the case of operators
with the same precedence, their associativity comes into play.
Ex: multiplication (*) and division (/) have higher precedence than addition (+) and
subtraction (-).
Expression: 2 + 3 * 4
First multiply 3 * 4 = 12 then add 2.
12 + 2 = 14
❑Parentheses () can be used to override the default precedence, forcing specific operations to be
evaluated first.
2. Associativity: If an expression contains two or more operators with the same precedence, then
Operator Associativity is used to determine. It can either be Left to Right or from Right to Left.
a) Left to Right: These operators are following left to right operations ( +, -, *, /, //, % ) and
comparison operators.
Ex: 10 – 5 + 3
The subtraction 10 – 5 performed first, then the addition 5 + 3.
b) Right to Left: The exponentiation operator (**) is a notable exception, exhibiting right-to-
left associativity. This means that in an expression like (2 ** 3 ** 2) the rightmost exponentiation
3 ** 2 is evaluated first (yielding 9) and then 2 ** 9 (means power of 2) is calculated.
3. Non-associative Operators: In Python, most operators have associativity, which means they are
evaluated from left to right or right to left. However, there are a few operators that are non-
associative, meaning they cannot be chained together.
Ex: a = 5, b = 10, c = 15
a = b = (a < b) += (b < c) after run – invalid syntax.
DATA TYPE

❑ What is Data?
Data refers to a raw facts. That can be processed and analyzed to extract meaningful
information. It can take various forms like numbers, text, images, or sounds and is often
stored electronically.
❑ Categories of Data
a) Structured Data: This type of data is organized data into a specific format, making it easy to
search, analyze, and process.
b) Unstructured Data: Unstructured data does not conform to a specific structure or format.
❑ Type of Data?
Data can be broadly categorized into qualitative and quantitative data. Qualitative data
describes characteristics or qualities, while quantitative data represents numerical values.
Types of Data in Statistics:
1. Qualitative Data (Categorical Data) : Qualitative data describes characteristics or
qualities. There are two types.
a) Nominal Data: This type of data represents categories without any inherent order
or ranking.
Ex: Colors (red, blue, green), Types of fruit (apple, banana, orange).
b) Ordinal Data: This type of data represents categories with a meaningful order or
ranking.
Ex: Educational levels (high school, bachelor's, master’s)
Customer satisfaction ratings (very dissatisfied, dissatisfied, neutral, satisfied,
very satisfied).
2. Quantitative Data (Numerical Data): quantitative data represents numerical values.
a) Discrete Data: This type of data can be counted and has distinct, separate values.
Ex: Number of students in a class,
Number of cars in a parking lot.
b) Continuous Data: This type of data can take on any value within a range and is often
obtained through measurement.
Ex: Height, Weight, Temperature.
PYTHON DATA TYPES

Python Data types are the classification of data items. It represents the kind of value that
tells what operations can be performed on a particular data.
Python offers several built-in data types to store and manipulate
different kinds of data. These include:
1. Numeric Data Type: The numeric data type in Python represents the data that has a
numeric value. A numeric value can be an integer, a floating number, or even a complex
number.
a) Integers - This value is represented by int class. It contains positive or negative whole
numbers (without fractions or decimals). In Python, there is no limit to how long an integer
value can be.
b) Float - This value is represented by the float class. It is a real number with a floating-
point representation. It is specified by a decimal point.
c) Complex Numbers - A complex number is represented by a complex class. It is
specified as (real part) + (imaginary part)j . Ex: 2+3j.
Program: Output:
2. Sequence Data Types: In Python, sequences are ordered collections that can hold
multiple values, which may be of the same or different data types. They provide a
structured and efficient way to store and manage data. Python offers several built-in
sequence data types, including:
a) String Data Type: Python strings are array of bytes representing sequences
of characters that store Unicode characters. Since Python does not have a dedicated
character data type, a single character is simply treated as a string of length one,
represented by the str class. Strings can be created using single (‘ ’), double (“ “), or
triple (“ “ “ “ “ “), quotes. Individual characters within a string can be accessed
through indexing.
Ex: s = ‘welcome to GEC Sheikhpura’ output: welcome to GEC Sheikhpura
print(s) <class ‘str’>
# Check data type e
print(type(s)) l Array starting from
# access string with index zero so S1 = e
print([s1])
print([s2])
b) List Data Type: Lists in Python are similar to arrays in other programming languages,
functioning as ordered collections of data. They are highly flexible, as elements within a list
can be of different data types. Lists in Python can be created by just placing the sequence
inside the square brackets [].
Ex: Program – Output:
# Empty list
a = [] [1, 2, 3]
# list with int values
a = [1, 2, 3] [‘GEC’, ‘Engg’, ‘College’, 4, 5]
print(a)
# list with mixed int and string
b = ["GEC", “Engg", “College", 4, 5]
print(b)
c) Tuple Data Type: Tuple (that can contain elements) is just like a list and also a ordered
collection of python object. The only difference between a tuple or a list is that tuples are
immutable (stable). Tuples cannot be modified after it is created but list can be.
Creating a Tuple in Python: In Python, tuples are sequences of values separated by commas.
Parentheses may or may not be used to group the values. Tuples can hold any amount of data
and support elements of various types like numbers, strings, or lists.
Program: # initiate empty tuple
tup1 = ()
tup2 = (‘Gec', ‘Engg’)
print("\nTuple with the use of String: ", tup2)

Output: Tuple with the use of String: (‘Gec', ‘Engg’)


3. Boolean Data Type: Represent truth value, either True and False. These values are
fundamental for logical operations and control flow in programming.
Ex: When you compare two values, the expression is evaluated and Python returns the
Boolean answer.
Case 1 print(10 > 9) True
Case 2 print(10 == 9) False
Case 3 print(10 < 9) False
➢ Key characteristics of the Boolean data type in Python:
The only two possible values are True and False. True behaves like 1 and False like 0 in
arithmetic contexts.
a) False equivalent: None, 0 (for any numeric type), empty strings (“ “) and empty
collections (lists [ ], tuple ( ), dictionaries { }, sets set( )).
b) True equivalent: Any non-zero numeric value, non-empty strings, and non-empty
collections.
➢ bool() Function: The built-in bool() function can be used to explicitly convert any value to
its Boolean equivalent.
print(bool("Hello")) # Output: True
print(bool(0)) # Output: False
print(bool([])) # Output: False
➢ Usage: Booleans are extensively used in:
1. Conditional statements: if, else, elif (stands for "else if").
2. Loops: a) while loops and b) for controlling flow within ‘for’ loops using break and
continue.
3. Logical Operations: and, or, not.
4. Set Data Type: A set in Python represents an un-ordered, mutable collection of unique
elements that supports iteration. While it can store heterogeneous data types, the arrangement
of elements within a set remains non-deterministic and does not maintain insertion order.
a) Unordered: Elements in a set do not have a defined order, and their position can
change. Indexing or slicing operations are not supported.
b) Unique elements: Sets automatically handle duplicate elements, ensuring that each
element in a set appears only once.
c) Mutable: Sets themselves are mutable, meaning you can add or remove elements after
creation using methods like add ( ), remove ( ), discard ( ) etc.
➢ Creating a Set: Sets can be created using curly braces { } with comma-separated
elements, or by using the set ( ) constructor with an inerrable (like a list or tuple).
Program:
# Creating a set using curly braces
my_set = {1, 2, 3, 4, 5}
# Creating a set from a list
another_set = set([10, 20, 30, 10] # Duplicates are automatically removed
print(another_set) # Output: {10, 20, 30}
Benefits: 1. Removing duplicate elements from a sequence.
2. Performing membership tests efficiently (quickly check if an element exists
within the set).
3. Implementing mathematical set operations such as union, intersection,
difference and symmetric difference.
INDENTATION

Indentation refers to the leading whitespace (spaces or tabs) at the beginning of a line of
code. Many popular languages such as C, and Java uses braces ({ }) to define a block of
code, and Python uses indentation. ‘indentation’ is a crucial part of Python's syntax, not
just a matter of style.
Ex: 1. if 5 > 2:
print("Five is greater than two!")
Output: Five is greater than two!
2. if 5 > 2:
print("Five is greater than two!")
Output: File "demo_indentation_test.py", line 2
print("Five is greater than two!")
^
IndentationError: expected an indented block
Example 2: The number of spaces is up to you as a programmer, but it has to be at least one.
You have to use the same number of spaces in the same block of code, otherwise Python will
give you an error.
1. if 5 > 2:
print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!")
Output: The number of spaces is up to you as a programmer, but it has to be at least one.
Five is greater than two!
Five is greater than two!
2. if 5 > 2:
print("Five is greater than two!")
print("Five is greater than two!")
Output: File "demo_indentation_test.py", line 2
print("Five is greater than two!")
^
IndentationError: expected an indented block
COMMENTS

Comments in Python are the lines in the code that are ignored by the interpreter during the
execution of the program. Comments starts with a # and Python will ignore them:
Ex: #This is a comment
print("Hello, World!")
➢ Types of Comments in Python:
1. Single-line Comments:
a) These comments begin with the hash symbol ‘#’.
b) Anything following the # on the same line is considered a comment.
Ex: # This is a single-line comment
x = 10 # Assigning the value 10 to variable x
2. Multi-line Comments: Python does not have a dedicated multi-line comment syntax.
However, there are different ways through which we can write multiline comments like
(enclosed in triple quotes, either (‘ ‘ ‘ , “ “ “ and multiple hashtags (#)) can be used to
achieve the effect of multi-line comments.
Ex: #This is a comment
#written in Multiline comments
#more than just one line
print("Hello, World!")
➢ Python will ignore string literals that are not assigned to a variable, you can add a
multiline string (triple quotes) in your code and place your comment inside it.
Ex: """
This is a comment
written in
more than just one line
"""
print("Hello, World!")
Purpose of Comments:
1. To clarify the logic of code sections.
2. To make code easier to understand for others and your self in future.
3. To temporarily disable lines of code without deleting them.
READING INPUT AND PRINT OUTPUT

In Python, the input ( ) function is utilized to read input from the user and the print ( )
function is used to display output to the console.
Ex: name = input("Enter your name: ")
print("Hello, “, name)
In the above example,
1. input(“Enter your name:”) displays the message "Enter your name: " to the user and
waits for them to type something and press Enter.
2. The value entered by the user is stored in the name variable.
3. By default, input() returns a string. If numerical input is required, type conversion
functions like int() or float() can be used.
➢ print() function: This function allows us to display text, variables and expressions
on the console.
Ex: print("Hello, World!")
"Hello, World!" is a string literal enclosed within double quotes. When this code runs,
it prints the message Hello, World!.
➢ Printing Variables: We can use the print() function to print single and multiple
variables by separating them with commas.
Ex: # Single variable
s = "Bob"
print(s)
# Multiple Variables
s = "Alice"
age = 25
city = "New York"
print(s, age, city)
TYPE CONVERSION

The process of changing the data type of a value from one type to another. This can be done
either automatically by the Python interpreter (implicit conversion) or explicitly by the
programmer using built-in functions (explicit conversion or type casting). Python prevents
Implicit Type Conversion from losing data.
a) Implicit Type Conversion: Python interpreter automatically converts one data type to
another without any user involvement.
Ex: x = 10
print("x is of type:", type(x))
y = 10.6
print("y is of type:", type(y))
z=x+y
print(z)
print("z is of type:", type(z))
one variable x is of integer type while the other variable y is of float type. the float value not
being converted into an integer instead is due to type promotion that allows performing
operations by converting data into a wider-sized data type without any loss of information.
b) Explicit Type Conversion: The data type is manually changed by the user as per their
requirement. With explicit type conversion, there is a risk of data loss since we are forcing
an expression to be changed in some specific data type. Various forms of explicit type
conversion are explained below:
1) int () - Converts to an integer.
2) float () - Converts to a floating-point number.
3) str () - Converts to a string.
4) list () - Converts to a list.
5) tuple () - Converts to a tuple.
6) set () - Converts to a set.
7) dict () - Converts to a dictionary (from sequences of key-value pairs).
8) ord () - Convert a character to an integer.
9) hex () - convert an integer to a hexadecimal string.
Ex: # initializing string
s = "10010"
# printing string converting to int base 2
c = int(s,2)
print ("After converting to integer base 2 : ", end="")
print (c)
# printing string converting to float
e = float(s)
print ("After converting to float : ", end="")
print (e)
TYPE() FUNCTION AND ITS OPERATORS

The type() function is mostly used for debugging purposes. There are two type of
arguments can be passed to type() function:
a) single argument: type(object) - If a single argument type(obj) is passed, it returns the
type of the given object.
Ex: We are printing the type of variable x. We will determine the type of an object in
Python.
x = 10
print(type(x))
b) With three arguments: If three argument types (object, bases, dict) are passed, it returns
a new type object.
1) name/object: A string representing the name of the new class.
2) bases: A tuple of base classes from which the new class inherits.
3) dict: A dictionary containing the namespace of the new class.
FINDING THE TYPE OF A PYTHON OBJECT

Here we are checking the object type using the type() function in Python: -
Program: a = ("Gec", “Engg")
b = [" Gec", “Engg "]
c = {" Gec", “Engg ":3}
d = "Hello World"
e = 10.23
f = 11.22
print(type(a))
print(type(b))
print(type(c))
print(type(d))
print(type(e))
print(type(f))
DYNAMIC AND STRONGLY TYPE LANGUAGE

Python is considered a dynamically typed and strongly typed language. Here's what
each term means in the context of Python:
1) Dynamically type: You don’t need to declare the type of a variable when you create it.
Python automatically determines the type at runtime.
Ex: x = 10 # x is an integer
x = "hello" # now x is a string
The type of a variable can change as the program runs. This gives flexibility but can also
lead to runtime errors if not managed carefully.
2) Strongly Typed: Python does not allow implicit type conversion (or coercion) between
conflicting types.
Ex: x = "10"
y=5
Print(x + y) # Error: can't concatenate str and int
You must explicitly convert types if needed. No implicit type conversion used.
Thank You

You might also like