0% found this document useful (0 votes)
4 views19 pages

Python

The document provides an introduction to Python programming, detailing its features, syntax basics, installation steps, and data types. It covers variable assignments, immutable variables, and numerical types, emphasizing Python's ease of use and dynamic typing. Additionally, it includes examples and explanations of various data types such as integers, strings, and lists.

Uploaded by

shrejallama35
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)
4 views19 pages

Python

The document provides an introduction to Python programming, detailing its features, syntax basics, installation steps, and data types. It covers variable assignments, immutable variables, and numerical types, emphasizing Python's ease of use and dynamic typing. Additionally, it includes examples and explanations of various data types such as integers, strings, and lists.

Uploaded by

shrejallama35
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

RSR RUNGTA COLLEGE OF ENGINEERING AND TECHNOLOGY

Rungta Knowledge City ,Kohka – Kurud ,Bhilai (C.G)-490024


Department of Computer Science & Engineering
BCA – BCA-3
Subject: Python Programming Subject code: BCA-15T

Unit-1
Introduction to Python
What is Python?
Python is a high-level, interpreted, and general-purpose programming language created by Guido van
Rossum and first released in 1991. It emphasizes code readability and simplicity, allowing
programmers to express concepts in fewer lines of code than many other languages.
Key Features of Python
1. Easy to Learn and Use
Python has a clean and simple syntax that closely resembles English, making it beginner-
friendly.
2. Interpreted Language
Python code is executed line-by-line by the Python interpreter, which makes debugging
easier.
3. Dynamically Typed
You don't need to declare variable types explicitly; Python figures it out at runtime.
4. High-level Language
Python abstracts away most of the complex details of the computer, like memory
management.
5. Cross-Platform
Python runs on many operating systems, including Windows, macOS, Linux, and more.
6. Extensive Standard Library
Python comes with a vast collection of modules and packages for tasks like file I/O,
networking, regular expressions, web services, and more.
7. Object-Oriented and Procedural Programming
Python supports multiple programming paradigms, including object-oriented, procedural, and
functional programming.
8. Open Source
Python is freely available and supported by a large global community.
9. Embeddable and Extensible
You can embed Python into C/C++ programs or extend Python with C/C++ for performance-
critical tasks.
10. Supports GUI Programming
Python can create graphical user interfaces with toolkits like Tkinter, PyQt, and others.

Python Syntax Basics


• Variables: No need to declare type; just assign a value.
x=5
name = "Abhishek"
RSR RUNGTA COLLEGE OF ENGINEERING AND TECHNOLOGY
Rungta Knowledge City ,Kohka – Kurud ,Bhilai (C.G)-490024
Department of Computer Science & Engineering
BCA – BCA-3
Subject: Python Programming Subject code: BCA-15T

• Comments: Use # for single-line comments.


# This is a comment
• Indentation: Python uses indentation (usually 4 spaces) to define code blocks instead of
braces {}.
• Print Statement:
print("Hello, World!")
• Data Types: Common built-in types include:
o Numbers: int, float, complex
o Text: str
o Boolean: True / False
o Collections: list, tuple, set, dict
Simple Python Program Example
# Program to greet the user
name = input("Enter your name: ") # Taking input
print("Hello, " + name + "! Welcome to Python programming.")

How to Install Python


Step 1: Download Python
1. Open your web browser.
2. Go to the official Python website: [Link]
3. You will see a big button that says “Download Python X.X.X” (where X.X.X is the latest
version number, e.g., 3.11.5). Click that button to download the installer.
Step 2: Run the Installer
1. Once the installer file is downloaded, open/run it.
2. Important: Before clicking “Install Now,” make sure to check the box that says:
Add Python X.X to PATH
This option adds Python to your system’s environment variables so you can run it from the command
line easily.
3. Click on Install Now.
Step 3: Wait for the Installation to Complete
• The installer will copy files and install Python on your system.
• Once it finishes, you will see a “Setup was successful” message.
RSR RUNGTA COLLEGE OF ENGINEERING AND TECHNOLOGY
Rungta Knowledge City ,Kohka – Kurud ,Bhilai (C.G)-490024
Department of Computer Science & Engineering
BCA – BCA-3
Subject: Python Programming Subject code: BCA-15T

• You can click Close to exit the installer.


Step 4: Verify the Installation
To make sure Python is installed correctly:
1. Open your Command Prompt (Windows) or Terminal (macOS/Linux).
2. Type:
python --version
or sometimes
python3 --version
3. You should see the installed Python version number printed, e.g.,
Python 3.11.5

Step 5: Run Python


• You can start Python in the terminal by typing:
python
• This will open the Python interactive shell where you can type Python commands directly.
• To exit, type:
exit()
Optional: Install an IDE or Code Editor
• Although you can write Python code in any text editor, using an IDE or specialized code
editor makes programming easier.
• Some popular options:
o PyCharm (free community edition available)
o Visual Studio Code (VS Code) with Python extension
o IDLE (comes bundled with Python)

Python basic syntax, interactive shell, editing, saving, and running scripts
1. Python Basic Syntax
• Case-sensitive: Python distinguishes between uppercase and lowercase letters. For example,
Variable and variable are different.
• Indentation matters: Python uses indentation (spaces or tabs) to define blocks of code
instead of braces {}.
• Statements: Each line is a statement. Use a newline to separate statements.
RSR RUNGTA COLLEGE OF ENGINEERING AND TECHNOLOGY
Rungta Knowledge City ,Kohka – Kurud ,Bhilai (C.G)-490024
Department of Computer Science & Engineering
BCA – BCA-3
Subject: Python Programming Subject code: BCA-15T

• Comments: Use # for single-line comments.


Example:
# This is a comment
x=5 # variable assignment
if x > 0:
print("Positive number")
else:
print("Non-positive number")

2. Python Interactive Shell (REPL)


• Python provides an interactive shell (REPL - Read Evaluate Print Loop) where you can type
Python commands and see immediate results.
• To open the interactive shell:
o Open your terminal or command prompt.
o Type python or python3 and press Enter.
• You will see the Python prompt >>>.
• Example session:
>>> 2 + 3
5
>>> print("Hello!")
Hello!
>>> x = 10
>>> x * 2
20
• To exit the shell, type exit() or press Ctrl + D (Linux/macOS) or Ctrl + Z then Enter
(Windows).

3. Editing, Saving, and Running a Python Script


Editing and Saving
• You can write Python code in any text editor:
o Simple editors like Notepad (Windows), TextEdit (macOS in plain text mode), or
gedit (Linux).
RSR RUNGTA COLLEGE OF ENGINEERING AND TECHNOLOGY
Rungta Knowledge City ,Kohka – Kurud ,Bhilai (C.G)-490024
Department of Computer Science & Engineering
BCA – BCA-3
Subject: Python Programming Subject code: BCA-15T

o Advanced editors/IDEs like VS Code, PyCharm, Sublime Text, or Atom.


• Save the file with a .py extension, for example: [Link].
Example Python script ([Link]):
# [Link]
print("Hello, Python!")
x = 10
print("x squared is", x * x)
Running a Python Script
• Open your terminal or command prompt.
• Navigate to the folder where the .py file is saved using the cd command.
• Run the script by typing:
python [Link]
or, if your system requires,

python3 [Link]
• The output will display in the terminal, for example:
Hello, Python!
x squared is 100

Understanding Data Types in Python


What is a Data Type?
A data type defines what kind of value a variable holds and what operations can be performed on it.
It helps the computer understand how to store and manipulate the data.
Python has several built-in data types, and because it is a dynamically typed language, you don’t need
to explicitly declare the data type of a variable; Python figures it out automatically.

1. Numeric Data Types


These are used to store numbers.
a) int (Integer)
• Represents whole numbers without a decimal point.
• Can be positive, negative, or zero.
Example:
RSR RUNGTA COLLEGE OF ENGINEERING AND TECHNOLOGY
Rungta Knowledge City ,Kohka – Kurud ,Bhilai (C.G)-490024
Department of Computer Science & Engineering
BCA – BCA-3
Subject: Python Programming Subject code: BCA-15T

x = 10
y = -5
z=0
b) float (Floating Point)
• Represents real numbers (numbers with decimal points).
• Can also represent scientific notation.
Example:
pi = 3.14159
temperature = -7.5
large_number = 1.5e6 # equals 1,500,000.0
c) complex
• Represents complex numbers with real and imaginary parts.
• Written as a + bj, where a is real part and b is imaginary part.
Example:
z = 2 + 3j
print([Link]) # 2.0
print([Link]) # 3.0

2. Text Type
str (String)
• Used to store sequences of characters (text).
• Strings are enclosed in single ('...'), double ("..."), or triple quotes ('''...''' or """...""").
• Strings are immutable (cannot be changed after creation).
Example:
name = "Abhishek"
greeting = 'Hello, World!'
multiline = """This
is a
multiline string."""
RSR RUNGTA COLLEGE OF ENGINEERING AND TECHNOLOGY
Rungta Knowledge City ,Kohka – Kurud ,Bhilai (C.G)-490024
Department of Computer Science & Engineering
BCA – BCA-3
Subject: Python Programming Subject code: BCA-15T

3. Boolean Type
bool
• Represents truth values: True or False.
• Often used in conditions and control flow.
Example:
is_active = True
has_permission = False

4. Sequence Data Types


These hold collections of items.
a) list
• Ordered, changeable (mutable), allows duplicate elements.
• Defined with square brackets [ ].
Example:
fruits = ['apple', 'banana', 'cherry']
fruits[0] = 'orange' # lists are mutable
b) tuple
• Ordered, but immutable (cannot be changed after creation).
• Defined with parentheses ( ).
Example:
coordinates = (10.0, 20.0)
# coordinates[0] = 5 # This will cause an error
c) range
• Represents an immutable sequence of numbers, commonly used in loops.
Example:
for i in range(5):
print(i) # prints 0 to 4
RSR RUNGTA COLLEGE OF ENGINEERING AND TECHNOLOGY
Rungta Knowledge City ,Kohka – Kurud ,Bhilai (C.G)-490024
Department of Computer Science & Engineering
BCA – BCA-3
Subject: Python Programming Subject code: BCA-15T

5. Set Types
set
• Unordered collection of unique elements.
• Mutable, but does not allow duplicates.
Example:
unique_numbers = {1, 2, 3, 3, 4} # duplicates removed, so set is {1, 2, 3, 4}
frozenset
• Immutable version of set.

6. Mapping Type
dict (Dictionary)
• Collection of key-value pairs.
• Keys must be unique and immutable types (like strings, numbers, tuples).
• Values can be of any type.
• Defined using curly braces {}.
Example:
person = {
"name": "Abhishek",
"age": 25,
"city": "Delhi"
}
print(person["name"]) # Output: Abhishek

7. None Type
NoneType
• Represents the absence of a value or a null value.
• There is only one None object in Python.
Example:
result = None
if result is None:
print("No result found.")
RSR RUNGTA COLLEGE OF ENGINEERING AND TECHNOLOGY
Rungta Knowledge City ,Kohka – Kurud ,Bhilai (C.G)-490024
Department of Computer Science & Engineering
BCA – BCA-3
Subject: Python Programming Subject code: BCA-15T

How to Check Data Type?


You can check the type of any variable using the built-in type() function.
x = 10
print(type(x)) # <class 'int'>
name = "Abhishek"
print(type(name)) # <class 'str'>
flag = True
print(type(flag)) # <class 'bool'>

Summary Table

Data Type Description Example

int Integer numbers (no decimals) x=5

float Floating-point numbers (decimals) pi = 3.14

complex Complex numbers z = 1 + 2j

str Text/String name = "Hello"

bool Boolean (True/False) flag = True

list Ordered, mutable collection [1, 2, 3]

tuple Ordered, immutable collection (1, 2, 3)

set Unordered, unique collection {1, 2, 3}

dict Key-value pairs mapping {"a": 1, "b": 2}

NoneType Null/None value None

Variables, Assignments, Immutable variables, and Numerical types


1. Variables and Assignments in Python
What is a Variable?
A variable is like a named container that stores data values. In Python, variables are used to hold
information which you can use and manipulate throughout your program.
How to Assign a Variable?
You assign a value to a variable using the assignment operator =.
Example:
RSR RUNGTA COLLEGE OF ENGINEERING AND TECHNOLOGY
Rungta Knowledge City ,Kohka – Kurud ,Bhilai (C.G)-490024
Department of Computer Science & Engineering
BCA – BCA-3
Subject: Python Programming Subject code: BCA-15T

x = 10
name = "Alice"
• Here, x is a variable holding the integer value 10.
• name holds the string "Alice".
Dynamic Typing
• Python is dynamically typed, meaning you don't need to declare the data type of a variable
explicitly.
• The type is inferred from the value assigned.
• You can also reassign variables to different types:
x=5 # x is int
x = "five" # now x is a string

2. Immutable Variables
What Does Immutable Mean?
• Immutable means cannot be changed after creation.
• Some data types in Python are immutable, meaning once created, their value cannot be
altered.
• For example: strings, integers, floats, tuples are immutable.
Immutable Variables Explained
When you assign a variable to an immutable value, if you try to change that value, Python actually
creates a new object instead of modifying the existing one.
Example with strings:
name = "Alice"
print(id(name)) # let's say prints 14025394876
name = name + " Smith"
print(id(name)) # different id, new string created
• The id() function shows the memory address.
• When " Smith" is concatenated, a new string object is created, and name now points to it.
Mutable vs Immutable Summary

Mutable Types Immutable Types

list, dict, set int, float, str, tuple

• Mutable objects can be changed in-place (without creating new object).


RSR RUNGTA COLLEGE OF ENGINEERING AND TECHNOLOGY
Rungta Knowledge City ,Kohka – Kurud ,Bhilai (C.G)-490024
Department of Computer Science & Engineering
BCA – BCA-3
Subject: Python Programming Subject code: BCA-15T

• Immutable objects cannot be changed after creation.

3. Numerical Types in Python


Python has several built-in numerical types:
a) int (Integer)
• Represents whole numbers without decimals.
• Integers can be positive, negative, or zero.
• Python integers can be arbitrarily large (limited by available memory).
Example:
a = 42
b = -10
b) float (Floating-point)
• Represents real numbers with decimal points.
• Supports fractional values and scientific notation.
• Internally stored as double-precision floating point (IEEE 754).
Example:
pi = 3.14159
temperature = -7.5
big_number = 1.5e6 # equals 1,500,000.0
c) complex (Complex Numbers)
• Represents numbers with real and imaginary parts.
• Written as a + bj, where a is real part and b is imaginary part (j denotes imaginary unit).
Example:
z = 2 + 3j
print([Link]) # 2.0
print([Link]) # 3.0

Important Notes About Numerical Types


• You can convert between types using functions like int(), float(), and complex().
x = 5.7
y = int(x) # y = 5 (decimal part truncated)
RSR RUNGTA COLLEGE OF ENGINEERING AND TECHNOLOGY
Rungta Knowledge City ,Kohka – Kurud ,Bhilai (C.G)-490024
Department of Computer Science & Engineering
BCA – BCA-3
Subject: Python Programming Subject code: BCA-15T

z = complex(y) # z = (5+0j)
• Arithmetic operations work naturally between these types, but mixing complex numbers with
floats or ints follows specific rules.

Summary Table

Concept Description Example

Variable Named container to store data x = 10

Assignment Using = to assign a value to a variable name = "Alice"

Immutable Data that cannot be changed after creation int, str, tuple

Mutable Data that can be changed in-place list, dict, set

Integer (int) Whole numbers without decimals 42, -10

Float (float) Numbers with decimal points 3.14, -7.5, 1.2e3

Complex (complex) Numbers with real and imaginary parts 2 + 3j

Operators
Operators are special symbols or keywords in Python that carry out operations on one or more
operands (values or variables). They are essential in programming to perform calculations,
comparisons, logical operations, and more.
1. Arithmetic Operators
Definition:
Arithmetic operators perform mathematical calculations like addition, subtraction, multiplication,
division, etc., on numerical values.

Operator Name Description Example Result

+ Addition Adds two operands 5+3 8

- Subtraction Subtracts right operand from left 5-3 2

* Multiplication Multiplies two operands 5*3 15

/ Division Divides left operand by right, returns float 5/2 2.5

// Floor Division Divides and returns the integer part only 5 // 2 2

% Modulus Returns remainder of division 5%2 1

** Exponentiation Raises left operand to power of right operand 5 ** 2 25


RSR RUNGTA COLLEGE OF ENGINEERING AND TECHNOLOGY
Rungta Knowledge City ,Kohka – Kurud ,Bhilai (C.G)-490024
Department of Computer Science & Engineering
BCA – BCA-3
Subject: Python Programming Subject code: BCA-15T

Example:
a = 10
b=3
print(a + b) # 13
print(a / b) # 3.3333...
print(a // b) # 3
print(a % b) # 1
print(a ** b) # 1000

2. Relational (Comparison) Operators


Definition:
Relational operators compare two values and return a Boolean value (True or False) depending on the
comparison result.

Operator Meaning Description Example Result

== Equal to True if both operands are equal 5 == 5 True

!= Not equal to True if operands are not equal 5 != 3 True

> Greater than True if left operand is greater 5>3 True

< Less than True if left operand is smaller 5<3 False

>= Greater than or equal to True if left operand is greater or equal 5 >= 5 True

<= Less than or equal to True if left operand is less or equal 5 <= 3 False

Example:
x = 10
y = 20
print(x == y) # False
print(x < y) # True
print(x >= 10) # True

3. Logical (Boolean) Operators


Definition:
Logical operators are used to combine multiple conditions and return a Boolean value.
RSR RUNGTA COLLEGE OF ENGINEERING AND TECHNOLOGY
Rungta Knowledge City ,Kohka – Kurud ,Bhilai (C.G)-490024
Department of Computer Science & Engineering
BCA – BCA-3
Subject: Python Programming Subject code: BCA-15T

Operator Name Description Example Result

and Logical AND Returns True if both conditions are True (5 > 3) and (4 < 6) True

or Logical OR Returns True if at least one condition is True (5 > 3) or (4 > 6) True

not Logical NOT Returns the inverse of the condition not(5 > 3) False

Example:
a=5
print(a > 0 and a < 10) # True
print(a < 0 or a > 10) # False
print(not(a == 5)) # False

4. Assignment Operators
Definition:
Assignment operators assign values to variables. They can also perform an operation and assign the
result in one step.

Operator Meaning Example Equivalent To

= Assign x=5 x=5

+= Add and assign x += 3 x=x+3

-= Subtract and assign x -= 2 x=x-2

*= Multiply and assign x *= 4 x=x*4

/= Divide and assign x /= 5 x=x/5

//= Floor divide and assign x //= 3 x = x // 3

%= Modulus and assign x %= 3 x=x%3

**= Exponentiate and assign x **= 2 x = x ** 2

Example:
x = 10
x += 5 # x = 15
x *= 2 # x = 30
print(x) # 30
RSR RUNGTA COLLEGE OF ENGINEERING AND TECHNOLOGY
Rungta Knowledge City ,Kohka – Kurud ,Bhilai (C.G)-490024
Department of Computer Science & Engineering
BCA – BCA-3
Subject: Python Programming Subject code: BCA-15T

5. Ternary Operator (Conditional Expression)


Definition:
Ternary operator allows you to write a simple if-else condition in a single line.
Syntax:
value_if_true if condition else value_if_false
Example:
age = 18
status = "Adult" if age >= 18 else "Minor"
print(status) # Output: Adult
• Here, if age >= 18 is True, status gets "Adult", else "Minor".
6. Bitwise Operators
Definition:
Bitwise operators work on binary representation of integers and perform operations bit-by-bit.

Operator Name Description Example Result

& Bitwise AND 1 if both bits are 1 5&3 1

` ` Bitwise OR 1 if either bit is 1 `5

^ Bitwise XOR 1 if bits are different 5^3 6

~ Bitwise NOT Inverts bits ~5 -6

<< Left Shift Shifts bits left, adds zeros right 5 << 1 10

>> Right Shift Shifts bits right 5 >> 1 2

Note: Bitwise operations work with integers only.


Example:
a = 5 # binary: 0101
b = 3 # binary: 0011
print(a & b) # 1 (0001)
print(a | b) # 7 (0111)
print(a ^ b) # 6 (0110)
print(~a) # -6 (two's complement)
print(a << 1) # 10 (1010)
print(a >> 1) # 2 (0010)
RSR RUNGTA COLLEGE OF ENGINEERING AND TECHNOLOGY
Rungta Knowledge City ,Kohka – Kurud ,Bhilai (C.G)-490024
Department of Computer Science & Engineering
BCA – BCA-3
Subject: Python Programming Subject code: BCA-15T

7. Increment and Decrement Operators


Explanation:
• Unlike some languages like C, Python does NOT have ++ or -- operators for incrementing
or decrementing variables.
• Instead, you use assignment operators with addition or subtraction:
x=5
x = x + 1 # Increment by 1
x += 1 # More concise increment
x=x-1 # Decrement by 1
x -= 1 # More concise decrement
Summary Table of Operators

Operator Type Examples Purpose/Use

Arithmetic +, -, *, /, % Math calculations

Relational ==, !=, >, <, >=, <= Compare values, returns Boolean

Logical and, or, not Combine Boolean conditions

Assignment =, +=, -=, *= Assign and update variable values

Ternary x if condition else y Inline if-else statement

Bitwise &, ` , ^, ~, <<, >>`

Increment/Decrement x += 1, x -= 1 Increase or decrease variable value

Expressions, Comments in a Program, and Understanding error messages


What is an Expression?
An expression is any combination of values, variables, operators, and function calls that Python can
evaluate to produce a result (a value).
• Expressions are the building blocks of a program’s logic.
• When Python evaluates an expression, it computes its value.
Examples of Expressions:
5+3 # Simple arithmetic expression, evaluates to 8
x = 10
x*2 # Uses variable x, evaluates to 20
len("hello") # Function call expression, evaluates to 5
RSR RUNGTA COLLEGE OF ENGINEERING AND TECHNOLOGY
Rungta Knowledge City ,Kohka – Kurud ,Bhilai (C.G)-490024
Department of Computer Science & Engineering
BCA – BCA-3
Subject: Python Programming Subject code: BCA-15T

Types of Expressions:
• Arithmetic expressions: Use arithmetic operators (+, -, *, /, etc.)
• Relational expressions: Use comparison operators (==, <, >, etc.) and result in Boolean
values (True or False).
• Logical expressions: Use logical operators (and, or, not).
• Function call expressions: Calling functions returns values (like len(), max(), etc.).
• Complex expressions: Can combine all above in one statement.
Why are expressions important?
• They form the logic and calculations inside programs.
• They can be part of statements like assignments, conditionals, loops.

What are Comments?


Comments are notes or explanations in the source code that are ignored by the Python interpreter.
They help humans understand what the code is doing.
Types of Comments in Python:
• Single-line comments: Start with # and continue till the end of the line.
Example:
# This is a single-line comment
x = 5 # This is an inline comment
• Multi-line comments: Python does not have a special multi-line comment syntax, but triple
quotes (''' or """) are often used to create multi-line strings that can serve as comments.
Example:
'''
This is a multi-line comment.
It can span multiple lines.
'''
or
"""
Another way to write
multi-line comments.
"""
(Note: Technically, these are multi-line strings, but when not assigned or used, they act as comments.)
RSR RUNGTA COLLEGE OF ENGINEERING AND TECHNOLOGY
Rungta Knowledge City ,Kohka – Kurud ,Bhilai (C.G)-490024
Department of Computer Science & Engineering
BCA – BCA-3
Subject: Python Programming Subject code: BCA-15T

Why use comments?


• To explain complex logic.
• To make code more readable.
• To temporarily disable parts of code during debugging.

Understanding Error Messages in Python


What are Error Messages?
When Python encounters a problem during the execution of your program, it stops and shows an
error message (also called an exception). This message helps you understand what went wrong.
Common Types of Errors:
1. Syntax Errors
• Occur when Python cannot parse your code because of incorrect syntax.
• Example: Missing a colon, unmatched parentheses, wrong indentation.
Example:
if x > 5 # Missing colon (:)
print("Hello")
Python error:
SyntaxError: invalid syntax
2. Runtime Errors
• Occur during program execution when Python detects an illegal operation.
• Examples: division by zero, accessing undefined variables, file not found.
Example:
print(10 / 0)
Python error:
ZeroDivisionError: division by zero
3. Name Errors
• Occur when you try to use a variable or function name that hasn’t been defined.
Example:
print(y)
Python error:
NameError: name 'y' is not defined
RSR RUNGTA COLLEGE OF ENGINEERING AND TECHNOLOGY
Rungta Knowledge City ,Kohka – Kurud ,Bhilai (C.G)-490024
Department of Computer Science & Engineering
BCA – BCA-3
Subject: Python Programming Subject code: BCA-15T

4. Type Errors
• Occur when an operation is applied to incompatible types.
Example:
print("5" + 3)
Python error:
TypeError: can only concatenate str (not "int") to str

How to Read Error Messages


Error messages usually have:
• Error type: The category of error (SyntaxError, TypeError, NameError, etc.)
• Description: Explains the cause of error.
• Traceback: The call stack showing where the error happened (line number, file name).
Tips for Debugging:
• Carefully read the error type and message.
• Look at the line number mentioned.
• Google the error message if you don’t understand it.
• Use print statements or debugging tools to trace values.
• Check for typos, missing punctuation, or wrong variable names.

Summary

Concept Description

Expression Combination of values/operators that produce a value

Comments Non-executable notes to explain code (# for single line)

Error Messages Feedback from Python when something goes wrong

You might also like