0% found this document useful (0 votes)
5 views9 pages

Python Worksheets UnitI

This document provides Python programming worksheets for B.Tech first-year students, covering an introduction to Python, its parts, and control flow statements. It includes learning objectives, theory notes, practice exercises, and review questions for each unit. Key topics include Python's history, installation of Anaconda and Jupyter Notebook, data types, control flow statements, and exception handling.

Uploaded by

jbbala
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views9 pages

Python Worksheets UnitI

This document provides Python programming worksheets for B.Tech first-year students, covering an introduction to Python, its parts, and control flow statements. It includes learning objectives, theory notes, practice exercises, and review questions for each unit. Key topics include Python's history, installation of Anaconda and Jupyter Notebook, data types, control flow statements, and exception handling.

Uploaded by

jbbala
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Python Programming Worksheets

For [Link] First-Year Students (Beginner Level)


Unit I: Introduction | Parts of Python | Control Flow Statements

UNIT I – Part A: Introduction to Python

A.1 Learning Objectives


• Trace the origin and evolution of the Python language
• Identify the major application (thrust) areas of Python
• Install the Anaconda Python distribution
• Install and use Jupyter Notebook for writing and running Python code

A.2 Theory Notes


A. History of Python Programming Language
Python was created by Guido van Rossum and first released in 1991 at CWI, Netherlands. It was designed as
a successor to the ABC language, with an emphasis on code readability. Key milestones:

Version Year Significance


Python 0.9.0 1991 First public release
Python 1.0 1994 Added functional programming
tools (lambda, map, filter, reduce)
Python 2.0 2000 Introduced list comprehensions,
garbage collection
Python 3.0 2008 Major redesign; not fully backward
compatible with Python 2
Python 3.x 2008–present Current actively maintained series
(e.g., 3.10, 3.11, 3.12)

The name 'Python' was inspired by the British comedy series 'Monty Python's Flying Circus', not the snake.

B. Thrust Areas of Python


Python's simplicity and rich ecosystem of libraries make it popular across many domains:
• Data Science and Data Analysis (NumPy, Pandas)
• Machine Learning and Artificial Intelligence (scikit-learn, TensorFlow, PyTorch)
• Web Development (Django, Flask)
• Automation and Scripting
• Scientific and Numeric Computing (SciPy, SymPy)
• Game Development (Pygame)
• Internet of Things (IoT) and Embedded Systems (MicroPython)
• Cybersecurity and Ethical Hacking (scripting, penetration-testing tools)

C. Installing Anaconda Python Distribution


Anaconda is a free, open-source distribution of Python (and R) that bundles hundreds of data-science
packages and the 'conda' package/environment manager.
1. Visit the official Anaconda website and download the installer for your operating system
(Windows/macOS/Linux)
2. Run the installer and follow the setup wizard (accept license, choose install location)
3. Optionally add Anaconda to the system PATH during installation (or use the Anaconda Prompt instead)
4. Verify installation by opening 'Anaconda Prompt' (or terminal) and typing: conda --version
5. Launch 'Anaconda Navigator' to access Jupyter Notebook, Spyder, and other bundled tools graphically

D. Installing and Using Jupyter Notebook


Jupyter Notebook is a web-based interactive environment for writing and running Python code in 'cells',
mixing code, output, and formatted text (Markdown).
Installation:

# Jupyter is installed automatically with Anaconda.


# To install separately using pip:
pip install notebook

Launching Jupyter Notebook:

# From Anaconda Prompt / terminal:


jupyter notebook
# This opens the Jupyter dashboard in your default web browser.

Basic usage:
• Click 'New' → 'Python 3' to create a new notebook (.ipynb file)
• Type code into a cell and press Shift+Enter to execute it
• Change a cell to 'Markdown' type to add formatted notes/headings
• Use 'File' → 'Save and Checkpoint' to save your work
• Use 'Kernel' → 'Restart & Run All' to re-run the notebook from scratch

A.3 Practice Exercises


6. Prepare a short timeline (5–6 points) of Python's version history from 1991 to the present.
7. List five real-world applications or companies that use Python, and identify which 'thrust area' each
belongs to.
8. Install Anaconda on your system and note down the conda and python versions using 'conda --version'
and 'python --version'.
9. Open Jupyter Notebook, create a new notebook, and write a cell that prints 'Hello, Python!'. Add a
Markdown cell above it with a heading describing the exercise.
10. Create a notebook with three cells: one Markdown title cell, one code cell computing the sum of 1 to
10, and one code cell printing the result with a formatted message.

A.4 Review Questions


11. Who created Python, and in which year was it first released?
12. Name any four thrust areas where Python is widely used and briefly justify why Python suits each.
13. What is Anaconda, and why is it preferred by beginners and data scientists over a plain Python
installation?
14. What is a Jupyter Notebook, and how does it differ from writing Python code in a plain text editor and
running it from the command line?
15. What keyboard shortcut is used to execute a cell in Jupyter Notebook?
UNIT I – Part B: Parts of Python Programming Language

B.1 Learning Objectives


• Identify identifiers, keywords, statements, and expressions in Python code
• Declare and use variables; apply operators with correct precedence
• Understand Python's built-in data types and indentation rules
• Read input, print output, and perform type conversions
• Use the type() function and 'is' operator; explain dynamic and strong typing

B.2 Theory Notes


A. Identifiers
Identifiers are names given to variables, functions, classes, etc. Rules: must start with a letter or underscore
(_), can contain letters, digits, and underscores, are case-sensitive, and cannot be a keyword.

studentName = "Ravi" # valid identifier


_marks = 90 # valid (starts with underscore)
2ndYear = 2024 # INVALID — cannot start with a digit

B. Keywords
Keywords are reserved words that have special meaning and cannot be used as identifiers.

False None True and as assert async await


break class continue def del elif else except
finally for from global if import in is
lambda nonlocal not or pass raise return try
while with yield

C. Statements and Expressions


A statement is an instruction the Python interpreter can execute (e.g., an assignment, an if statement, a
loop). An expression is a combination of values, variables, and operators that evaluates to a single value.

x = 5 + 3 # '5 + 3' is an expression; the whole line is an assignment


statement
if x > 5: # 'x > 5' is an expression; the whole line is an if statement
print(x)

D. Variables
A variable is a name that refers to a value stored in memory. Python variables do not need explicit type
declaration — the type is inferred from the assigned value.

age = 20 # int
price = 99.5 # float
name = "Asha" # str
is_pass = True # bool

E. Operators, Precedence and Associativity


Category Operators
Arithmetic + - * / // % **
Category Operators
Relational == != > < >= <=
Assignment = += -= *= /= //= %= **=
Logical and or not
Bitwise & | ^ ~ << >>
Membership in not in
Identity is is not

Precedence determines which operator is evaluated first when multiple operators appear in an expression
(e.g., ** binds tighter than *, which binds tighter than +). Associativity determines the evaluation order
among operators of the SAME precedence — most Python operators are left-associative, but ** is right-
associative.

print(2 + 3 * 4) # 14 (* evaluated before +)


print(2 ** 3 ** 2) # 512 (right-associative: 2 ** (3 ** 2))

F. Data Types
Type Example Description
int 10, -5 Whole numbers
float 3.14, -0.5 Decimal (floating-point) numbers
complex 2+3j Complex numbers
str "Hello" Sequence of characters (text)
bool True, False Boolean values
list [1, 2, 3] Ordered, mutable collection
tuple (1, 2, 3) Ordered, immutable collection
dict {"a": 1} Key-value pairs
set {1, 2, 3} Unordered collection of unique
items

G. Indentation
Python uses indentation (whitespace at the start of a line), instead of braces {}, to define blocks of code.
Consistent indentation (commonly 4 spaces) is mandatory — incorrect indentation causes an
IndentationError.

if 5 > 2:
print("Five is greater than two") # indented block belongs to if
print("This line is outside the if block")

H. Comments
# This is a single-line comment
"""
This is a multi-line string,
often used as a comment/docstring
"""
I. Reading Input
The input() function reads a line of text from the keyboard and always returns it as a string.

name = input("Enter your name: ")


age = int(input("Enter your age: ")) # convert input string to int
print(name, age)

J. Print Output
print("Hello, World!")
print("Name:", name, "Age:", age)
print(f"Name: {name}, Age: {age}") # f-string formatting
print("A", "B", "C", sep="-") # A-B-C
print("No newline", end=" ") # controls line ending

K. Type Conversions
Python allows converting values from one type to another using built-in functions:

x = int("25") # str -> int


y = float("3.14") # str -> float
z = str(100) # int -> str
b = bool(0) # int -> bool (False)

L. The type() Function and 'is' Operator


type() returns the data type of a value/variable. The 'is' operator checks whether two references point to the
SAME object in memory (identity), whereas '==' checks whether two values are EQUAL.

x = 10
print(type(x)) # <class 'int'>

a = [1, 2, 3]
b = [1, 2, 3]
print(a == b) # True (values are equal)
print(a is b) # False (different objects in memory)

M. Dynamic and Strongly Typed Language


Python is DYNAMICALLY typed — a variable's type is determined at run time and can change as different
values are assigned to it. Python is also STRONGLY typed — it does not implicitly convert between unrelated
types (e.g., adding a string and an int raises a TypeError).

x = 10 # x is an int
x = "ten" # now x is a str (dynamic typing allowed)

print("5" + 5) # TypeError: strongly typed — no implicit str+int conversion

B.3 Solved Example


# Program to demonstrate variables, operators, input/output, and type conversion
name = input("Enter your name: ")
marks1 = float(input("Enter marks in Subject 1: "))
marks2 = float(input("Enter marks in Subject 2: "))

total = marks1 + marks2


average = total / 2

print(f"Student: {name}")
print(f"Total Marks: {total}")
print(f"Average Marks: {average:.2f}")
print("Type of average:", type(average))

is_pass = average >= 40


print("Result:", "Pass" if is_pass else "Fail")

B.4 Practice Exercises


16. Write a program to read a person's name and age using input(), and print a formatted greeting using an
f-string.
17. Write a program to swap two numbers without using a third (temporary) variable.
18. Write a program that reads a temperature in Fahrenheit and converts it to Celsius (use float conversion
and formatted print with 2 decimals).
19. Write short code snippets to demonstrate each data type listed in the Data Types table (int, float,
complex, str, bool, list, tuple, dict, set) using type() to print each one's type.
20. Write a program to demonstrate the difference between '==' and 'is' using two lists with identical
content.
21. Identify and correct the indentation error in the following snippet: if 10 > 5: print("Ten is greater")
22. Write a program to accept two numbers from the user as strings, convert them to integers, and print
their sum, difference, and product.

B.5 Review Questions


23. What are the rules for naming a valid identifier in Python?
24. Differentiate between a statement and an expression, with examples.
25. Why does Python not require explicit type declarations for variables?
26. Explain operator precedence and associativity with an example using ** and *.
27. Why is indentation significant in Python? What error occurs when indentation is inconsistent?
28. What is the difference between the '==' operator and the 'is' operator?
29. Explain, with an example, why Python is called a 'strongly typed' language even though it is dynamically
typed.
30. What does the input() function return, and why is explicit type conversion often needed after reading
input?
UNIT I – Part C: Control Flow Statements

C.1 Learning Objectives


• Use if, if-else, if-elif-else, and nested if statements for decision-making
• Use while and for loops for repetition
• Control loop execution using continue and break
• Handle run-time errors gracefully using try and except

C.2 Theory Notes


A. if Statement
marks = 45
if marks >= 40:
print("Pass")

B. if-else Statement
marks = 30
if marks >= 40:
print("Pass")
else:
print("Fail")

C. if...elif...else
marks = 82
if marks >= 90:
grade = 'A'
elif marks >= 75:
grade = 'B'
elif marks >= 40:
grade = 'C'
else:
grade = 'F'
print("Grade:", grade)

D. Nested if Statement
age = 20
has_id = True
if age >= 18:
if has_id:
print("Allowed to vote")
else:
print("ID required")
else:
print("Not eligible")

E. while Loop
Repeats a block as long as a condition remains True (entry-controlled loop).

i = 1
while i <= 5:
print(i)
i += 1

F. for Loop
Iterates over a sequence (range, list, string, etc.).

for i in range(1, 6): # 1, 2, 3, 4, 5


print(i)

fruits = ["apple", "banana", "mango"]


for fruit in fruits:
print(fruit)

G. continue and break Statements


continue — skips the current iteration and moves to the next:

for i in range(1, 6):


if i == 3:
continue
print(i)

break — terminates the loop immediately:

for i in range(1, 10):


if i == 5:
break
print(i)

H. Catching Exceptions Using try and except


Python uses try/except blocks to handle run-time errors (exceptions) gracefully instead of the program
crashing.

try:
num = int(input("Enter a number: "))
result = 10 / num
print("Result:", result)
except ValueError:
print("Error: Please enter a valid integer")
except ZeroDivisionError:
print("Error: Cannot divide by zero")
finally:
print("Execution complete")

C.3 Solved Example


# Program combining control flow, loops, and exception handling
for attempt in range(1, 4): # allow up to 3 attempts
try:
num = int(input("Enter a positive number: "))
if num <= 0:
print("Number must be positive. Try again.")
continue

if num % 2 == 0:
print(num, "is Even")
else:
print(num, "is Odd")

break # valid input received, exit loop


except ValueError:
print("Invalid input — please enter an integer.")
else:
print("Too many invalid attempts.")

C.4 Practice Exercises


31. Write a program to check whether a given year is a leap year (use nested if).
32. Write a program to find the largest of three numbers using if-elif-else.
33. Write a program using a while loop to print the multiplication table of a number entered by the user.
34. Write a program to compute the factorial of a number using a for loop.
35. Write a program that prints numbers from 1 to 50, skipping multiples of 3 using continue, and stopping
completely at 41 using break.
36. Write a program to check whether a number is prime using a for loop and break.
37. Write a program that repeatedly asks the user to enter a number until they enter 'stop' (a string), using
try/except to catch invalid numeric input.
38. Write a program to safely divide two numbers entered by the user, using try/except to handle both
ValueError and ZeroDivisionError.

C.5 Review Questions


39. What is the difference between if-elif-else and multiple separate if statements?
40. Explain the difference between while and for loops. When would you prefer one over the other?
41. Explain the difference between continue and break with examples.
42. What is the purpose of the try/except block? Give an example of two different exception types it can
catch.
43. What is the role of the 'finally' clause in exception handling?
44. Trace the output of the following code: for i in range(1, 6): if i == 3: continue if i == 5:
break print(i)

Instructor Note: All example programs should be run in Jupyter Notebook or a Python IDE to verify output before
distribution to students. Installation steps may vary slightly by operating system version.

You might also like