MAEER’s
MIT Arts Commerce Science College Alandi(D) Pune
F.Y.B.Sc. (Cyber & Digital Science)
Subject Code: 2408SB3T205
Subject: Python Programming
No. of Credit: 02
1.1The Python Programming Language, History, versions,
features, Applications
1.2 The Python programming environment, Basic Syntax,
Writing and executing a Python program, Comments, Keywords
UNIT I : and identifiers
Essentials of 1.3 Data types and Variables, Getting and setting the data type,
Constants, Lines and indentation, Input/output with print and
Python input, Command line arguments
Programming 1.4 Operators and expressions, Precedence of operators, type
conversion
1.5 Strings: declaration, manipulation, special operations,
escape character, string formatting Operator, Built-in String
functions.
• Python is a popular • Applications
programming language • Python can be used on a
created by Guido van server to create web
Rossum and released in applications.
1991. Latest stable version: • Python can be used
Python 3.x
alongside software to
• Python has a simple syntax create workflows.
similar to the English • Python can connect to
language database systems.
• Open-source and cross- • It can also read and
Introduction platform. modify files.
• Supports multiple • Python can be used to
programming paradigms handle big data and
(procedural, object- perform complex
oriented, functional). mathematics.
• Large, active community • Python can be used for
for support and rapid prototyping, or for
collaboration. production-ready
software development.
1. Easy to Learn and Use
Simple syntax similar to English, making it beginner-friendly.
2. Interpreted Language
No need for compilation; code is executed line-by-line for faster debugging.
3. High-Level Language
Abstracts complex programming details, allowing focus on logic and
functionality.
4. Versatile and General-Purpose
Used in web development, AI, data analysis, automation, game development,
Features of and more.
5. Extensive Standard Library
Python Provides built-in modules for file handling, math, web protocols, and more.
Programming
6. Platform-Independent
Code can run on different operating systems without modification.
Language 7. Open Source
Freely available with a large, active community contributing to its growth.
8. Object-Oriented and Functional
Supports multiple programming paradigms, including OOP, procedural, and
functional styles.
9. Dynamic Typing
No need to declare variable types; Python infers them automatically.
10.Rich Ecosystem
Thousands of libraries (e.g., NumPy, Pandas, Django) for diverse applications.
Python programming
environment
• Includes: Integrated Development
Environments (IDEs)
• These tools can be used to learn, build,
run, and test Python scripts
1. IDLE: The default editor that comes
with Python, and a good choice for
beginners.
2. PyCharm: A popular IDE created by
JetBrains
3. Visual Studio Code: A free, open-
source IDE created by Microsoft.
4. Jupyter Notebook : Is another
Integrated Development Environment
specifically used for Data Science
Syntax
• Python is an interpreted programming language, this means that as a developer you write
Python (.py) files in a text editor and then put those files into the python interpreter to be
executed. (needs python package installed)
• The way to run a python file is like this on the command line / :
$ python filename.py
• Or use python prompt to Invoking the Interpreter in interactive mode
$ python
>>> print(“Hello”)
• Using Jupyter Notebook – ( needs notebook package installed )
• The way to start Jupyter Notebook application using command line:
$ jupyter notebook
• Using Jupyter Notebook application in browser
Browser window with URL - http://localhost:8888/tree?
File-> New -> Notebook
Select Kernal for notebook – ipyub file
Python Indentation
• Indentation refers to the spaces at the beginning of a code line.
• Where in other programming languages the indentation in code is for readability only, the indentation in
Python is very important.
• Python uses indentation to indicate a block of code.
• Python will give you an error if you skip the indentation
Python Variables
• In Python, variables are created when you assign a value to it
• Python has no command for declaring a variable.
Python Comments
• In Python has commenting capability for the purpose of in-code documentation.
• Comments start with a #, and Python will render the rest of the line as a comment
Variables • Rules for Naming
1. Variables Must begin with a letter or an
underscore (_).
• Variables are containers for storing data values.
• A variable is a name that refers to a memory 2. Can contain letters, numbers, and underscores.
location used to store data. 3. Cannot start with a digit.
• In Python, variables are created when you assign a 4. Cannot use Python keywords (e.g., if, while).
value to them 5. Case-sensitive: variable and Variable are
• Ex: different.
x = 10 • Casting
name = "Amit"
• If you want to specify the data type of a variable,
• Variables do not need to be declared with any this can be done with casting.
particular type, and can even change type after
they have been set. • Ex:
x = str(3) # x will be '3'
• Ex:
y = int(3) # y will be 3
x = 10 # Integer
z = float(3) # z will be 3.0
x = "Hello" # String
print(x) • Checking Type of a Variable
• Use the type() function to find a variable's type:
x = 10
print(type(x)) # Output: <class 'int’>
Getting the Data Type
• Use the type() function to check the data type of a variable.
x = 5
print(type(x))
# Output: <class 'int’>
y = "Hello"
print(type(y))
# Output: <class 'str'>
Setting/Changing the Data Type
• You can change the data type of a variable using type # Integer to String
conversion functions. x = 10
• Common Type Conversion Functions: x = str(x)
int() → Converts to integer print(x, type(x))
float() → Converts to float # Output: '10' <class 'str’>
str() → Converts to string
bool() → Converts to Boolean # String to Float
list() → Converts to list y = "3.14"
tuple() → Converts to tuple y = float(y)
set() → Converts to set print(y, type(y))
# Output: 3.14 <class 'float'>
Output with print()
• The print() function is used to display data on the console.
• Basic usage
print("Hello, World!") # Output: Hello, World!
• Printing Multiple Items
name = "Amit“
age = 25
print("Name:", name, "Age:", age) # Output: Name: Amit Age: 25
• Formatted Output
name = "Bob"
age = 30
print(f"My name is {name} and I am {age} years old.")
• Using format() Method
print("My name is {} and I am {} years old.".format(name, age))
• Old-style % formatting
name = "Alice“
age = 30
print("My name is %s and I am %d years old." % (name, age))
Input with input()
• The input() function takes user input as a string.
• Basic Usage # Integer input
user_name = input("Enter your name: ") age = int(input("Enter your age: "))
print("Hello ", user_name) # Float input
height = float(input("Enter your height in
• Converting Input to Other Types meters: "))
By default, input() returns a string, so you need to print(f"You are {age} years old and
convert it to other types if needed. {height} meters tall.")
• Accepting Multiple Values Using input() in Python
To accept multiple values in a single input, you can use the split() method along with input().
This allows the user to enter multiple values separated by spaces, commas, or any other delimiter.
# Input: multiple values separated by spaces
values = input("Enter multiple values: ").split()
print(values)
# Accept input and split into two parts
num, text = input("Enter an integer and a string separated by space: ").split()
# Convert the first input to an integer
num = int(num)
# Print the results
print("Integer:", num) print("String:", text)
Command line arguments in python
• In Python, command-line arguments allow you to pass information to a script when running it from the
terminal or command prompt.
• Python provides the sys module to handle these arguments.
• sys.argv is a list in Python that contains the command-line arguments passed to the script.
• The first element (sys.argv[0]) is always the script name.
• Example
import sys
print("Script name:", sys.argv[0])
print("Number of arguments:", len(sys.argv))
print("Arguments:", sys.argv)
• Running the script:
python script.py arg1 arg2
Arithmetic Operators
Operator Name Description Example
+ Addition Adds together two values a+b
- Substraction Subtracts one value from another a–b
* Multiplication Multiplies two values a*b
/ Division Divides one value by another a/b
// Floor Division Returns the largest integer that is less a // b
than or equal to the quotient of two
numbers
% Modulus Returns the division remainder a%b
** Exponentiation raising one quantity to the power of a**b
another.
Comparison Operators
Operator Name Description Example
== Equal to Returns true if the values are equal a == b
!= Not equal to Returns true if the values are not equal a != b
> Greater than Returns true if the first value is greater a>b
than the second value
< Less than Returns true if the first value is less than a<b
the second value
>= Greater than or equal Returns true if the first value is greater a >= b
to than, or equal to, the second value
<= Less than or equal to Returns true if the first value is less than, a <= b
or equal to, the second value
Logical Operators
• Logical operators are used to check 2 or more different conditions and take decision accordingly
Note
• In the case of AND, the result is true only if both conditions are true.
• In the case of OR, the result is false only if both conditions are false.
• The logical NOT operator takes the operand and reverses the value of the expression
• They are commonly used in decision-making statements like if, while, and for loops to combine
multiple conditions.
Operator Name Description Example
and Logical AND Returns 1 if both statements are true if x < y and y < z:
or Logical OR Returns 1 if one of the statements is true if x > y or y < z:
not Logical NOT Reverse the result, returns 0 if the result is if not x > y :
1
Assignment Operators
Operator Description Example Same as
= Simple assignment operator. Assigns values from right side x=5 x=5
operands to left side operand
+= It adds the right operand to the left operand and assign the result x += 3 x=x+3
to the left operand.
-= It subtracts the right operand from the left operand and assigns x -= 3 x=x-3
the result to the left operand.
*= It multiplies the right operand with the left operand and assigns x *= 3 x=x*3
the result to the left operand.
/= It divides the left operand with the right operand and assigns the x /= 3 x=x/3
result to the left operand.
//= It combines the floor division operation with assignment. It x //= 2 x = x // 2
divides the value of the variable on the left by the value on the
right and then assigns the result back to the variable.
%= It takes modulus using two operands and assigns the result to the x %= 3 x=x%3
left operand.
**= It raises the value of the variable on the left to the power of the x **= 2 x = x ** 2
value on the right and assigns the result back to the variable.
Bitwise Operators
Operator Name Description Example
& AND Sets each bit to 1 if both x&y
bits are 1
| OR Sets each bit to 1 if one of x|y • Bitwise operators are used on (binary)
two bits is 1 numbers.
^ XOR Sets each bit to 1 if only x^b • These operators are essential for
one of two bits is 1 tasks such as low-level programming,
hardware manipulation, and
~ NOT Binary One's Complement ~x optimizing certain algorithms
Operator is unary and has
the effect of 'flipping' bits.
<< Zero fill left shift Shift left by pushing zeros in x << 2
from the right
>> Signed right Shift right by pushing copies x >> 2
shift of the leftmost bit in from
the left, and let the
rightmost bits fall off
Membership Operators
• Used to check if a value exists in a
Operator Description Example Result sequence.
in Value in sequence 'a' in 'apple' true
not in Value not in sequence 'b' not in 'apple' true
Identity Operators
• Used to check if two variables
Operator Description Example Result reference the same object.
is Same object x is y true / false
not is Different objects x is not y true / false
String
• A string is a sequence of characters enclosed in Strings are Arrays
quotes. • Like many other popular programming
• Strings are one of the most commonly used data languages, strings in Python are arrays of
types and are highly versatile. bytes representing unicode characters.
• Python provides various ways to define, • However, Python does not have a character
manipulate, and work with strings. data type, a single character is simply a string
with a length of 1.
• Square brackets can be used to access
Creating Strings elements of the string.
a = “Hello, World!”
• Strings can be created using: print(a[1])
Single quotes: Hello’ Strings in Python are immutable, meaning their
Double quotes: “Hello” content cannot be changed after creation.
Triple quotes (for multi-line strings): Any operation that modifies a string returns a
‘’’Hello’’’ new string
or text = “hello”
“”” text[0] = ‘H’ # Error: Strings are
immutable
Hello
text = "Hello" # Assigning a new
“”” string is fine
String - Indexing and Slicing
Slicing Negative Indexing
• You can return a range of characters by using the • Use negative indexes to start the slice from the
slice syntax. end of the string:
• Specify the start index and the end index, b = "Hello, World!"
separated by a colon, to return a part of the print(b[-2:]) #d!
string. print(b[:-2]) # Hello, Worl
b = "Hello, World!" print(b[-5:-2]) #orl
print(b[2:5]) #llo Concatenation
Slice From the Start • Combine strings using the + operator
• By leaving out the start index, the range will start str1 = "Hello“
at the first character: str2 = "World“
b = "Hello, World!" result = str1 + " " + str2
print(b[:5]) #Hello # "Hello World“
Slice To the End Repetition
• By leaving out the end index, the range will go to • Repeat strings using the * operator
the end: result = "Ha" * 3 # "HaHaHa"
b = "Hello, World!"
print(b[2:]) #llo, World!
Commonly used string functions
Formatting and Case Conversion • str.swapcase(): Swaps the case of each
character.
str.capitalize(): Converts the first character to
uppercase. print("Hello World".swapcase())
print("hello".capitalize()) Searching and Finding
# Output: Hello • str.find(sub): Returns the index of the first
• str.upper(): Converts all characters to occurrence of a substring. Returns -1 if not found.
uppercase print("hello".find("e")) # Output: 1
print("hello".upper()) • str.index(sub): Similar to find() but raises a
# Output: HELLO ValueError if the substring is not found.
• str.lower(): Converts all characters to print("hello".index("e")) # Output: 1
lowercase. • str.startswith(prefix): Checks if the string
print("HELLO".lower()) starts with the specified prefix.
# Output: hello print("hello".startswith("he")) #
• str.title(): Converts the first character of each Output: True
word to uppercase. • str.endswith(suffix): Checks if the string ends
print("hello world".title()) with the specified suffix.
# Output: Hello World print("hello".endswith("lo"))
# Output: True
Commonly used string functions
Replacing and Splitting Trimming
• str.replace(old, new): Replaces occurrences of old with • str.strip(): Removes leading and trailing
new. whitespace (or specified characters).
print("hello world".replace("world", "Python")) print(" hello ".strip())
# Output: hello Python # Output: hello
• str.split(separator): Splits the string into a list using the • str.lstrip(): Removes leading whitespace.
specified separator. print(" hello".lstrip())
print("a,b,c".split(",")) # Output: hello
# Output: ['a', 'b', 'c’]
• str.splitlines(): Splits the string into a list at line breaks. • str.rstrip(): Removes trailing whitespace.
print("line1\nline2".splitlines()) print("hello ".rstrip())
# Output: ['line1', 'line2’] # Output: hello
Commonly used string functions
Checking String Properties
• str.isalpha(): Checks if all characters are • str.isspace(): Checks if all characters are
alphabetic. whitespace.
print("hello".isalpha()) print(" ".isspace())
# Output: True # Output: True
• str.isdigit(): Checks if all characters are digits. • str.isupper(): Checks if all characters are
print("1234".isdigit()) uppercase.
# Output: True print("HELLO".isupper())
# Output: True
• str.isalnum(): Checks if all characters are • str.islower(): Checks if all characters are
alphanumeric. lowercase.
print("hello123".isalnum()) print("hello".islower())
# Output: True # Output: True
Special operations on string
String Escaping with Backslashes Raw Strings
• Special characters can be included in strings using • Raw strings treat backslashes as literal characters,
escape sequences, Common escape sequences: useful for regex or file paths
\n: Newline raw_string =
\t: Tab r"C:\Users\Name\Documents"print(raw_string)
# Output: C:\Users\Name\Documents
\\: Backslash
\': Single quote Substring Membership
\": Double quote • Check if a substring exists using in and not in
text = "This is a line.\nThis is a new text = "Python programming“
line." print("Python" in text) # True
# \n for new line print("Java" not in text) # True
print(text)
Count Substring Occurrences
text = "This is a tab:\tHere."
text = "banana"print(text.count("a")) # 3
# \t for tab
print(text) Other
quote = "He said, \"Hello!\"" • len(str): returns no of character in string
# Escaping quotes • ord(char): Returns the ASCII value of the given
print(quote) character.
String formatting operator
• The string formatting operator % is an older method Floating-Point Formatting
for formatting strings. pi = 3.14159265
• It allows you to embed values into strings by using print("Pi is approximately %.2f." % pi)
placeholders. # Output: Pi is approximately 3.14.
• Placeholder Description Hexadecimal and Octal
%s String or any object (uses str()). number = 255
%d Integer print("Hex: %x, Octal: %o" % (number,
%f Floating-point number number))
%.nfFloating-point with n decimal places. # Output: Hex: ff, Octal: 377
%x Hexadecimal (lowercase) Escape % Symbol
%X Hexadecimal (uppercase) • To include a literal % symbol in your string, use %%
%o Octal discount = 50
Basic Usage print("Get a %d%% discount!" % discount)
name = "Alice“ # Output: Get a 50% discount!
age = 25
print("My name is %s and I am %d years
old." % (name, age))
# Output: My name is Alice and I am 25
years old.
String formatting operator
Using a Tuple
name = “Bob”
age = 30
print("Name: %s, Age: %d" % (name, age))
Using a Dictionary
info = {"name": "Bob", "age": 30}
print("Name: %(name)s, Age: %(age)d" %
info)