Python — UT1 Important Notes

These notes are prepared from the Python Module 1 and Module 2 study material in this folder. Examples are written in standard Python 3 syntax.

Lab-code reference: Where a UT1 topic has a matching program, the lab version from ~/uni/sem3/python-lab is included below. The path shown before a lab program is its original file path.

How to write the answer

  • 5 marks: definition/introduction + classification or features + syntax + a short example/program.
  • 9 marks: definition + detailed points/table + syntax + explanation/flow + program with output or use case.

5-Mark Questions

1. Features of Python

Python is a high-level, interpreted, interactive, object-oriented and general-purpose programming language. It is designed to be readable and uses indentation to define blocks of code.

Important features

  1. Easy to learn: It has a small number of keywords and a simple syntax.
  2. Easy to read: Python code is close to ordinary English and is clearly structured.
  3. Easy to maintain: Readable code is easier to debug, modify and maintain.
  4. Interpreted: A Python program is executed by an interpreter at run time; a separate compilation step is not normally required.
  5. Interactive: Statements can be tested directly at the Python prompt.
  6. Object-oriented: Python supports classes, objects, inheritance and other object-oriented concepts.
  7. Portable: The same Python program can run on different platforms such as Windows, Linux and macOS, with little or no change.
  8. Large standard library: It provides modules for files, mathematics, databases, networking and many other tasks.
  9. Extendable: Low-level modules can be added to extend Python’s functionality.
  10. Database and GUI support: Python provides database interfaces and libraries for graphical user interfaces.
  11. Scalable: Its structure supports both small scripts and large applications.
  12. Dynamically typed: The type of a variable is determined at run time; a type declaration is not required.

Conclusion: Python’s simple syntax, portability and extensive libraries make it useful for web development, data science, artificial intelligence, scientific computing, automation and application development.


2. Python Operators — All Important Operators

An operator is a symbol or keyword used to perform an operation on values or variables. The values on which an operator works are called operands.

A. Arithmetic operators

OperatorMeaningExampleResult for a = 15, b = 4
+Additiona + b19
-Subtractiona - b11
*Multiplicationa * b60
/True divisiona / b3.75
//Floor divisiona // b3
%Remainder/modulusa % b3
**Exponent/powera ** b50625

B. Comparison (relational) operators

Comparison operators compare two values and return True or False.

OperatorMeaning
==Equal to
!=Not equal to
>Greater than
<Less than
>=Greater than or equal to
<=Less than or equal to

Example: 20 > 10 gives True.

C. Assignment operators

OperatorExampleEquivalent to
=x = 5Assigns 5 to x
+=x += 2x = x + 2
-=x -= 2x = x - 2
*=x *= 2x = x * 2
/=x /= 2x = x / 2
%=x %= 2x = x % 2
//=x //= 2x = x // 2
**=x **= 2x = x ** 2
&=, |=Bitwise assignmentApply bitwise AND or OR

Remember: = assigns a value, while == tests equality.

D. Logical operators

Logical operators combine or reverse conditions.

OperatorMeaningExample
andTrue only when both conditions are trueage >= 18 and citizen
orTrue when at least one condition is truex < 0 or x > 10
notReverses a Boolean resultnot(is_valid)

E. Membership operators

They test whether a value occurs in a sequence or set.

OperatorMeaningExample
inValue exists"a" in "cat"
not inValue does not exist"z" not in "cat"

F. Identity operators

They test whether two variables refer to the same object, not merely whether their values are equal.

OperatorMeaning
isSame object
is notDifferent objects
a = [1, 2, 3]
b = a
c = [1, 2, 3]
 
print(a is b)   # True: both names refer to the same object
print(a is c)   # False: different objects
print(a == c)   # True: values are equal

G. Bitwise operators

Bitwise operators work on the binary representation of integers.

OperatorMeaningExample
&Bitwise AND5 & 3
|Bitwise OR5 | 3

Lab code

The operator programs in ~/uni/sem3/python-lab/exp-1/ are:

  • operators.py — comparison, logical and augmented-assignment operators.
  • arithmetic.py — an arithmetic-operation menu using if-elif-else.
  • identity_membership.py — is, is not, in and not in.

~/uni/sem3/python-lab/exp-1/arithmetic.py

print("operations: +  -  *  /  //  %  **")
op = input("pick operation: ")
 
a = float(input("first number: "))
b = float(input("second number: "))
 
if op == "+":
    print("result:", a + b)
elif op == "-":
    print("result:", a - b)
elif op == "*":
    print("result:", a * b)
elif op == "/":
    print("result:", a / b)
elif op == "//":
    print("result:", a // b)
elif op == "%":
    print("result:", a % b)
elif op == "**":
    print("result:", a ** b)
else:
    print("unknown operation")

~/uni/sem3/python-lab/exp-1/operators.py

print(5 == 3)        # False
print(5 != 3)        # True
print(5 > 3)         # True
print(5 < 3)         # False
print(5 >= 3)        # True
print(5 <= 3)        # False
 
print(True and False)    # False
print(True or False)     # True
print(not True)          # False
 
n = 10
n += 5
print(n)        # 15
n -= 3
print(n)        # 12
n *= 2
print(n)        # 24
n //= 4
print(n)        # 6
n %= 3
print(n)        # 0
n **= 2
print(n)        # 0

~/uni/sem3/python-lab/exp-1/identity_membership.py

x = 10
y = 10
z = 20
print(x is y)       # True
print(x is z)       # False
print(x is not z)   # True
 
nums = [1, 2, 3]
print(2 in nums)        # True
print(5 in nums)        # False
print(5 not in nums)    # True
 
word = "hello"
print("ell" in word)    # True
print("xyz" in word)    # False

3. Important Programs

A. Fibonacci series

The Fibonacci series starts with 0, 1; every next term is the sum of the previous two terms.

n = int(input("how many terms? "))
a, b = 0, 1
count = 0
 
print("fibonacci series:")
while count < n:
    print(a, end=" ")
    a, b = b, a + b
    count += 1
print()

Lab file: ~/uni/sem3/python-lab/exp-2/fibonacci_while.py.

For n = 7, the output is:

fibonacci series:
0 1 1 2 3 5 8

B. Factorial

The factorial of n is n × (n-1) × ... × 1. By definition, 0! = 1.

n = int(input("enter a number: "))
result = 1
i = 1
 
while i <= n:
    result *= i
    i += 1
 
print("factorial of", n, "=", result)

Lab file: ~/uni/sem3/python-lab/exp-2/factorial_while.py. It assumes a non-negative input.

C. Palindrome

A palindrome reads the same forward and backward, for example madam or 121.

num = int(input("Enter a number: "))
 
temp = num
reverse = 0
 
while temp > 0:
    digit = temp % 10
    reverse = reverse * 10 + digit
    temp = temp // 10
 
if num == reverse:
    print(num, "is a palindrome")
else:
    print(num, "is not a palindrome")

Lab file: ~/uni/sem3/python-lab/exp-3/palindrome_number.py.

D. Common list programs

1. Sum and average of list elements

numbers = [10, 20, 30, 40, 50]
 
total = sum(numbers)
average = total / len(numbers)
 
print("Sum =", total)
print("Average =", average)

2. Largest and smallest element

numbers = [10, 20, 30, 40, 50]
 
largest = max(numbers)
smallest = min(numbers)
 
print("Largest =", largest)
print("Smallest =", smallest)

3. Search for an element

numbers = [10, 20, 30, 40, 50]
value = 30
 
if value in numbers:
    print("Element found at index", numbers.index(value))
else:
    print("Element not found")

4. Reverse a list and remove duplicates

numbers = [10, 20, 10, 30, 20]
 
print("Reversed list:", numbers[::-1])
unique_numbers = list(dict.fromkeys(numbers))
print("Without duplicates:", unique_numbers)

List Operations

Lists are ordered, mutable, dynamic, heterogeneous and allow duplicate values.

Remember: List indexing starts at 0, so the first element is at index 0.

a) Accessing Elements

Syntax:

list_name[index]

Example:

numbers = [10, 20, 30, 40]
 
print(numbers[0])
print(numbers[2])

Output:

10
30

b) Changing Elements

Use the index of an element to change its value.

numbers = [10, 20, 30]
 
numbers[1] = 50
 
print(numbers)

Output:

[10, 50, 30]

c) Adding Elements

append()

Adds one element at the end of the list.

numbers = [10, 20]
 
numbers.append(30)
 
print(numbers)

Output:

[10, 20, 30]
insert()

Adds an element at a specified position.

numbers = [10, 30]
 
numbers.insert(1, 20)
 
print(numbers)

Output:

[10, 20, 30]

d) Removing Elements

pop()

Removes an element by index.

numbers = [10, 20, 30]
 
numbers.pop(1)
 
print(numbers)

Output:

[10, 30]
del

Deletes an element using its index.

numbers = [10, 20, 30]
 
del numbers[0]
 
print(numbers)

Output:

[20, 30]
remove()

Removes the specified value.

numbers = [10, 20, 30]
 
numbers.remove(20)
 
print(numbers)

Output:

[10, 30]

Lab list programs

The lab versions are in ~/uni/sem3/python-lab/exp-3/ and ~/uni/sem3/python-lab/exp-4/.

~/uni/sem3/python-lab/exp-3/list_operations.py

fruits = ["apple", "banana", "cherry"]
print("Original list:", fruits)
 
fruits.append("orange")
print("After append:", fruits)
 
fruits.remove("banana")
print("After remove:", fruits)
 
fruits.pop()
print("After pop:", fruits)
 
fruits.pop(0)
print("After pop(0):", fruits)

~/uni/sem3/python-lab/exp-4/list_largest_smallest_sum.py

numbers = [45, 12, 78, 3, 56, 90, 21]
 
print("List:", numbers)
print("Largest element:", max(numbers))
print("Smallest element:", min(numbers))
print("Sum of elements:", sum(numbers))

Also revise ~/uni/sem3/python-lab/exp-4/list_basics.py for append(), insert(), remove() and pop().


9-Mark Questions

4. Conditional Statements

A conditional statement makes a decision. It executes different blocks of code depending on whether a condition is True or False. Python uses a colon (:) and indentation to define each block.

A. if statement

Executes a block only when the condition is true.

if condition:
    statement(s)
age = 20
if age >= 18:
    print("Eligible to vote")

B. if-else statement

Used when there are two possible outcomes.

if condition:
    statement(s)
else:
    statement(s)
age = 16
if age >= 18:
    print("Eligible to vote")
else:
    print("Not eligible to vote")

C. if-elif-else statement

Used when several conditions must be tested. Python executes the first matching block.

if condition1:
    statement(s)
elif condition2:
    statement(s)
else:
    statement(s)
marks = int(input("Enter marks: "))
 
if marks >= 90:
    grade = "A+"
elif marks >= 80:
    grade = "A"
elif marks >= 70:
    grade = "B"
elif marks >= 60:
    grade = "C"
else:
    grade = "Fail"
 
print("Grade:", grade)

D. Nested if

An if statement placed inside another if statement is called a nested if.

age = 20
citizen = True
 
if age >= 18:
    if citizen:
        print("Eligible to vote")

Important points

  • Conditions normally use comparison and logical operators.
  • The colon after the condition is compulsory.
  • All statements in the same block must have equal indentation.
  • elif means “else if”; any number of elif blocks may be used.
  • else is optional.

Lab programs

~/uni/sem3/python-lab/exp-2/positive_or_negative.py

n = float(input("enter a number: "))
 
if n > 0:
    print(n, "is positive")
elif n < 0:
    print(n, "is negative")
else:
    print(n, "is zero")

~/uni/sem3/python-lab/exp-2/largest_of_three.py

a = float(input("enter first number: "))
b = float(input("enter second number: "))
c = float(input("enter third number: "))
 
if a > b:
    if a > c:
        print(a, "is largest")
    else:
        print(c, "is largest")
else:
    if b > c:
        print(b, "is largest")
    else:
        print(c, "is largest")

5. Control Statements

Control statements control the order in which statements execute. They are used for decision-making, repetition and changing the normal flow of execution.

Types of control statements

  1. Conditional/decision-making statements: if, if-else, if-elif-else, nested if.
  2. Looping/iteration statements: for, while.
  3. Jump statements: break, continue and pass.

A. for loop

Used when the sequence or number of iterations is known.

for variable in sequence:
    statements
for i in range(1, 6):
    print(i)

Output: 1 2 3 4 5 (on separate lines).

B. while loop

Used when repetition depends on a condition and the number of iterations may not be known beforehand.

while condition:
    statements
count = 1
while count <= 5:
    print(count)
    count += 1

The update statement is important; otherwise an infinite loop may occur.

Lab loop program

~/uni/sem3/python-lab/exp-2/multiplication_table.py

n = int(input("Enter a number: "))
 
for i in range(1, 11):
    print(f"{n} x {i} = {n * i}")

C. break

Stops the nearest loop immediately.

for i in range(1, 11):
    if i == 6:
        break
    print(i)

Output: 1 2 3 4 5.

D. continue

Skips the remaining statements in the current iteration and starts the next iteration.

for i in range(1, 6):
    if i == 3:
        continue
    print(i)

Output: 1 2 4 5.

E. pass

Does nothing. It is used as a placeholder when a statement is syntactically required but the code is not written yet.

for i in range(3):
    pass

Combined example

for number in range(1, 11):
    if number == 8:
        break
    if number % 2 == 0:
        continue
    print(number)

Output: 1 3 5 7.


6. String Slicing

A string is an immutable sequence of characters. Each character has an index. Positive indexes start from 0 and negative indexes start from -1 at the end.

For text = "PYTHON":

CharacterPYTHON
Positive index012345
Negative index-6-5-4-3-2-1

Syntax

string[start:stop:step]
  • start: index from which slicing begins; included.
  • stop: ending index; not included.
  • step: movement between characters; default is 1.
  • If a value is omitted, Python uses a suitable default.

Examples

text = "PYTHON"
 
print(text[:])       # PYTHON: whole string
print(text[2:])      # THON: index 2 to end
print(text[:4])      # PYTH: start to index 3
print(text[1:5])     # YTHO: indexes 1, 2, 3, 4
print(text[::2])     # PTO: every second character
print(text[::-1])    # NOHTYP: reverse string
print(text[-4:-1])   # THO

Important points

  • The stop index is excluded.
  • A positive step moves from left to right.
  • A negative step moves from right to left.
  • Slicing creates a new string; it does not modify the original string.
  • Strings cannot be changed by item assignment because they are immutable.

Lab code

~/uni/sem3/python-lab/exp-3/string_indexing_and_slicing.py

s = "PYTHON PROGRAMMING"
 
# Indexing
print(s[0])      # First character
print(s[1])      # Second character
print(s[7])      # Character at index 7
print(s[-1])     # Last character
print(s[-2])     # Second last character
print(s[-18])    # First character using negative index
 
# Slicing
print(s[0:6])    # PYTHON
print(s[7:18])   # PROGRAMMING
print(s[:6])     # From start to index 6
print(s[7:])     # From index 7 to end
print(s[:])      # Entire string
print(s[0:6:2])  # Every second character in PYTHON
print(s[::2])    # Every second character of whole string
print(s[::-1])   # Reversed string
print(s[-11:])   # Last 11 characters
print(s[:-12])   # Everything except last 12 characters

~/uni/sem3/python-lab/exam/2.py is another short practice program for positive and negative indexing and slicing.


7. Tuples and Sets

A. Tuple

A tuple is an ordered sequence of values enclosed in parentheses. It may contain different data types.

Features of tuples

  • Ordered; elements have fixed indexes.
  • Immutable; elements cannot be changed after creation.
  • Allows duplicate values.
  • Can contain heterogeneous data types.
  • Supports indexing and slicing.
  • Supports concatenation (+) and repetition (*).
  • Usually uses less memory than a list for fixed data.

Syntax and examples

my_tuple = (10, 20, 30, 40)
student = ("Jain", 21, 85.5, True)
 
print(my_tuple[0])
print(my_tuple[1:3])

Lab tuple programs

~/uni/sem3/python-lab/exp-4/tuple_basics.py

my_tuple = ("python", 10, 3.14, "lab")
 
print("Tuple:", my_tuple)
 
# accessing elements using index
print("First element:", my_tuple[0])
print("Third element:", my_tuple[2])
print("Last element:", my_tuple[-1])
 
# accessing a range using slicing
print("Elements from index 1 to 3:", my_tuple[1:4])

A single-element tuple must contain a comma:

a = (10)    # int, not a tuple
b = (10,)   # tuple

Because a tuple is immutable, methods such as append(), remove() and sort() cannot be used directly on it. Common tuple operations/methods include len(), max(), min(), sum(), count() and index().

~/uni/sem3/python-lab/exp-4/tuple_slicing_concat.py

tuple1 = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
tuple2 = ("a", "b", "c")
 
print("Tuple 1:", tuple1)
print("Tuple 2:", tuple2)
 
# slicing
print("tuple1[2:5]  ->", tuple1[2:5])
print("tuple1[:4]   ->", tuple1[:4])
print("tuple1[6:]   ->", tuple1[6:])
print("tuple1[-3:]  ->", tuple1[-3:])
print("tuple1[::2]  ->", tuple1[::2])
 
# concatenation
result = tuple1 + tuple2
print("Concatenated tuple:", result)

B. Set

A set is an unordered collection of unique elements. It is useful for membership testing and mathematical set operations.

Features of sets

  • Unordered; no fixed index is guaranteed.
  • Does not allow duplicate values.
  • The set itself is mutable: elements can be added or removed.
  • Elements must be immutable/hashable, so a list or dictionary cannot be an element of a set.
  • Does not support indexing or slicing.
  • Can contain different hashable data types.
  • Supports union, intersection, difference, symmetric difference, subset and superset operations.

Syntax and examples

fruits = {"apple", "banana", "orange"}
numbers = set([1, 2, 2, 3])
empty_set = set()       # {} creates an empty dictionary
 
print(numbers)          # {1, 2, 3}

There is no standalone set-operation program in the lab folder; ~/uni/sem3/python-lab/exp-1/datatypes.py only demonstrates a set literal with print({1, 2, 3}). Use the set-operation program above for the UT1 answer.

Common set methods:

numbers.add(4)             # add one element
numbers.update([5, 6])     # add multiple elements
numbers.remove(6)          # KeyError if absent
numbers.discard(10)        # no error if absent

Difference between tuple and set

BasisTupleSet
MeaningOrdered collectionUnordered collection
Symbol( ){ } or set()
OrderPreservedNot guaranteed
MutabilityImmutableMutable collection
DuplicatesAllowedAutomatically removed
Indexing/slicingSupportedNot supported
Element restrictionAny valuesElements must be immutable/hashable
Main useFixed, ordered group of valuesUnique values and set mathematics
Examplet = (1, 2, 2)s = {1, 2, 2} becomes {1, 2}

Set operations

Let A = {1, 2, 3, 4, 5} and B = {4, 5, 6, 7, 8}.

OperationSymbol/methodResult
UnionA | B or A.union(B){1, 2, 3, 4, 5, 6, 7, 8}
IntersectionA & B or A.intersection(B){4, 5}
DifferenceA - B or A.difference(B){1, 2, 3}
Symmetric differenceA ^ B or A.symmetric_difference(B){1, 2, 3, 6, 7, 8}
Subset testA.issubset(B) or A <= BTrue when every item of A is in B
Superset testA.issuperset(B) or A >= BTrue when B is contained in A

Tuple and set program

# Tuple program
numbers = (10, 20, 30, 20, 40, 50)
print("Length:", len(numbers))
print("Maximum:", max(numbers))
print("Minimum:", min(numbers))
print("Sum:", sum(numbers))
print("Count of 20:", numbers.count(20))
print("Index of 30:", numbers.index(30))
 
# Set program
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print("Union:", A | B)
print("Intersection:", A & B)
print("Difference:", A - B)
print("Symmetric difference:", A ^ B)

8. Dictionary Methods

A dictionary stores data as key: value pairs. It is written using curly braces. Dictionaries are mutable, preserve insertion order in modern Python, and do not allow duplicate keys.

Syntax

dictionary_name = {
    key1: value1,
    key2: value2
}
student = {"name": "Raj", "age": 21, "course": "BCA"}
print(student["name"])

Keys should be unique and hashable, such as strings, numbers or tuples. If the same key is assigned twice, the later value replaces the earlier value.

Important dictionary methods

MethodPurposeExample
keys()Returns a view of all keysstudent.keys()
values()Returns a view of all valuesstudent.values()
items()Returns key-value pairsstudent.items()
get(key[, default])Returns a value safely; avoids KeyErrorstudent.get("name")
update(other)Adds pairs or changes existing valuesstudent.update({"marks": 90})
pop(key[, default])Removes a specified key and returns its valuestudent.pop("age")
popitem()Removes and returns the last inserted pairstudent.popitem()
setdefault(key[, default])Gets a value; inserts the key if absentstudent.setdefault("city", "Bengaluru")
clear()Removes all itemsstudent.clear()
copy()Creates a shallow copynew_student = student.copy()
fromkeys(iterable[, value])Creates a dictionary from keysdict.fromkeys(["a", "b"], 0)

del student["key"] is a dictionary operation, not a method. Direct access such as student["phone"] raises KeyError if the key does not exist; get() is safer.

Program demonstrating dictionary methods

student = {
    "name": "Raj",
    "age": 21,
    "course": "BCA",
    "marks": 85
}
 
print("Keys:", student.keys())
print("Values:", student.values())
print("Items:", student.items())
print("Name:", student.get("name"))
 
student.update({"marks": 90})
student.setdefault("city", "Bengaluru")
print("Updated dictionary:", student)
 
removed_age = student.pop("age")
print("Removed age:", removed_age)
print("Final dictionary:", student)

Lab dictionary programs

~/uni/sem3/python-lab/exp-5/dict_access.py

student = {"name": "Arjun", "roll_no": 21, "course": "B.Tech"}
 
print("Dictionary:", student)
 
# accessing values using keys
print("Name:", student["name"])
print("Roll no:", student["roll_no"])
 
# get() returns None instead of an error if the key is not found
print("Course:", student.get("course"))
print("City:", student.get("city"))

~/uni/sem3/python-lab/exp-5/dict_add_update_delete.py

student = {"name": "Arjun", "roll_no": 21, "course": "B.Tech"}
print("Original dictionary:", student)
 
student["cgpa"] = 8.5       # add a key-value pair
print("After adding cgpa:", student)
 
student["course"] = "CSE"  # update an existing key
print("After updating course:", student)
 
del student["roll_no"]      # delete a key-value pair
print("After deleting roll_no:", student)

~/uni/sem3/python-lab/exp-5/dict_methods.py

student = {"name": "Arjun", "roll_no": 21, "course": "B.Tech"}
print("Dictionary:", student)
 
print("Keys:", student.keys())
print("Values:", student.values())
print("Items:", student.items())
print("get('name'):", student.get("name"))
 
student.update({"course": "CSE", "cgpa": 8.5})
print("After update:", student)

Dictionary characteristics

  • Stores data as key-value pairs.
  • Keys are unique; values may be repeated.
  • Mutable: values can be added, changed or removed.
  • Values can be of different data types.
  • Access is generally by key, not by numeric position.

9. Functions and Their Types

A function is a reusable block of code that performs a particular task. It is defined once and called whenever required.

Advantages of functions

  • Avoid repetition and support code reusability.
  • Make programs modular, readable and organized.
  • Simplify testing, debugging and maintenance.
  • Allow a large problem to be divided into smaller tasks.

General syntax of a user-defined function

def function_name(parameters):
    statements
    return value       # optional
  • def defines the function.
  • function_name is the name used to call it.
  • parameters are optional inputs.
  • return sends a result back to the caller and is optional.

Type 1: Built-in functions

These are predefined by Python and can be used directly.

FunctionPurpose
print()Displays output
input()Reads input from the user
len()Returns length
max() / min()Finds the largest/smallest value
sum()Calculates a total
type()Returns the data type
abs()Returns absolute value
round()Rounds a number

Example: len("Python") gives 6.

Type 2: User-defined functions

These are created by the programmer using def.

a. Without parameters and without return value

def greet():
    print("Welcome to Python")
 
greet()

b. With parameters and without return value

def add_and_print(a, b):
    print(a + b)
 
add_and_print(10, 20)

c. Without parameters and with return value

def get_number():
    return 10
 
number = get_number()
print(number)

d. With parameters and with return value

def add(a, b):
    return a + b
 
result = add(5, 7)
print(result)       # 12

Common parameter styles

def profile(name, course="BCA"):       # default parameter
    print(name, course)
 
profile(course="BCA", name="Raj")     # keyword arguments
  • Positional arguments: matched according to position.
  • Keyword arguments: passed using parameter names.
  • Default arguments: use a default value when no value is supplied.
  • Variable-length arguments: *args accepts many positional arguments and **kwargs accepts many keyword arguments.

Important points about return

  • It ends the function execution.
  • It can return one value or multiple values as a tuple.
  • If no return statement is written, the function returns None.

There is no standalone user-defined-function program in ~/uni/sem3/python-lab for this UT1 question. The def examples above follow the study material; the later lab files use def for class methods in experiments 6 and 7.


Last-minute revision checklist

  • Python features: learn any five with one-line explanations.
  • Operators: remember all seven groups, especially //, %, **, in, is and bitwise operators.
  • Programs: practise Fibonacci, factorial, palindrome and at least three list programs.
  • Conditional statements: write the four forms and remember indentation.
  • Control statements: distinguish for, while, break, continue and pass.
  • Slicing: remember start is included and stop is excluded; [::-1] reverses a sequence.
  • Tuple: ordered and immutable; set: unordered and unique.
  • Dictionary: practise keys(), values(), items(), get(), update(), pop() and clear().
  • Functions: know built-in vs user-defined, syntax, parameters and return values.