0% found this document useful (0 votes)
77 views34 pages

Chapter 7

This document provides a comprehensive guide to the basics of Python programming, covering foundational concepts such as data types, control structures, functions, and libraries. It includes practical examples and explanations for using the Python interpreter, debugging techniques, and the use of built-in data types like lists and tuples. Additionally, it introduces popular libraries like NumPy, Pandas, and Matplotlib for data manipulation and visualization.

Uploaded by

deena rsd
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)
77 views34 pages

Chapter 7

This document provides a comprehensive guide to the basics of Python programming, covering foundational concepts such as data types, control structures, functions, and libraries. It includes practical examples and explanations for using the Python interpreter, debugging techniques, and the use of built-in data types like lists and tuples. Additionally, it introduces popular libraries like NumPy, Pandas, and Matplotlib for data manipulation and visualization.

Uploaded by

deena rsd
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
You are on page 1/ 34

Python Programming Basics

1. Introduction

Python is a high-level, interpreted, and dynamically typed programming language


known for its simplicity and readability. This guide covers the foundational concepts of Python
programming as specified in the syllabus, including interpreter usage, debugging, data types,
control structures, functions, strings, lists, tuples, dictionaries, libraries, and advanced list
processing. Each section includes explanations and practical examples to provide a solid
understanding.

2. Python Interpreter and Interactive Mode

• Interpreter:

o Executes Python code line by line, unlike compiled languages like C++.

o Run scripts using python filename.py or interactively via the terminal.

o Example:

o # Run in terminal: python

o >>> print("Hello, World!")

o Hello, World!

• Interactive Mode:

o Launch by typing python or python3 in the terminal.

o Allows immediate execution of Python statements, ideal for testing code


snippets.

o Example:

o >>> x = 5

o >>> x * 2

o 10

• IDLE:

o Python’s built-in Integrated Development and Learning Environment.

1
o Supports editing, running, and debugging Python code.

o Example: Open IDLE, write print("Hello, World!"), and run to see output.

• Key Points:

o Interactive mode is great for learning and quick prototyping.

o Use scripts for larger programs, executed via the interpreter.

3. Debugging

• Definition: The process of identifying and fixing errors (bugs) in code.

• Techniques:

o Print Statements: Insert print() to inspect variable values.

o x = 10

o print(f"Value of x: {x}") # Debugging output

o pdb Module: Python’s built-in debugger for setting breakpoints and stepping
through code.

o import pdb

o x=5

o pdb.set_trace() # Pause execution, inspect variables

o y=x*2

o print(y)

▪ Commands in pdb: n (next), s (step into), c (continue), q (quit).

o IDE Debugging: Tools like PyCharm or VS Code offer graphical debugging


with breakpoints and variable inspection.

• Key Points:

o Use pdb for complex debugging; print() for quick checks.

o Modern IDEs simplify debugging with visual tools.

2
4. Values and Types

Python supports several built-in data types, each with specific characteristics and operations.

• Integer (int):

o Whole numbers (e.g., 5, -2).

o Unlimited precision in Python 3.

o Example: x = 42

• Float (float):

o Decimal numbers (e.g., 3.14, -0.001).

o Follows IEEE 754 standard, may have precision issues.

o Example: pi = 3.14159

• Boolean (bool):

o Represents True or False.

o Used in logical operations.

o Example: is_valid = True

• String (str):

o Sequence of characters (e.g., "hello", 'world').

o Enclosed in single (') or double (") quotes.

o Example: name = "Alice"

• List (list):

o Ordered, mutable collection (e.g., [1, 2, 3], ["a", "b"]).

o Example: numbers = [1, 2, 3]

• Key Points:

o Types are dynamically assigned; no explicit declaration needed.

o Use type() to check a variable’s type: print(type(42)) → <class 'int'>.

3
5. Variables, Expressions, Statements

• Variables:

o Names that store data, assigned using =.

o Dynamically typed; type inferred from value.

o Example:

o x = 10 # Integer

o name = "Bob" # String

• Expressions:

o Combinations of values, variables, and operators that evaluate to a value.

o Example: x + 5 evaluates to 15 if x = 10.

• Statements:

o Instructions executed by the interpreter (e.g., assignments, loops, conditionals).

o Example:

o x = 10 # Assignment statement

o print(x * 2) # Print statement

6. Tuple Assignment

• Definition: Assign multiple values to multiple variables in a single statement using


tuples.

• Syntax: (var1, var2) = (value1, value2) or var1, var2 = value1, value2.

• Example:

• a, b = 1, 2 # Assigns a=1, b=2

• x, y = y, x # Swaps values

• print(a, b) # 1 2

• Use Case: Unpacking values from a tuple or list, swapping variables, or returning
multiple values from functions.

4
• Key Points:

o Number of variables must match number of values.

o Can unpack iterables: x, y = [10, 20].

7. Precedence of Operators

• Definition: Determines the order in which operators are evaluated in an expression.

• Order (highest to lowest):

o Parentheses: ()

o Exponentiation:

o Multiplication/Division: *, /, // (floor division), % (modulus)

o Addition/Subtraction: +, -

o Comparison: ==, !=, <, >, <=, >=, is

o Logical: not, and, or

• Example:

• result = 2 + 3 * 4 # * has higher precedence: 2 + (3 * 4) = 14

• result = (2 + 3) * 4 # Parentheses override: (2 + 3) * 4 = 20

• print(result) # 20

• Key Points:

o Use parentheses to enforce desired evaluation order.

o Logical operators have lowest precedence, evaluated last.

8. Comments

• Definition: Annotations in code ignored by the interpreter, used for documentation or


explanation.

• Types:

o Single-line: Start with #.

o # This is a comment

5
o x = 5 # Assign 5 to x

o Multi-line: Use triple quotes (''' or """) as docstrings or comments.

o """

o This is a multi-line comment

o or docstring for a function/class

o """

o def my_func():

o pass

• Key Points:

o Docstrings are used for function/class documentation, accessible via __doc__.

o Comments improve code readability but should not state the obvious.

9. Python Libraries

Python’s standard and third-party libraries extend functionality for numerical, data, and
visualization tasks.

9.1 NumPy

• Purpose: Numerical operations with powerful N-dimensional arrays.

• Key Features:

o Fast array operations, broadcasting, linear algebra.

o Example:

o import numpy as np

o a = np.array([1, 2, 3])

o print(a + 5) # [6 7 8]

• Use Case: Matrix computations, scientific simulations.

9.2 Pandas

• Purpose: Data analysis with DataFrames and Series.

6
• Key Features:

o Data manipulation, filtering, grouping, merging.

o Example:

o import pandas as pd

o df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})

o print(df)

o # A B

o #0 1 3

o #1 2 4

• Use Case: Data cleaning, analysis, CSV/Excel processing.

9.3 Matplotlib

• Purpose: Visualization and plotting.

• Key Features:

o Line plots, scatter plots, histograms, etc.

o Example:

o import matplotlib.pyplot as plt

o plt.plot([1, 2, 3], [4, 5, 6])

o plt.xlabel("X")

o plt.ylabel("Y")

o plt.show() # Displays a line plot

• Use Case: Data visualization, scientific plotting.

9.4 SciPy

• Purpose: Scientific computing (optimization, interpolation, integration).

• Key Features:

7
o Builds on NumPy for advanced math functions.

o Example:

o from scipy import optimize

o def f(x): return x2 + 10

o result = optimize.minimize(f, 0)

o print(result.x) # Minimizes x^2 + 10

• Use Case: Solving equations, statistical analysis.

10. Conditionals and Iteration

10.1 Conditionals

• Boolean Values: True, False.

• Operators:

o Comparison: ==, !=, <, >, <=, >=.

o Logical: and, or, not.

• Conditional Statements: if, elif, else.

o Example:

o x = 10

o if x > 0:

o print("Positive")

o elif x == 0:

o print("Zero")

o else:

o print("Negative")

• Key Points:

o Indentation defines block scope (typically 4 spaces).

8
o Conditions evaluate to True or False.

10.2 Iteration

• while Loop:

o Repeats while a condition is true.

o Example:

o i=0

o while i < 5:

o print(i) # 0 1 2 3 4

o i += 1

• for Loop:

o Iterates over a sequence (e.g., list, range).

o Example:

o for item in [1, 2, 3]:

o print(item) # 1 2 3

o for i in range(5):

o print(i) # 0 1 2 3 4

• break and continue:

o break: Exits the loop.

o continue: Skips to the next iteration.

o Example:

o for x in range(10):

o if x == 5:

o break # Stops at 5

o if x % 2 == 0:

9
o continue # Skips even numbers

o print(x) # 1 3

11. Functions

• Definition: Reusable code blocks defined with def.

• Syntax:

• def function_name(parameters):

• # Body

• return value # Optional

• Types:

o Positional Parameters: Required, in order.

o Default Parameters: Optional, with default values.

o Keyword Parameters: Specified by name.

o Variable-length Parameters: *args (positional), kwargs (keyword).

• Example:

• def add(a, b=0): # Default parameter

• return a + b

• print(add(5)) # 5 (uses default b=0)

• print(add(5, 3)) # 8

• def print_info(kwargs):

• print(kwargs)

• print_info(name="Alice", age=25) # {'name': 'Alice', 'age': 25}

• Scope:

o Local: Variables defined inside a function.

o Global: Variables defined outside, accessed with global keyword.

10
o Example:

o x = 10

o def foo():

o global x

o x = 5 # Modifies global x

o foo()

o print(x) # 5

• Function Composition: Using functions as arguments or return values.

o Example:

o def apply(func, x):

o return func(x)

o def square(x):

o return x * x

o print(apply(square, 4)) # 16

• Recursion: Function calling itself.

o Example:

o def factorial(n):

o if n == 0:

o return 1

o return n * factorial(n - 1)

o print(factorial(5)) # 120

12. Strings

• Definition: Immutable sequences of characters.

• Slices: Access substrings using [start:end:step].

11
o Example:

o s = "Hello"

o print(s[1:4]) # ell

o print(s[::-1]) # olleH (reverse)

• Immutability: Strings cannot be modified in place.

o Example:

o s = "Hello"

o # s[0] = 'h' # Error: strings are immutable

o s = s.lower() # Creates new string

o print(s) # hello

• String Methods:

o lower(), upper(), find(), replace(), strip(), split(), join().

o Example:

o s = " Hello World "

o print(s.strip()) # Hello World

o print(s.split()) # ['Hello', 'World']

• String Module:

o Provides constants like string.ascii_letters.

o Example:

o import string

o print(string.ascii_letters) #
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ

13. Lists

• Definition: Ordered, mutable collections, usable as arrays.

• Operations:

12
o append(), remove(), pop(), insert(), extend().

o Example:

o a = [1, 2, 3]

o a.append(4) # [1, 2, 3, 4]

o a.pop() # [1, 2, 3]

o print(a)

• Slices:

o Example:

o a = [1, 2, 3, 4, 5]

o print(a[1:3]) # [2, 3]

• Methods:

o sort(), reverse(), index(), count().

o Example:

o a = [3, 1, 2]

o a.sort() # [1, 2, 3]

o print(a)

• Loops:

o Example:

o a = [1, 2, 3]

o for element in a:

o print(element) # 1 2 3

• Mutability: Lists can be modified in place.

o Example:

o a = [1, 2, 3]

13
o a[0] = 10 # [10, 2, 3]

• Aliasing: Multiple variables referencing the same list.

o Example:

o a = [1, 2, 3]

o b = a # Alias

o b[0] = 10

o print(a) # [10, 2, 3]

• Cloning: Create a copy using slicing or copy().

o Example:

o a = [1, 2, 3]

o b = a[:] # Clone

o b[0] = 10

o print(a) # [1, 2, 3]

• List Parameters: Lists passed to functions are mutable.

o Example:

o def modify_list(lst):

o lst.append(4)

o a = [1, 2, 3]

o modify_list(a)

o print(a) # [1, 2, 3, 4]

14. Tuples

• Definition: Ordered, immutable collections.

• Tuple Assignment:

o Example:

14
o x, y = (1, 2) # x=1, y=2

o print(x, y)

• Tuples as Return Values:

o Example:

o def get_coords():

o return (10, 20)

o x, y = get_coords()

o print(x, y) # 10 20

• Key Points:

o Immutable: t[0] = 5 raises an error.

o Lightweight compared to lists, used for fixed data.

15. Dictionaries

• Definition: Mutable, unordered collections of key-value pairs.

• Operations:

o Add/update: d[key] = value.

o Access: d[key].

o Delete: del d[key], d.pop(key).

• Methods:

o keys(), values(), items(), get(), update().

o Example:

o d = {'a': 1, 'b': 2}

o d['c'] = 3

o print(d.keys()) # dict_keys(['a', 'b', 'c'])

o print(d.get('a')) # 1

15
• Key Points:

o Keys must be immutable (e.g., strings, numbers, tuples).

o get() is safer than d[key] (returns None if key is missing).

16. Advanced List Processing

16.1 Iterators

• Definition: Objects that enable traversal of containers (e.g., lists, dictionaries).

• Example:

• lst = [1, 2, 3]

• it = iter(lst)

• print(next(it)) # 1

• print(next(it)) # 2

• Use Case: Manual iteration or custom traversal logic.

16.2 Generators

• Definition: Functions that yield values one at a time using yield, conserving memory.

• Example:

• def count():

• i=0

• while True:

• yield i

• i += 1

• gen = count()

• print(next(gen)) # 0

• print(next(gen)) # 1

• Use Case: Processing large datasets or infinite sequences.

16
17. Practical Example

• Description: Filter even numbers from a list using a list comprehension.

• Code:

• def filter_even(numbers):

• return [n for n in numbers if n % 2 == 0]

• nums = [1, 2, 3, 4, 5, 6]

• evens = filter_even(nums)

• print(evens) # [2, 4, 6]

18. Comprehensive Example Program

This program combines multiple concepts from the syllabus:

import numpy as np

import pandas as pd

import matplotlib.pyplot as plt

# Function with recursion and tuple return

def min_max(numbers):

if not numbers:

return None, None

return min(numbers), max(numbers)

# Main program

def main():

# Variables and types

x = 10 # int

17
pi = 3.14 # float

is_valid = True # bool

name = "Alice" # str

lst = [1, 2, 3, 4] # list

# Tuple assignment

min_val, max_val = min_max(lst)

print(f"Min: {min_val}, Max: {max_val}") # Min: 1, Max: 4

# Conditional

if x > 0:

print("x is positive")

# Iteration

for i in range(5):

if i % 2 == 0:

continue

print(i) # 1 3

# String operations

s = "Hello, World!"

print(s[0:5]) # Hello

print(s.upper()) # HELLO, WORLD!

18
# List operations

lst.append(5)

print(lst[1:3]) # [2, 3]

lst_clone = lst[:] # Cloning

lst_clone[0] = 10

print(f"Original: {lst}, Clone: {lst_clone}") # Original: [1, 2, 3, 4, 5], Clone: [10, 2, 3, 4, 5]

# Dictionary

d = {'name': 'Alice', 'age': 25}

print(d.get('name')) # Alice

# NumPy

arr = np.array([1, 2, 3])

print(arr * 2) # [2 4 6]

# Pandas

df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})

print(df)

# Matplotlib

plt.plot([1, 2, 3], [4, 5, 6])

plt.xlabel("X")

plt.ylabel("Y")

plt.show()

19
if __name__ == "__main__":

main()

Output:

Min: 1, Max: 4

x is positive

Hello

HELLO, WORLD!

[2, 3]

Original: [1, 2, 3, 4, 5], Clone: [10, 2, 3, 4, 5]

Alice

[2 4 6]

A B

0 1 3

1 2 4

[Displays a line plot]

19. Key Issues in Python Programming

1. Dynamic Typing:

o Pros: Flexibility, no type declarations.

o Cons: Risk of runtime type errors; use isinstance() for checks.

2. Mutability:

o Lists and dictionaries are mutable, leading to aliasing issues.

20
o Use cloning ([:], copy()) to avoid unintended changes.

3. Performance:

o Interpreted nature makes Python slower than compiled languages like C++.

o Use NumPy/SciPy for performance-critical numerical tasks.

4. Indentation:

o Python relies on indentation for scope, unlike braces in C++.

o Inconsistent indentation (e.g., mixing tabs and spaces) causes errors.

5. Library Dependencies:

o Libraries like NumPy, Pandas require installation (pip install numpy).

o Ensure compatible versions for interoperability.

6. Error Handling:

o Use try/except for robust error handling (not covered in the syllabus but
recommended).

o Example:

o try:

o x=1/0

o except ZeroDivisionError:

o print("Cannot divide by zero")

21
Multiple Choice Questions

1. What type of language is Python?

A) Low-level

B) High-level

C) Assembly-level

D) Machine-level

2. How does Python execute code?

A) Compiles to machine code

B) Line-by-line interpretation

C) Transpiles to Java

D) Batch compilation

3. Which of the following starts the Python interactive shell?

A) python run

B) python3 script.py

C) python or python3

D) py start

4. What is the correct file extension for Python files?

A) .pt

B) .py

C) .pyt

D) .pn

22
5. Which tool is the default IDE provided with Python?

A) Eclipse

B) IDLE

C) Jupyter

D) PyDev

6. Which of the following executes a Python script?

A) python filename.py

B) run python.py

C) exec python file

D) py run filename

7. What does the `print()` function do?

A) Reads input

B) Prints output to screen

C) Executes code

D) Declares variables

8. Which data type represents decimal numbers?

A) int

B) bool

C) float

D) str

23
9. Which data type represents text?

A) int

B) str

C) bool

D) list

10. How do you find the type of a variable `x`?

A) typeof(x)

B) type(x)

C) var(x)

D) istype(x)

11. Which symbol is used for a comment in Python?

A) //

B) /\*

C) #

D) --

12. What is the result of `type(42)`?

A) \<type 'float'>

B) \<class 'int'>

C) int

D) integer

24
13. Which is a correct tuple assignment?

A) a, b := 1, 2

B) a = b = (1, 2)

C) a, b = 1, 2

D) a b = 1 2

14. Which keyword defines a function?

A) fun

B) define

C) function

D) def

15. How do you call a function named `greet`?

A) greet{}

B) call greet()

C) greet()

D) run.greet()

16. What is the use of `return` in a function?

A) Stop the function

B) Print output

C) Exit script

D) Return a value

25
17. Which of the following is a valid list?

A) (1, 2, 3)

B) {1, 2, 3}

C) \[1, 2, 3]

D) <1, 2, 3>

18. What is the output of `print(len("Python"))`?

A) 7

B) 5

C) 6

D) Error

19. Which of the following is mutable?

A) int

B) str

C) tuple

D) list

20. What is aliasing in lists?

A) Cloning a list

B) Copying by value

C) Sharing the same reference

D) Creating a new list

26
21. Which operator has highest precedence?

A) +

B) \*

C) \*\*

D) ==

22. What is the output of `2 + 3 * 4`?

A) 20

B) 14

C) 24

D) 10

23. What does the `pdb` module do?

A) Installs packages

B) Debugs code

C) Creates virtual environments

D) Measures performance

24. Which method adds an item to a list?

A) add()

B) insert()

C) append()

D) extend()

27
25. Which function returns an iterator object?

A) iter()

B) next()

C) range()

D) list()

26. What does `yield` do in a function?

A) Returns all values at once

B) Returns and pauses

C) Stops execution

D) Defines constants

27. What is a generator in Python?

A) Class instance

B) Function with return

C) Function using yield

D) Iterable object

28. What is the result of `print("Python"[::-1])`?

A) nohtyP

B) Pyt

C) Python

D) Error

28
29. What does `split()` do to a string?

A) Combines characters

B) Divides string into list

C) Converts string to int

D) Removes spaces

30. Which function changes string to lowercase?

A) lower()

B) downcase()

C) small()

D) toLower()

31. What is `kwargs` used for?

A) Positional arguments

B) List unpacking

C) Arbitrary keyword arguments

D) Return values

32. What is the correct way to clone a list `a`?

A) b = a

B) b = copy(a)

C) b = a\[:]

D) b = clone(a)

29
33. How do you declare an empty dictionary?

A) \[]

B) {}

C) dict()

D) Both B and C

34. What does `get()` do in dictionaries?

A) Deletes a key

B) Returns default if key not found

C) Sorts dictionary

D) Updates dictionary

35. What will `del d['key']` do?

A) Delete the dictionary

B) Add key to dictionary

C) Delete key from dictionary

D) Print key

36. Which key types are valid in a dictionary?

A) Mutable only

B) Any type

C) Immutable types only

D) Strings only

30
37. What is the purpose of NumPy?

A) Web scraping

B) Scientific plotting

C) Numerical operations

D) GUI development

38. What is the purpose of Pandas?

A) Game development

B) GUI handling

C) Data analysis

D) Animation

39. Which object does Pandas use for tabular data?

A) Series

B) Table

C) DataList

D) DataFrame

40. What is `matplotlib.pyplot` used for?

A) Machine learning

B) Plotting graphs

C) File operations

D) Network sockets

31
41. What does `plt.show()` do?

A) Save graph

B) Export image

C) Display graph

D) Pause execution

42. Which library builds on NumPy for scientific computing?

A) Pandas

B) SciPy

C) Seaborn

D) Matplotlib

\*\*43. What does the following code return?

`def f(): return 5`

`print(f())`

\*\*

A) f

B) None

C) 5

D) Error

32
44. What is recursion?

A) Function repeating another

B) Function calling itself

C) Loop within loop

D) Self-executing code

45. What is the base case in recursion?

A) First iteration

B) Infinite condition

C) Stopping condition

D) None of the above

46. How many arguments can a Python function accept?

A) One

B) Unlimited

C) Only three

D) Zero only

47. What is the result of `range(3)`?

A) \[1, 2, 3]

B) \[0, 1, 2]

C) \[1, 2]

D) \[0, 1, 2, 3]

33
48. What is `__doc__` used for?

A) Execute script

B) Return author info

C) Access docstring

D) Return error

49. Which structure defines block scope in Python?

A) Braces {}

B) Semicolons ;

C) Tabs and spaces

D) Parentheses ()

50. What is the default step in slicing like `s[::]`?

A) 1

B) 0

C) -1

D) 2

34

You might also like