Python basics, data types and control flow — Unit 1 Notes (Python Programming)

BCC302 · Unit 1

Python basics, data types and control flow notes — Unit 1

Free unit-wise study notes on python basics, data types and control flow for Python Programming, Semester 3 of B.Tech — Computer Science & Engineering — key concepts, examples, important questions and a revision checklist for semester exams.

An introduction to Python's syntax and philosophy. Covers the Python interpreter, variable typing, fundamental data types, input/output, and control flow statements (if/elif/else, loops).

Notebook — 14 pages

Page 1

Wink Notes

B.Tech CSE — 3rd Semester

Python Programming

Unit - 1

1. Introduction to Python

Python was created by Guido van Rossum and released in 1991. It is designed to be highly readable, prioritizing programmer productivity over raw execution speed.

1.1 Key Features of Python

  • Interpreted: Python code is executed line-by-line by an interpreter (typically CPython), unlike C/C++ which are compiled into machine code beforehand. This makes debugging easier but execution slower.
  • Dynamically Typed: You don't need to declare variable types (e.g., `int x = 5`). You just write `x = 5`. The interpreter infers the type at runtime.
  • High-Level: Abstracts away memory management. There are no pointers, and garbage collection is automatic.
  • Multi-Paradigm: Supports Procedural, Object-Oriented, and Functional programming styles.
  • "Batteries Included": Python comes with a massive standard library allowing you to do everything from connecting to web servers to reading CSV files without installing third-party packages.

Next — The Python Interpreter

1 of 14

Page 2

Wink Notes

B.Tech CSE — 3rd Semester

Python Programming

Unit - 1

2. The Python Interpreter & Execution

When you run a Python script (`python script.py`), the execution happens in two distinct steps, hidden from the user.

2.1 Compilation to Bytecode

First, the source code (`.py`) is compiled into an intermediate, platform-independent representation called Bytecode (`.pyc`). This bytecode is a lower-level set of instructions.

2.2 The Python Virtual Machine (PVM)

Next, the PVM (which is the actual "interpreter") reads the bytecode line-by-line and translates it into machine code that your specific CPU can execute.

Because the PVM executes bytecode sequentially, Python is slower than compiled C code. To speed it up, heavily mathematical Python libraries (like NumPy) are actually written in C under the hood.

Next — Basic Syntax and Indentation

2 of 14

Page 3

Wink Notes

B.Tech CSE — 3rd Semester

Python Programming

Unit - 1

3. Basic Syntax & Indentation

Python's syntax is strictly enforced and unique compared to C/Java.

3.1 The Rule of Indentation

Python does not use curly braces `{}` to define code blocks (like loops or functions). Instead, it uses whitespace indentation.

```python
if x > 5:
print("Greater") # Indented, belongs to 'if'
x = 0 # Also belongs to 'if'
print("Done") # Unindented, outside the 'if'
```

Standard practice is to use 4 spaces for one level of indentation. Mixing tabs and spaces will cause an `IndentationError`.

3.2 Comments

Single-line comments start with `#`. Python does not have a distinct multi-line comment syntax, but multi-line strings (`'''` or `"""`) are often used as docstrings to serve the same purpose.

Next — Variables and Dynamic Typing

3 of 14

Page 4

Wink Notes

B.Tech CSE — 3rd Semester

Python Programming

Unit - 1

4. Variables and Dynamic Typing

In Python, a variable is not a bucket in memory that holds a value. Instead, a variable is a name (label) attached to an object in memory.

```python
x = 10
x = "Hello"
```

In C, the above would cause a type error. In Python, it is perfectly legal.
1. First, an integer object `10` is created in memory, and the label `x` is attached to it.
2. Then, a string object `"Hello"` is created in memory, and the label `x` is detached from `10` and attached to `"Hello"`.

4.1 Variable Naming Rules

  • Must start with a letter or underscore (`_`).
  • Can contain letters, numbers, and underscores.
  • Case-sensitive (`Age` and `age` are different).
  • Cannot be a Python keyword (e.g., `if`, `while`, `True`).

Next — Fundamental Data Types

4 of 14

Page 5

Wink Notes

B.Tech CSE — 3rd Semester

Python Programming

Unit - 1

5. Fundamental Data Types

You can check the type of any variable using the `type()` function.

5.1 Numeric Types

  • `int`: Integers of arbitrary size. Python automatically allocates more memory for massive numbers, so they never overflow. `x = 1000000000000000000` is completely valid.
  • `float`: Decimal numbers. Implemented as C `double` (IEEE 754 64-bit) under the hood. `y = 3.14`
  • `complex`: Complex numbers. Used heavily in scientific computing. `z = 3 + 4j` (Note the use of `j` instead of `i`).

5.2 Boolean Type

`bool`: Represents `True` or `False` (capitalized!). Inherits from integer; `True` evaluates to 1, and `False` evaluates to 0 in math.

5.3 NoneType

`None`: Represents the absence of a value (similar to `null` in Java/C). Used to initialize an empty variable.

Next — Type Casting

5 of 14

Page 6

Wink Notes

B.Tech CSE — 3rd Semester

Python Programming

Unit - 1

6. Type Casting (Conversion)

Python provides built-in functions to explicitly convert a variable from one data type to another.

6.1 Common Casting Functions

  • `int()`: Converts to integer. `int("5")` 5\to 5. `int(3.9)` 3\to 3 (truncates, does not round).
  • `float()`: Converts to float. `float(5)` 5.0\to 5.0.
  • `str()`: Converts to string. `str(5.5)` "5.5"\to "5.5".
  • `bool()`: Converts to boolean.

6.2 Truthy and Falsy Values

When casting to `bool()`, almost everything evaluates to `True` (Truthy), EXCEPT for a specific set of "Falsy" values:

  • `0`, `0.0` (Numeric zero)
  • `""` (Empty string)
  • `[]`, `()`, `{}` (Empty collections)
  • `None`
  • `False`

This allows concise checks: `if string_var:` instead of `if len(string_var) > 0:`.

Next — Standard Input and Output

6 of 14

Page 7

Wink Notes

B.Tech CSE — 3rd Semester

Python Programming

Unit - 1

7. Standard Input & Output

7.1 Output: The `print()` function

Displays text to the console. By default, it separates multiple arguments with a space, and ends with a newline.

```python
print("Age:", 20) # Output: Age: 20
print("A", "B", sep="-") # Output: A-B
print("Hello", end=" ") # Prevents newline
print("World") # Output: Hello World
```

7.2 Input: The `input()` function

Pauses execution and waits for the user to type something and hit Enter.

```python
name = input("Enter name: ")
```

CRITICAL RULE: `input()` ALWAYS returns a string. If you want the user to enter a number, you MUST cast it immediately:
`age = int(input("Enter age: "))`

Next — Operators: Arithmetic

7 of 14

Page 8

Wink Notes

B.Tech CSE — 3rd Semester

Python Programming

Unit - 1

8. Operators: Arithmetic & Assignment

8.1 Arithmetic Operators

  • `+` (Addition), `-` (Subtraction), `*` (Multiplication)
  • `/` (True Division): Always returns a `float`. E.g., `5 / 2 = 2.5`.
  • `//` (Floor Division): Returns an `int`, chopping off the decimal. E.g., `5 // 2 = 2`.
  • `%` (Modulus): Returns the remainder. E.g., `5 % 2 = 1`.
  • `` (Exponentiation): Power operator. E.g., `2 3 = 8`.

8.2 Assignment Operators

Standard assignment: `x = 5`
Compound assignment: `x += 3` (Equivalent to `x = x + 3`). Works with `-=`, `*=`, `/=`, `//=`, etc.

Note: Python does not have the `++` or `--` operators found in C/Java. You must use `x += 1`.

Next — Operators: Relational & Logical

8 of 14

Page 9

Wink Notes

B.Tech CSE — 3rd Semester

Python Programming

Unit - 1

9. Operators: Relational & Logical

9.1 Relational (Comparison) Operators

Used to compare values. They always return a boolean (`True` or `False`).

  • `==` (Equal to)
  • `!=` (Not equal to)
  • `>`, `<`, `>=`, `<=`

Python allows chained comparisons: `if 0 < x < 10:` is perfectly valid and readable.

9.2 Logical Operators

Used to combine conditional statements. Instead of symbols (`&&`, `||`), Python uses plain English words.

  • `and`: Returns True if BOTH statements are true.
  • `or`: Returns True if AT LEAST ONE statement is true.
  • `not`: Reverses the boolean result. (`not True` \to `False`).

Short-Circuiting: In `A and B`, if A is False, Python doesn't even evaluate B. In `A or B`, if A is True, Python doesn't evaluate B. This saves execution time.

Next — Operators: Membership & Identity

9 of 14

Page 10

Wink Notes

B.Tech CSE — 3rd Semester

Python Programming

Unit - 1

10. Operators: Membership & Identity

10.1 Membership Operators (`in`, `not in`)

Checks if a sequence (like a string or list) contains a specific value.

```python
name = "Alice"
print("A" in name) # True
print("z" not in name) # True
```

10.2 Identity Operators (`is`, `is not`)

Compares the memory location of two objects, not their value. (Equivalent to checking pointer equality in C).

```python
x = [1, 2, 3]
y = [1, 2, 3]
print(x == y) # True (Values are identical)
print(x is y) # False (They are two different lists in memory)

z = x
print(x is z) # True (Both labels point to the same memory location)
```

Next — Control Flow: if/elif/else

10 of 14

Page 11

Wink Notes

B.Tech CSE — 3rd Semester

Python Programming

Unit - 1

11. Control Flow: Conditional Statements

Allow the program to make decisions and execute different code blocks based on conditions.

```python
marks = 85

if marks >= 90:
print("Grade A")
elif marks >= 80:
print("Grade B")
else:
print("Needs Improvement")
```

11.1 Key Syntax Rules

  • Conditions do NOT need to be wrapped in parentheses `()`.
  • The statement must end with a colon `:`.
  • The body of the block MUST be indented.
  • Python uses `elif`, not `else if`.

11.2 Ternary Operator (Conditional Expression)

A one-line shorthand for an `if-else` block.
Syntax: `[Value if True] if [Condition] else [Value if False]`
Example: `status = "Pass" if marks >= 40 else "Fail"`

Next — Control Flow: The `while` Loop

11 of 14

Page 12

Wink Notes

B.Tech CSE — 3rd Semester

Python Programming

Unit - 1

12. Control Flow: The `while` Loop

Executes a block of code repeatedly as long as a condition remains `True`.

```python
count = 0
while count < 3:
print("Counting:", count)
count += 1
```

12.1 The `while-else` construct

Python has a unique feature where an `else` block can be attached to a loop.

The `else` block executes ONLY if the loop finishes its execution naturally (i.e., the condition becomes `False`). If the loop is terminated abruptly by a `break` statement, the `else` block is skipped.

This is extremely useful for search algorithms (e.g., "Search for X in the list. If loop finishes naturally, X wasn't found, so trigger the `else` block to print 'Not Found'").

Next — Control Flow: The `for` Loop

12 of 14

Page 13

Wink Notes

B.Tech CSE — 3rd Semester

Python Programming

Unit - 1

13. Control Flow: The `for` Loop

Unlike C/Java where a `for` loop is basically a glorified `while` loop with a counter, Python's `for` loop acts strictly as an iterator over a sequence (like a string, list, or range).

13.1 Iterating over a sequence

```python
name = "Wink"
for letter in name:
print(letter) # Prints W, i, n, k on separate lines
```

13.2 The `range()` function

To loop a specific number of times, use `range(start, stop, step)`.
- `stop` is exclusive.
- `start` defaults to 0.
- `step` defaults to 1.

```python
for i in range(5): # 0, 1, 2, 3, 4
for i in range(2, 6): # 2, 3, 4, 5
for i in range(10, 0, -2): # 10, 8, 6, 4, 2
```

Next — Loop Control Statements

13 of 14

Page 14

Wink Notes

B.Tech CSE — 3rd Semester

Python Programming

Unit - 1

14. Loop Control Statements

Used to alter the normal flow of a loop.

  • `break`: Instantly terminates the loop entirely. Execution jumps to the first line after the loop.
  • `continue`: Skips the rest of the current iteration. Execution jumps immediately back to the top of the loop for the next iteration.
  • `pass`: A null statement. It literally does nothing. Used as a placeholder when the syntax requires a block of code, but you haven't written it yet (e.g., an empty function or an empty `if` block).

Summary Checklist

  • Explain the difference between `is` (identity) and `==` (equality).
  • What is the output of `5 // 2` versus `5 / 2`?
  • Explain the concept of "Truthy" and "Falsy" values.
  • Write a `for` loop using `range()` to print all even numbers from 100 down to 0.
  • Explain how the `else` block works when attached to a `while` loop.

14 of 14

Continue in this subject