Chapters
- 1.Computer System Organization
- 2.Data Representation and Boolean Logic
- 3.Getting Started With Python
- 4.Python Programming Fundamentals
- 5.Conditional And Looping Construct
- 6.Strings Manipulation In Python
- 7.List Manipulation In Python
- 8.Tuples and Dictionary
- 9.Introduction to Python Modules
- 10.Society, Law and Ethics
Chapter 3: Getting Started with Python
Introduction to Python
Python is a high-level, interpreted, general-purpose programming language created by Guido van Rossum in 1991. It emphasizes code readability and simplicity, making it ideal for beginners and professionals alike.
Key Characteristics of Python:
- Simple and readable: Code reads like English
- Interpreted: Code is executed line by line
- High-level: Abstracts complex details automatically
- Case-sensitive: Python and python are different
- Platform-independent: Runs on any OS with Python installed
Advantages of Python
- Easy to learn: Simple syntax similar to English
- Free and open source: No cost to download and use
- Large community: Extensive support and resources
- Versatile: Used in web development, AI, data science, automation
- Rich libraries: Thousands of pre-built modules available
- Cross-platform: Works on Windows, macOS, Linux
Disadvantages of Python
- Slower execution: Being interpreted, it's slower than compiled languages like C++
- Memory consumption: Uses more memory than languages like C
- Mobile development: Not suitable for mobile app development
- Runtime errors: Errors caught only at runtime, not compile time
- Indentation dependency: Incorrect indentation causes errors
Installing Python
Downloading Python
- Visit www.python.org
- Click on 'Downloads' menu
- Select your Operating System (Windows, macOS, Linux)
- Download the latest stable version (3.x)
- Choose between 32-bit or 64-bit based on your system
Installation on Windows
- Double-click the downloaded installer (.exe file)
- Check 'Add Python 3.x to PATH' (IMPORTANT!)
- Click 'Install Now' or customize installation
- Wait for installation to complete
- Click 'Close' when finished
Important: Always check 'Add Python to PATH' during installation. This allows you to run Python from command prompt.
Verifying Installation
In Command Prompt/Terminal, type:
python --version
If installed correctly, it will show the Python version (e.g., Python 3.12.0)
Python Interactive Shell (IDLE)
IDLE is Python's Integrated Development and Learning Environment, included with Python installation.
To open IDLE:
- Windows: Search 'IDLE' in Start Menu and click
- Or open Command Prompt and type:
idle
Writing Your First Program
In IDLE Interactive Mode:
>>> print("Hello, World!")
Hello, World!
>>>Creating a Python Script File:
- Open IDLE and go to File → New File
- Type your code:
print("Hello, World!") - Save the file with .py extension (e.g., first_program.py)
- Run by pressing F5 or Run → Run Module
Python Syntax and Structure
Python Character Set
The set of valid characters that Python recognizes:
- Letters: A-Z, a-z (English alphabets)
- Digits: 0-9
- Special Characters: + - * / = ( ) [ ] : ; , . ! ? @ # $ % ^ & ~
- Whitespace: Space, Tab, Newline
Tokens
Smallest meaningful units in Python code:
1. Keywords (Reserved Words)
Words with special meaning to Python compiler. Cannot be used as variable names.
and, or, not, if, else, elif, while, for, break, continue, def, class, import, from, return, pass, try, except, finally, with, True, False, None, in, is, lambda, yield, assert, del, global, nonlocal, raise, etc.
2. Identifiers
Names given to variables, functions, classes, and modules.
Rules for Identifiers:
- Must start with letter or underscore (_), not a digit
- Can contain letters, digits, and underscores
- Case-sensitive: Name, name, and NAME are different
- No spaces allowed
- Cannot be Python keywords
Valid identifiers: name, _name, name123, myVariable, MY_CONSTANT
Invalid identifiers: 123name, my-var, my var, if, class
3. Literals
Fixed values written directly in code: 10, 3.14, "Hello", True
4. Operators
Symbols for operations: +, -, *, /, =, ==, !=, etc.
5. Delimiters
Special characters: ( ) [ ] , : . ; @ # $ % & ^ ~ !
Indentation
Python uses indentation (whitespace at the beginning of lines) to define code blocks. This replaces curly braces used in other languages.
if True:
print("This is indented") # 4 spaces
print("Same block")
print("Outside block")Important: Use consistent indentation (typically 4 spaces). Mixing tabs and spaces causes errors.
Variables in Python
A variable is a name that refers to a memory location where data is stored. In Python, you don't need to declare variable types - Python automatically determines the type.
Variable Assignment
name = "John" # String variable age = 25 # Integer variable height = 5.9 # Float variable is_student = True # Boolean variable # Multiple assignment x = y = z = 10 # All three get value 10 a, b, c = 1, 2, 3 # a=1, b=2, c=3
Dynamic Typing
Python variables can change type during execution:
x = 10 # x is an integer x = "Hello" # x is now a string x = 3.14 # x is now a float
Data Types in Python
1. Numeric Types
- int (Integer): Whole numbers without decimal (10, -5, 0)
- float (Floating-point): Numbers with decimal (3.14, -2.5, 0.0)
- complex: Numbers with real and imaginary parts (3+4j)
2. String (str)
Sequence of characters enclosed in quotes:
name = "Python" # Double quotes lang = 'Python' # Single quotes text = """Multi line string""" # Triple quotes
3. Boolean (bool)
Represents True or False values. Used in conditional statements.
4. None Type
Represents absence of value or null value: x = None
5. Sequence Types
- List: Ordered, mutable collection [1, 2, 3]
- Tuple: Ordered, immutable collection (1, 2, 3)
- Range: Sequence of numbers range(1, 10)
6. Mapping Type
Dictionary (dict): Key-value pairs {"name": "John", "age": 25}
7. Set Types
- Set: Unordered, unique elements {1, 2, 3}
- Frozenset: Immutable set
Type Checking and Conversion
# Check type
type(10) # <class 'int'>
type("Hello") # <class 'str'>
# Type conversion
int("25") # Converts string to int: 25
str(100) # Converts int to string: "100"
float(10) # Converts int to float: 10.0Operators in Python
1. Arithmetic Operators
| Operator | Name | Example | Result |
|---|---|---|---|
| + | Addition | 10 + 3 | 13 |
| - | Subtraction | 10 - 3 | 7 |
| * | Multiplication | 10 * 3 | 30 |
| / | Division | 10 / 3 | 3.333... |
| // | Floor Division | 10 // 3 | 3 |
| % | Modulus | 10 % 3 | 1 |
| ** | Exponent | 10 ** 3 | 1000 |
2. Comparison (Relational) Operators
| Operator | Name | Example | Result |
|---|---|---|---|
| == | Equal | 5 == 5 | True |
| != | Not equal | 5 != 3 | True |
| > | Greater than | 5 > 3 | True |
| < | Less than | 5 < 3 | False |
| >= | Greater or equal | 5 >= 5 | True |
| <= | Less or equal | 5 <= 3 | False |
3. Logical Operators
- and: Returns True if both conditions are True
- or: Returns True if at least one condition is True
- not: Reverses the Boolean value
4. Assignment Operators
- = Simple assignment (x = 10)
- += Add and assign (x += 5 means x = x + 5)
- -= Subtract and assign
- *= Multiply and assign
- /= Divide and assign
- //= Floor divide and assign
- %= Modulus and assign
- **= Exponent and assign
5. Identity Operators
- is: Returns True if both variables refer to same object
- is not: Returns True if variables refer to different objects
6. Membership Operators
- in: Returns True if value exists in sequence
- not in: Returns True if value does not exist in sequence
Input and Output
Output: print() Function
print("Hello, World!")
print("Name:", "John") # Multiple values
print("Age:", 25, sep="-") # Custom separator
print("Line1", end=" ") # Custom end character
print("Line2")Input: input() Function
The input() function always returns a string:
name = input("Enter your name: ")
age = int(input("Enter your age: ")) # Convert to integer
marks = float(input("Enter marks: ")) # Convert to floatComments in Python
Comments are used to explain code and are ignored by the interpreter.
Single-line Comments
# This is a single-line comment x = 10 # This is an inline comment
Multi-line Comments
""" This is a multi-line comment Also called docstring when used at the beginning of a function """
Debugging in Python
Debugging is the process of finding and fixing errors (bugs) in code.
Types of Errors
1. Syntax Errors
Errors in code structure that prevent execution:
print("Hello" # Missing closing parenthesis
if x == 5 # Missing colon2. Runtime Errors
Errors that occur during execution:
x = 10 / 0 # Division by zero print(name) # NameError: variable not defined
3. Logical Errors
Code runs but produces incorrect results:
# Intended: average of a and b average = a + b / 2 # Wrong: should be (a + b) / 2