0% found this document useful (0 votes)
11 views23 pages

Introduction to Python Programming

The document provides an introduction to Python programming, covering its history, installation, basic syntax, and features. It explains data types, variables, and the significance of Python in various domains such as web development, data science, and artificial intelligence. Additionally, it discusses Python's operators, type conversion, and the structure of Python programs, including tokens and comments.

Uploaded by

nikita.jangid
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)
11 views23 pages

Introduction to Python Programming

The document provides an introduction to Python programming, covering its history, installation, basic syntax, and features. It explains data types, variables, and the significance of Python in various domains such as web development, data science, and artificial intelligence. Additionally, it discusses Python's operators, type conversion, and the structure of Python programs, including tokens and comments.

Uploaded by

nikita.jangid
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

Course Code : 25MCDECA1111

Python Programming
BY MS. NIKITA JANGID
Unit 1
INTRODUCTION TO PYTHON AND DATA TYPES
❖PYTHON INTRODUCTION
Python was created 1991 with focus on code readability and express concepts in fewer lines of
code.
• Simple and readable syntax makes it beginner-friendly.
• Runs seamlessly on Windows, macOS and Linux.
• Includes libraries for tasks like web development, data analysis and machine learning.
• Variable types are determined automatically at runtime, simplifying code writing.
• Supports multiple programming paradigms, including object-oriented, functional and
procedural programming.
• Free to use, distribute and modify.

❖INSTALLATION & WORKING WITH PYTHON


• Steps to Install:
1. Download Python from [Link].
2. Run the installer → Check "Add Python to PATH".
3. Choose Install Now (default settings recommended).
• Verify Installation:
Open terminal/command prompt → python --version
Output example: Python 3.11.7
• Working with Python:
o Interactive Mode (REPL): Type python in terminal → run commands line by
line.
o Script Mode: Save code in .py file → run with: python [Link]

❖UNDERSTANDING HELLO WORLD PROGRAM IN


PYTHON
Hello, World! in python is the first python program which we learn when we start learning
any program. It’s a simple program that displays the message “Hello, World!” on the screen.

Here’s the “Hello World” program:


# This is a comment. It will not be executed.
print("Hello, World!")
Output
Hello, World!
How does this work:
• print() is a built-in Python function that tells the computer to show something on the
screen.
• The message "Hello, World!" is a string, which means it's just text. In Python, strings are
always written inside quotes (either single ' or double ").
• Anything after # in a line is a comment. Python ignores comments when running the
code, but they help people understand what the code is doing.
• Comments are helpful for explaining code, making notes or skipping lines while testing.
We can also write multi-line comments using triple quotes:
"""
This is a multi-line comment.
It can be used to describe larger sections of code.
"""

❖WHY LEARN PYTHON?


1. Easy to Read and Write
• Python looks like simple English.
• You don’t need to write complicated code.
• Example: To print "Hello", just write:
• print("Hello")
2. Large Library Support
• Python has ready-made libraries (collections of code) for almost everything.
• Example:
1. NumPy & Pandas → For Data Science.
2. TensorFlow & PyTorch → For Artificial Intelligence.
3. Django & Flask → For Web Development.

3. Widely Used in Industry


• Big companies use Python daily.
• Examples:
• Google → Uses Python for search systems.
• YouTube & Instagram → Built using Python.
• NASA→ Uses Python for scientific research.
4. Huge Community Support
• Millions of developers use Python.
• If you face an error, you can easily find a solution online.
• Beginners get lots of free tutorials, forums, and guides
[Link]-Platform Language
• Python runs on Windows, Linux, Mac, Android.
• Write once → Run anywhere.
[Link] (Used Everywhere)
• Websites (Django, Flask)
• Games (Pygame)
• Data Science & AI (Machine Learning, Deep Learning)
• Automation (scripts to save time)
• IoT Devices (Raspberry Pi projects).
7. Beginner-Friendly + Powerful
• Easy for students to learn as the first programming language.
• But also powerful enough for advanced technologies like Artificial Intelligence and
Cybersecurity
❖APPLICATIONS OF PYTHON
• Web Development → Django, Flask
• Data Science & ML → NumPy, Pandas, TensorFlow, Scikit-Learn
• Artificial Intelligence → Natural Language Processing, Neural Networks
• Automation → Writing scripts, bots
• Game Development → PygameDesktop Apps → Tkinter, PyQt

❖FEATURES OF PYTHON
• Easy to Learn & Readable– Syntax is like English.
• Interpreted– Runs line by line (no need for compilation)
• Cross-Platform– Works on Windows, macOS, Linux, etc.
• Open Source– Free to use, with a huge community.
• Extensive Libraries– For data, AI, ML, web, graphics, etc.
• Object-Oriented– Supports OOP concepts (classes, objects).
• Versatile– Can be used in almost every field of technology
❖FIRST PYTHON PROGRAM
print("Hello, World!")
Output: Hello, World

❖AFTER LEARNING PYTHON – WHICH DOMAIN TO


CHOOSE?
Python is one of the most versatile programming languages. Once you learn the basics, you can
explore many domains depending on your interest and career goals. Some popular domains are:
[Link] Development: Use frameworks like Django and Flask to build dynamic websites and
web applications. Example: Building an e-commerce site like Amazon.
[Link] Science & Analytics: Learn libraries like Pandas, NumPy, Matplotlib, Seaborn for data
analysis. Use Scikit-learn and TensorFlow for machine learning. Example: Predicting sales
trends using data.
[Link] Intelligence & Machine Learning: Use TensorFlow, PyTorch, Keras to build
smart models. Applications include chatbots, recommendation systems, and self-driving cars.
[Link] & Scripting: Python is great for automating repetitive tasks (file handling,
emails, data entry). Example: Writing a script that automatically renames 1000 files.
[Link] Development: Use Pygame to build 2D games. Example: Creating a simple snake or
puzzle game.
[Link]: Python helps in ethical hacking, penetration testing, and security analysis.
Example: Writing a script to scan open ports of a server
[Link] of Things (IoT): Python works well with hardware like Raspberry Pi. Example:
Building a home automation system with sensors.
8. Desktop GUI Applications: Libraries like Tkinter, PyQt, Kivy are used for making desktop
apps. Example: Building a calculator or notepad application.

❖CHARACTER SET IN PYTHON


• Character set is the set of valid characters that can be used in Python programs.
• Python supports Unicode, so it can handle many languages and [Link] allowed
in Python:
• Letters: A-Z, a-z
• Digits: 0-9
• Special symbols: + - * / % = ( ) [ ] { } @ # , . : etc.
• Whitespace characters: space, tab, newline
• Other symbols: Unicode characters like π,√
❖PYTHON TOKENS
In Python, tokens are the smallest units of a program.
Just like words make sentences in English, tokens make Python
programs.
• Whenever we write a Python program, the Python interpreter breaks
it into tokens before execution.
Types of Tokens in Python
• Keywords
• Identifiers
• Literals
• Operators
• Punctuators / Separators

1. Keywords
• Keywords are reserved words in Python.
• They have special meaning and cannot be used as variable names.
• Examples: if, else, while, for, break, True, False, None, etc.
• Example:
if True:
print("This is a keyword example")

2. Identifiers
• Identifiers are names used to identify variables, functions, classes, etc.
• Rules for identifiers:
1. Must start with a letter (a-z, A-Z) or an underscore (_).
2. Can contain letters, digits (0-9), and underscore.
3. Cannot use keywords as identifiers.
4. Python is case-sensitive (Var and var are different).
Example
name = "Priyanshu" # identifier = name
_age = 22
# identifier = _age
3. Literals
• Literals are fixed values assigned to variables.
• Types of literals in Python:
• String Literals– "Hello", 'World'
• Numeric Literals
• Integer → 10, -5
• Float → 3.14, -0.99
• Complex → 2+3j
• Boolean Literals– True, False
• Special Literal– None

4. Operators
• Operators are symbols used to perform operations.
• Types of operators:
1. Arithmetic → +, -, *, /, %, **, //
2. Relational → ==, !=, >, <, >=, <=
3. Logical → and, or, not
4. Assignment → =, +=, -=, *=, /=
5. Bitwise → &, |, ^, ~, <<, >>
6. Membership → in, not in

5. Punctuators (Separators)
•These are symbolsused to structure Python programs.
Symbol Meaning
() Parentheses (function call, tuples)
[] Square brackets (lists, indexing)
{} Curly braces (dictionaries, sets)
: Colon (used in loops, functions, classes)
, Comma (separates values)
. Dot (object/member access)
; Semicolon (rarely used, separates statements on one line)
# Comment symbol
""" """ Triple quotes (multi-line string or docstring)
❖WHAT IS A VARIABLE?
• A variable is a name given to a memory location used to store data.
• In Python, you don’t need to declare the type of variable explicitly → Python automatically
detects it (Dynamic Typing).
➢ Syntax:
• variable_name = value
➢ Example in Real Life:
• Suppose you have a wallet.
• Inside the wallet, you can keep money (numbers).
• You can also keep a card (text).
• Here, your wallet = variable, and the money/card = value
➢ Rule for Variable Creations
1. A variable name must start with a letter (a–z, A–Z) or an underscore (_) only.
2. A variable name cannot start with a number.
3. Variable names can contain only letters, numbers, and underscores → no spaces or special
symbols allowed.
4. Variable names are case-sensitive (name, Name, and NAME are different).
5. Reserved keywords (like if, while, for, class, etc.) cannot be used as variable names.
6. No need to declare type before use (Python is dynamically typed).
7. Multiple variables can be assigned in one line → a, b, c = 1, 2, 3.
8. Same value can be assigned to multiple variables → x = y = z = "Python"
➢ Example in Python
• name = “Rahul" # Like writing your name on a form
age = 21 # Your age (a number)
height = 5.9 # Height in feet
• is_student = True # Yes/No answer
❖DATA TYPES IN PYTHON
Definition: A data type tells what kind of data a variable can store. (Just like we have types of
things in life: number, text, yes/no, list of items, etc.)
Python has two main categories of data types:
1. Primitive (Basic / Built-in) Data Types
2. Non-Primitive (Collection / Data Structures) Data Types
Primitive (Basic / Built-in) Data Types
These are the fundamental data types.
a) Numeric Types
➢ int (Integer): Whole numbers (positive or negative) without decimals.
• Syntax:
• x = 10 # int
➢ float (Floating-point): Numbers with decimal points.
Syntax:
y = 3.14 # float
➢ Complex: Numbers with a real and imaginary part.
Syntax:
z = 2 + 3j # complex
b) Text Type
➢ str (String): A sequence of characters inside quotes.
Syntax:
name = "Priyanshu" # string
c) Boolean Type
➢ bool (Boolean)
• Represents truth values: True or False.
Syntax:
• flag = True
Non-Primitive (Collection / Data Structures) Data Types
1. List: A list is an ordered collection that can hold multiple items of any type. Lists are
mutable, meaning you can change them after creation. Use square brackets [], with items
separated by commas.
Syntax:
fruits = ["apple", "banana", "cherry", 100]
print(fruits)
2. Tuple: A tuple is an ordered collection like a list, but it is immutable (cannot be changed
once created). Use round brackets () with items separated by commas.
Syntax:
coordinates = (10, 20, 30)
print(coordinates) # 10
3. Set: A set is an unordered collection of unique elements. It does not allow duplicates and is
used for mathematical operations. Use curly braces {} with unique items, OR use the set()
constructor.
Syntax:
nums = {1, 2, 3, 3, 4}
print(nums)
# {1, 2, 3, 4} (duplicates removed)

4. Frozenset: A frozenset is the immutable version of a set. Once created, you cannot add or
remove elements. Use the frozenset() function.
Syntax:
fs = frozenset([1, 2, 3, 4])
print(fs)
output:
frozenset({1, 2, 3, 4})
[Link] (dict): A dictionary stores data in key-value pairs. Keys are unique, and values
can be any type. Use curly braces {} with key-value pairs separated by (:).
Example:
student = {"name": "Priyanshu", "age": 23, "grade": "A"}
print(student["name"]) # Priyanshu
student["age"] = 24
print(student)
# updating value
# {'name': 'Priyanshu', 'age': 24, 'grade': 'A'}
Basic Data Types

Sequence Data Types


Set Data Type

❖STRING DATA TYPE & STRING OPERATIONS


• A string is a sequence of characters enclosed in 'single' or "double quotes".
• Example:
• name = "Python"
Common String Operations
s = "Python Programming"
print(len(s)) # length of string
print([Link]()) # PYTHON PROGRAMMING
print([Link]()) # python programming
print([Link]()) # Python Programming
print([Link]()) # removes spaces
print([Link]("Python", "Java")) # Java Programming
print([Link]()) # ['Python', 'Programming']
print(s[0]) #P
print(s[-1]) # g (last character)
print(s[0:6]) # Python (slicing)
• Strings are immutable (cannot be changed after creation).
❖PYTHON TYPE CONVERSION
• Type Conversion means changing one data type into another.
• Example: Converting a number into a string or a string into a number.
• Just like in real life: If you have 100 rupees in coins, you can exchange it for a 100 rupee
note. The value is the same, but the form (type) has changed.
Types of Type Conversion
(A) Implicit Type Conversion (Type Casting by Python)
• Python automatically converts one type to another.
• Happens when you combine two different types in an expression.
• Also called Type Casting or Type Promotion.
Syntax: (done automatically by Python)
• result = int_value + float_value
Example:
• x = 10 #int
• y = 3.5 9 #float
• z = x + y # int + float → float
• print(z) # Output: 13.5
• print(type(z)) # <class 'float'>
(B) Explicit Type Conversion (Type Casting by Programmer)
You manually change the type using Python functions. Functions: int(), float(), str(), list(),
tuple(), set(), dict().
Syntax:
new_variable = datatype(value)
➢ Explicit Type Conversion Example
# int → float
x=5
y = float(x)
print(y) # Output: 5.0
# float → int
a = 9.8
b = int(a)
print(b) # Output: 9
# number → string
age = 21
text = str(age)
print(text) # Output: "21"

# string → int
num = int("100")
print(num + 20) # Output: 120

❖OPERATORS IN PYTHON
Operators in general are used to perform operations on values and variables. we will look into
different types of Python operators.
• OPERATORS: These are the special symbols. Eg- + , * , /, etc.
• OPERAND: It is the value on which the operator is applied.
1. Arithmetic Operators: Arithmetic operators are used in Python to perform basic
mathematical operations like addition, subtraction, multiplication, division, etc., on
numeric values (integers, floats, complex numbers).

Syntax:
# General form
• result = operand1 operator operand2
Example :
# Define operands
a = 10
b=3
print("Addition:", a + b) # 13
print("Subtraction:", a - b) #7
print("Multiplication:", a * b) # 30
print("Division:", a / b) # 3.333...
print("Floor Division:", a // b) # 3
print("Modulus:", a % b) #1
print("Exponentiation:", a ** b) # 1000
2. Comparison (Relational) Operators: Comparison operators (also called relational
operators) are used to compare two values. They always return a Boolean value → either
True or False.

Syntax
result = operand1 comparison_operator operand2
Examples:# Define operands
x = 10
y = 20
print("x == y :", x == y) # False
print("x != y :", x != y) # True
print("x > y :", x > y) # False
print("x < y :", x < y) # True
print("x >= y :", x >= y) # False
print("x <= y :", x <= y) # True
Key Points:
• Comparison operators are mainly used in conditions (if, while, etc.).
• They return Boolean values (True / False).
3. Logical Operators: Logical operators are used to combine conditional statements. They
return a Boolean value (True or False) based on logical relationships between conditions.
Syntax
result = condition1 logical_operator condition2
Examples:
x = 10
y=5
# Logical AND
print(x > 5 and y < 10) # True (both are True)
print(x > 5 and y > 10) # False (second is False)
# Logical OR
print(x > 5 or y > 10) # True (one is True)
print(x < 5 or y > 10) # False (both False)
# Logical NOT
print(not(x > 5))
print(not(y > 10))
# False (because x > 5 is True)
# True (because y > 10 is False)

• and → All conditions must be True.


• or → At least one condition True.
• not → Reverses the result.
• Often used in if, while, and complex conditions
4. Bitwise Operators: Bitwise operators are used in Python to perform operations on the
binary representation (bits) of integers.
• They treat numbers as sequences of 0s and 1s.
• Work only with integers.
• Useful in low-level programming, cryptography, networking, compression, and optimization.

➢ Bitwise AND Operator


The Bitwise AND (&) operator compares each bit of two numbers.
• If both bits are 1 → result is 1.
• Otherwise → result is 0.
Rule (Truth Table):
•0&0=0
•0&1=0
•1&0=0
•1&1=1
Example
• a = 5 # binary: 0101
• b = 3 # binary: 0011
• result = a & b
• print(result) # Output: 1
➢ Bitwise OR (|) in Python
• The Bitwise OR (|) operator compares each bit of two numbers.
• If at least one bit is 1 → result is 1.
• If both bits are 0 → result is 0.
Rule (Truth Table):
•0|0=0
•0|1=1
•1|0=1
•1|1=1
Example
• a = 5 # binary: 0101
• b = 3 # binary: 0011
• result = a | b
• print(result) # Output: 7
➢ Bitwise XOR (^)
The Bitwise XOR (^) operator compares each bit of two numbers.
• If the bits are different → result is 1.
• If the bits are the same → result is 0.
Rule (Truth Table):
•0^0=0
•0^1=1
•1^0=1
•1^1=0
Example
• a = 5 # binary: 0101
• b = 3 # binary: 0011
• result = a ^ b
• print(result) # Output: 6
➢ Bitwise NOT (~)
• The Bitwise NOT operator (~) in Python is a unary operator (works
on only one operand).
• It flips every bit of the given number:
•0→1
•1→0
• It is also known as the one’s complement operator.
• In Python, integers are stored in signed two’s complement form, so
applying ~ gives:
• Example = ~x = -(x + 1)
➢ Right Shift (>>)
• Shifts the bits of the number to the right and fills 0 on voids left( fills 1
in the case of a negative number) as a result. Similar effect as of
dividing the number with some power of two
• Example: 10>>1= 5
➢ Left Shift (<<)
• Shifts the bits of the number to the left and fills 0 on voids right as a
result. Similar effect as of multiplying the number with some power
of two.
• Example: 5<<1=1
5. Assignment Operators
x=5
x += 3 # x = x + 3 → 8
x -= 2 # x = x - 2 → 6
x *= 4 # x = x * 4 → 24
x /= 6 # x = x / 6 → 4.0
6. Identity Operators
• is → returns True if two objects refer to the same memory location.
• is not → returns True if they are not the same.
x = [1,2,3]
y=x
z = [1,2,3]
print(x is y) # True
print(x is z) # False (different memory)

7. Membership Operators
• in → checks if element exists.
• not in → checks if element doesn’t exist.
nums = [1,2,3,4]
print(2 in nums) # True
print(5 not in nums) # True

❖BLOCKS IN PYTHON
• A block is a group of statements that are executed together.
• In Python, blocks are defined by indentation (spaces or tabs) instead
of {} like in C, C++, or Java.
• Example: functions, loops, if-else statements all contain blocks.
# Example of block inside if
x = 10
if x > 5:
print("x is greater than 5") # Block starts here
print("This also belongs to the same block")
print("Outside the block")
# Not part of if block

❖INDENTATION IN PYTHON
• Indentation means spaces at the beginning of a line.
• In Python, indentation is used to define blocks of code.
• Without proper indentation, Python will give an IndentationError.
• Example
for i in range(3):
print("Hello") # This line is indented → inside loop
print("World") # Same block
print("Done")
# Not indented → outside loop

❖LISTS & LIST SLICING


• A list is a mutable collection of items.
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # apple
fruits[1] = "orange" # update
print(fruits) # ['apple', 'orange', 'cherry']
➢ List Slicing
nums = [10, 20, 30, 40, 50]
print(nums[1:4]) # [20, 30, 40]
print(nums[:3]) # [10, 20, 30]
print(nums[2:]) # [30, 40, 50]
print(nums[::-1]) # [50, 40, 30, 20, 10]
➢ List Methods
[Link](60) # add
[Link](20) # remove
[Link](1,15) # insert
[Link]() # remove last
[Link]() # sort
[Link]() # reverse

❖TUPLE DATA TYPE


• A tuple is an immutable collection.
t = (1, 2, 3, "hello")
print(t[0]) #1
# t[1] = 5 → Error (immutable)
➢ Tuple Operations
print(len(t)) # length
print([Link](2)) # count occurrences
print([Link](3)) # index of element

You might also like