An Autonomous Institute
NEAR ITPB, CHANNASANDRA, BENGALURU – 560 067
Affiliated to VTU,Belagavi
Approved by AICTE, New Delhi
Recognized by UGC under 2(f) & 12(B)
Accredited by NBA & NAAC
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
INTRODUCTION TO PYTHON PROGRAMMING – MVJ22PCLK25B
~PREPARED BY DEEPTHI S S , ASSISTANT PROFESSOR - CSE
CHAPTER 1: PYTHON BASICS
First Python program:
# Script Begins
Statement 1
Statement 2
Statement 3
# Script Ends
1. Entering Expressions into the Interactive Shell
Python provides an interactive shell, also called the REPL (Read-Eval-Print Loop). It allows you to
type Python expressions and immediately see the results.
How to Open the Interactive Shell
1. Open Command Prompt (Windows) or Terminal (Mac/Linux).
2. Type:
python
or
python3
3. You will see the >>> prompt, which means Python is ready to take input.
The shell evaluates the expressions and prints the results.
Example:
2. The Integer, Floating-Point, and String Data Types
Python supports different types of data:
1. Integer (int)
• Whole numbers without decimals.
• Example: 10, -5, 1000
• Arithmetic operations work as expected:
Example:
2. Floating-Point (float)
• Numbers with decimals.
• Example: 3.14, -2.5, 100.0
• Division always returns a float
Example:
(even if the number has .0, it is still a float)
3. Strings (str)
• A sequence of characters enclosed in "" or ''.
• Example:
Checking Data Type
Use type() to check the type of a value:
>>> type(42)
<class 'int'>
>>> type(3.14)
<class 'float'>
>>> type("Hello")
<class 'str'>
3. String Concatenation and Replication
Python provides ways to combine and repeat strings.
1. String Concatenation (+ Operator)
• Joins two or more strings.
• Example:
>>> "Hello" + " World"
'Hello World'
• Note: Strings cannot be directly added to numbers.
>>> "Age: " + 25 # This will cause an error
Instead, convert numbers to strings using str():
>>> "Age: " + str(25) # Correct
'Age: 25'
2. String Replication (* Operator)
• Repeats a string multiple times.
• Example:
>>> "Python" * 3
'PythonPythonPython'
• It works only with strings and integers:
>>> "Hello" * 2.5 # This will cause an error
3. Storing Values in Variables
Variables allow us to store and reuse values.
Declaring Variables
• Assign values using the = operator.
• Example:
name = "Alice"
age = 25
pi = 3.14
Using Variables
• Variables can be used in expressions.
• Example:
>>> x = 10
>>> y = 20
>>> result = x + y
>>> print(result)
30
• Updating value of a variable:
>>> count = 5
>>> count = count + 2
>>> print(count)
7
Shortcut: Instead of count = count + 2, you can write:
>>> count += 2
Variable Naming Rules
Allowed:
• name
• first_name
• age
• _hidden_variable
Not Allowed:
• 2nd_name (Cannot start with a number)
• my-name (Hyphens are not allowed)
• class (Reserved keyword)
4. Your First Program
Steps to Write a Python Script
1. Open a text editor (Notepad, VS Code, PyCharm, etc.).
2. Write the following code:
print("Hello, World!")
3. Save the file as hello.py.
4. Open Command Prompt/Terminal and navigate to the folder where hello.py is saved.
5. Run the script:
python hello.py
output:
Hello, World!
5. Dissecting the Program
Let’s analyze this program:
name = input("Enter your name: ") # User enters name
print("Hello, " + name + "!") # Display greeting
Explanation
1. input("Enter your name: ")
o Takes user input.
o Always returns a string.
2. name = input(...)
o Stores the input in the variable name.
3. print("Hello, " + name + "!")
o Prints a greeting message.
Example Output
Enter your name: Alice
Hello, Alice!
CHAPTER 2 – FLOW CONTROL
1. Boolean Values
A Boolean value is a data type that has only two possible values:
• True
• False
These values are used in logical operations and control flow statements. In Python, Boolean
values are represented as keywords:
is_raining = True
is_sunny = False
Internally, Python treats True as 1 and False as 0. This means you can use them in
arithmetic operations:
print(True + True) # Output: 2 (1 + 1)
print(False + 5) # Output: 5 (0 + 5)
2. Comparison Operators
Comparison operators are used to compare values and return Boolean results (True or
False). Python provides the following comparison operators:
Operator Description Example
== Equal to 5 == 5 → True
!= Not equal to 5 != 3 → True
> Greater than 10 > 3 → True
< Less than 2 < 5 → True
>= Greater than or equal to 7 >= 7 → True
<= Less than or equal to 4 <= 8 → True
Example:
a = 10
b = 20
print(a > b) # Output: False
print(a != b) # Output: True
3. Boolean Operators
Boolean operators are used to combine Boolean values and expressions.
Operator Description Example
and Returns True if both conditions are True (5 > 3) and (10 > 2) →
True
or Returns True if at least one condition is (5 > 3) or (10 < 2) → True
True
not Reverses the Boolean value not (5 > 3) → False
Example:
x = True
y = False
print(x and y) # Output: False
print(x or y) # Output: True
print(not x) # Output: False
4. Mixing Boolean and Comparison Operators
You can combine comparison and Boolean operators in complex expressions.
Example:
age = 25
income = 50000
# Check if age is between 18 and 30 and income is above 40000
if (age >= 18 and age <= 30) and (income > 40000):
print("Eligible for the offer")
else:
print("Not eligible")
Another example:
a = 10
b = 5
c = 20
print((a > b) and (c > a)) # True, because both conditions are True
print((a < b) or (c < a)) # False, because both conditions are False
5. Elements of Flow Control
Flow control determines how a program executes its instructions based on conditions. The
key elements include:
1. Sequential Execution - Code runs from top to bottom.
2. Decision Making (Conditionals: if, elif, else) - Code runs based on conditions.
3. Loops (for, while) - Code runs repeatedly based on conditions.
4. Function Calls - Code executes when a function is invoked.
Example:
temperature = 30
if temperature > 25:
print("It's hot outside!") # This runs because the condition is True
6. Program Execution
A Python program is executed line by line, from top to bottom unless flow control statements
alter this order.
Key concepts:
• Interpreted Language: Python runs one statement at a time.
• Execution starts from the first non-indented line.
• Functions run only when called.
Example:
print("Start")
def greet():
print("Hello!")
greet() # Calls the function
print("End")
Output:
Start
Hello!
End
7. Flow Control Statements
Flow control statements decide the execution path of a program.
Conditional Statements
Used to make decisions.
x = 10
if x > 0:
print("Positive")
elif x < 0:
print("Negative")
else:
print("Zero")
Loops
Loops execute a block of code multiple times.
• while loop (Runs as long as the condition is True)
i = 1
while i <= 5:
print(i)
i += 1
• for loop (Iterates over a sequence)
for i in range(1, 6):
print(i)
• break Statement (Exits the loop early)
for i in range(5):
if i == 3:
break
print(i)
• continue Statement (Skips the current iteration)
for i in range(5):
if i == 3:
continue
print(i)
8. Importing Modules
Python provides built-in and third-party modules to extend functionality.
• Importing a module:
import math
print(math.sqrt(25)) # Output: 5.0
• Importing a specific function:
from math import sqrt
print(sqrt(25)) # Output: 5.0
• Importing with an alias:
import math as m
print(m.pi) # Output: 3.141592653589793
• Importing multiple modules:
import os, sys, random
9. Ending a Program Early with sys.exit()
Python allows terminating a program using sys.exit(). This is useful when an error occurs
or when you need to exit based on a condition.
Using sys.exit()
Before using sys.exit(), you must import the sys module.
import sys
age = int(input("Enter your age: "))
if age < 18:
print("You are not eligible.")
sys.exit() # Terminates the program
print("Welcome to the voting system!")
Handling sys.exit() with try-except
If sys.exit() is called inside a try block, it can be caught in an except block.
import sys
try:
print("Exiting the program")
sys.exit()
except SystemExit:
print("Program exited")
CHAPTER 3 – FUNCTIONS
1. Functions in Python
A function is a reusable block of code that performs a specific task. Functions help in
modular programming, making code more organized, readable, and reusable.
Defining a Function
Functions are defined using the def keyword, followed by the function name and
parentheses.
Syntax:
def function_name(parameters):
"""Optional docstring"""
# Function body
return value # Optional return statement
Example:
def greet():
print("Hello, welcome to Python!")
greet() # Function call
Output:
Hello, welcome to Python!
2. def Statements with Parameters
Functions can take parameters (also called arguments) to process data.
Example: Function with Parameters
def add_numbers(a, b):
result = a + b
print("Sum:", result)
add_numbers(5, 10) # Output: Sum: 15
• a and b are parameters (placeholders).
• 5 and 10 are arguments (actual values passed).
3. Return Values and return Statements
A function can return a value using the return statement.
Example: Function Returning a Value
def square(num):
return num * num
result = square(4)
print("Square:", result) # Output: Square: 16
Key Points about return
• Ends function execution and sends the result back.
• Functions without return return None.
• Can return multiple values as a tuple.
Example of multiple return values:
def arithmetic_operations(a, b):
return a + b, a - b, a * b, a / b
sum_, diff, prod, quot = arithmetic_operations(10, 2)
print(sum_, diff, prod, quot) # Output: 12 8 20 5.0
4. The None Value
• None represents the absence of a value.
• Functions that don’t return anything return None.
Example:
def no_return():
print("This function has no return statement")
result = no_return()
print(result) # Output: None
5. Keyword Arguments and print()
Python allows calling functions using keyword arguments (named parameters) instead of
positional arguments.
Example: Using Keyword Arguments
def greet(name, message="Hello"):
print(message, name)
greet(name="Alice", message="Good morning!") # Output: Good morning! Alice
greet("Bob") # Output: Hello Bob (default message)
The print() Function
The print() function has optional keyword arguments:
Argument Description
sep Separator between values (default: space " ")
end What to print at the end (default: newline \n)
Example:
print("Python", "Programming", sep="-") # Output: Python-Programming
print("Hello", end=" ")
print("World!") # Output: Hello World! (same line)
6. Local and Global Scope
Variables in Python have scope, meaning where they can be accessed.
Local Variables
• Declared inside a function.
• Accessible only within that function.
def my_function():
local_var = 10 # Local variable
print("Inside function:", local_var)
my_function()
# print(local_var) # Error: local_var is not defined outside the function
Global Variables
• Declared outside any function.
• Accessible throughout the program
global_var = 20 # Global variable
def show():
print("Global variable:", global_var)
show()
print("Outside function:", global_var)
7. The global Statement
If a function needs to modify a global variable, use global.
Example: Using global
count = 0 # Global variable
def increment():
global count # Modify global variable inside function
count += 1
increment()
print(count) # Output: 1
Without global, Python treats count as local, and modifying it inside increment() would
cause an error.
8. Exception Handling
Exceptions are runtime errors that disrupt program execution. Python provides try-except
blocks to handle exceptions.
Common Exceptions
Exception Description
ZeroDivisionError Dividing by zero
ValueError Invalid value (e.g., entering text instead of a number)
TypeError Wrong data type operation
IndexError Accessing out-of-range index
Basic try-except Example
try:
x = int(input("Enter a number: "))
result = 10 / x
print("Result:", result)
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("Invalid input! Enter a number.")
Using finally (Always Executes)
try:
f = open("file.txt", "r")
data = f.read()
except FileNotFoundError:
print("File not found!")
finally:
print("This will always execute.")
9. A Short Program: Guess the Number
This is a simple Python program where the user guesses a number, and the program provides
hints.
import random
def guess_the_number():
number = random.randint(1, 100)
attempts = 0
print("Welcome to Guess the Number!")
print("Try to guess the number between 1 and 100.")
while True:
try:
guess = int(input("Enter your guess: "))
attempts += 1
if guess < number:
print("Too low! Try again.")
elif guess > number:
print("Too high! Try again.")
else:
print(f"Congratulations! You guessed it in {attempts}
attempts.")
break
except ValueError:
print("Please enter a valid number.")
guess_the_number()
Explanation:
• Generates a random number between 1 and 100.
• Uses a loop to keep asking for input.
• Provides hints if the guess is too high or too low.
• Uses exception handling to handle invalid inputs.
• Ends when the correct number is guessed.
Summary
• Functions improve code reuse and organization.
• Return values allow functions to send results.
• None represents the absence of a return value.
• Keyword arguments improve readability.
• Global and local scope affect variable accessibility.
• Exception handling makes programs more robust.
• A guessing game demonstrates these concepts in action.