0% found this document useful (0 votes)
7 views22 pages

Python Programming Basics and Concepts

The document provides an introduction to Python programming, covering various concepts such as print and input functions, control flow statements (elif, for, while), user-defined functions, variable scope, lists, dictionaries, tuples, string methods, file handling, assertions, logging, classes, pure functions, and JSON. Each concept is explained with examples and includes key methods and characteristics. The document serves as a comprehensive guide for beginners to understand fundamental Python programming principles.

Uploaded by

syedanas1314981
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)
7 views22 pages

Python Programming Basics and Concepts

The document provides an introduction to Python programming, covering various concepts such as print and input functions, control flow statements (elif, for, while), user-defined functions, variable scope, lists, dictionaries, tuples, string methods, file handling, assertions, logging, classes, pure functions, and JSON. Each concept is explained with examples and includes key methods and characteristics. The document serves as a comprehensive guide for beginners to understand fundamental Python programming principles.

Uploaded by

syedanas1314981
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

Introduc on to Python Programming (BPLCK105B/205B)

Passing + Scoring Package


1. Demonstrate with example print(), input() and string
replica on. (6 Marks)
1. print( ) → outputs to console.
2. sep argument changes separator.
3. end argument changes line ending.
4. Can print variables, expressions, strings.
5. input( ) → reads input from user.
6. Always returns string.
7. Needs type conversion for numbers.
8. String replica on uses *.
9. "hi"*3 → hihihi.
[Link] for forma ng and pa erns.
Example 1
name = input("Enter your name: ")
print("Hello,", name)
Example 2
print("*" * 10) # **********
2. Explain elif, for, while, break and con nue statements in
Python with examples. (8 Marks)
1. elif → else-if branch.
2. Used in mul -way decision.
3. for → iterates sequences.
4. while → runs ll condi on false.
5. break → exits loop.
6. con nue → skips itera on.
7. Loops avoid repe on.
8. for uses iterators internally.
9. while uses condi on checking.
[Link] loops + condi ons provide flow control.
Example 1
for i in range(5):
if i == 3:
break
print(i)

Example 2
n=5
while n > 0:
n -= 1
if n % 2 == 0:
con nue
print(n)

3. What are user-defined func ons? How can we pass


parameters in user-defined func ons? Explain with example. (5
Marks)
1. Func on = reusable block of code.
2. Defined with def.
3. Parameters allow input.
4. Posi onal arguments supported.
5. Default arguments possible.
6. Keyword arguments improve clarity.
7. *args for variable arguments.
8. **kwargs for key-value arguments.
9. return used for output.
[Link] modularity and reuse.

Example 1
def greet(name="Guest"):
return f"Hello {name}"
print(greet("Ananya"))

Example 2
def add(*nums):
return sum(nums)
print(add(2, 3, 4)) # 9

4. Explain Local and Global scope with variables for each. (8


Marks)
1. Local variables exist inside func on.
2. Destroyed when func on ends.
3. Global variables exist outside func on.
4. Accessible anywhere.
5. Local shadows global.
6. global keyword modifies global.
7. Overuse of global = bad design.
8. Local improves modularity.
9. Scoping prevents conflicts.
[Link] memory management.

Example 1
x = 10 # global
def func():
x = 5 # local
print("Local:", x)
func()
print("Global:", x)

Example 2
count = 0
def increment( ):
global count
count += 1
increment()
print(count)

5. What is a List? Explain append(), insert(), and remove()


methods with examples. (8 Marks)
1. List = mutable collec on.
2. Ordered and indexed.
3. Can store mixed types.
4. append(x) → add at end.
5. insert(i, x) → add at posi on.
6. remove(x) → delete first match.
7. Error if element not found.
8. Supports slicing.
9. Dynamic resizing.
[Link] DS in Python.
Example 1
lst = [1, 2, 3]
[Link](4)
print(lst) # [1, 2, 3, 4]

Example 2
lst = ["a", "b", "c"]
[Link](1, "z")
[Link]("c")
print(lst) # ['a', 'z', 'b']
6. Explain keys(), values(), items() methods in a dic onary with
example. (12 Marks)
1. Dict stores key-value pairs.
2. Keys must be unique.
3. Values can repeat.
4. keys() → returns list of keys.
5. values() → returns values.
6. items() → returns pairs.
7. Iterables can be looped.
8. Efficient lookup using hash.
9. Mutable in nature.
[Link] used for mapping.
Example 1
d = {"a": 1, "b": 2}
print([Link]()) # dict_keys(['a','b'])
Example 2
for k, v in {"x": 10, "y": 20}.items():
print(k, v)
7. How is a tuple different from a list? Which func on is used to
convert list to tuple? (6 Marks)
1. List mutable, tuple immutable.
2. Tuples faster than lists.
3. Lists = [], tuples = ().
4. Lists allow modifica on.
5. Tuples fixed data storage.
6. Tuples hashable, lists not.
7. Lists grow/shrink dynamically.
8. Tuples use less memory.
9. Both allow mixed data.
[Link]: tuple(list).
Example 1
lst = [1,2,3]
tpl = tuple(lst)
print(tpl)

Example 2
t = (10, 20, 30)
# t[0] = 50 # Error → immutable
8. Explain upper(), lower(), isupper(), islower() with example. (8
Marks)
1. String methods for case.
2. upper() → all caps.
3. lower() → all small.
4. isupper() → check uppercase.
5. islower() → check lowercase.
6. Returns new string, unchanged original.
7. isupper/islower → Boolean.
8. Used for valida on.
9. Unicode support.
[Link] user input.
Example 1
s = "Hello"
print([Link]()) # HELLO

Example 2
x = "python"
print([Link]()) # True
9. Illustrate file opening with open(), reading with read() and
wri ng with write(). (12 Marks)
1. File opened with open().
2. Modes: r, w, a.
3. read() → full content.
4. readline() → line by line.
5. write() → writes string.
6. with open() auto closes file.
7. w overwrites.
8. a appends.
9. Binary files need b mode.
[Link] I/O essen al for persistence.
Example 1
with open("[Link]","w") as f:
[Link]("Hello File")

Example 2
with open("[Link]","r") as f:
print([Link]())
10. Explain steps involved in adding bullets to Wiki-Markup. (10
Marks)
1. Wiki markup → lightweight forma ng.
2. * → bullet list.
3. # → numbered list.
4. Used in wikis/docs.
5. Each line begins with symbol.
6. Supports nes ng.
7. Easy syntax.
8. Can be generated with Python.
9. Converts to HTML later.
[Link] in collabora ve edi ng.
Example 1
lines = ["* Apple", "* Banana", "* Mango"]
print("\n".join(lines))
Example 2
for item in ["One","Two","Three"]:
print("*", item)
11. How do you copy files and folders using shu l module? (6
Marks)
1. shu l → shell u li es module.
2. copy() copies file.
3. copy2() preserves metadata.
4. copytree() copies directory.
5. move() moves file/folder.
6. rmtree() deletes folder.
7. Supports both files & dirs.
8. Must import shu l.
9. Raises error if path invalid.
[Link] in file automa on.
Example 1
import shu l
shu [Link]("[Link]", "[Link]")

Example 2
import shu l
shu [Link]("src_folder", "backup_folder")
12. What are Asser ons? Explain with examples. (8 Marks)
1. Asser on = sanity check.
2. Uses assert keyword.
3. Syntax: assert condi on, message.
4. Stops program if false.
5. Used in debugging.
6. Helps catch logical errors.
7. Disabled with -O flag.
8. Should not replace excep ons.
9. Used in development, not produc on.
[Link] program reliability.
Example 1
x = 10
assert x > 0, "x must be posi ve"
Example 2
def div(a, b):
assert b != 0, "Denominator cannot be zero"
return a/b
print(div(10, 2))
13. Illustrate logging levels in Python. (6 Marks)
1. Logging = tracking events.
2. Levels: DEBUG, INFO, WARNING, ERROR, CRITICAL.
3. DEBUG → lowest, for dev.
4. INFO → general messages.
5. WARNING → non-cri cal issues.
6. ERROR → serious issue.
7. CRITICAL → very serious.
8. Configurable with basicConfig().
9. Be er than print() debugging.
[Link] goes to file/console.
Example 1
import logging
[Link]fig(level=[Link])
[Link]("Program started")
Example 2
import logging
[Link]("File not found!")
14. What is a Class? How to define class in Python? How to
ini ate and access members? (8 Marks)
1. Class = blueprint of object.
2. Defined with class.
3. Objects = instances of class.
4. A ributes = variables inside class.
5. Methods = func ons inside class.
6. Constructor = __init__().
7. Object crea on: obj = Class().
8. Access members via . operator.
9. Encapsula on of data + methods.
[Link] OOP concepts.
Example 1
class Student:
def __init__(self, name):
[Link] = name
s = Student("Ananya")
print([Link])

Example 2
class Car:
def drive(self):
print("Car is moving")
c = Car()
[Link]()

15. Define Pure func on with example. (8 Marks)


1. Pure func on → no side effects.
2. Always returns same output for same input.
3. Doesn’t modify global variables.
4. No I/O opera ons.
5. Doesn’t depend on external state.
6. Determinis c in behavior.
7. Helps in tes ng.
8. Improves reliability.
9. Example: mathema cal func ons.
[Link] = impure func on.
Example 1
def square(x):
return x * x
print(square(5))

Example 2
def add(a, b):
return a+b
print(add(2,3))

16. Explain Prin ng Objects. (4 Marks)


1. By default, prin ng object shows memory address.
2. Can override with __str__().
3. __str__ returns string representa on.
4. Used for user-friendly output.
5. Useful in debugging.
6. Example: prin ng Student object.
7. __repr__ gives developer representa on.
8. Both can be defined in class.
9. Improves readability.
[Link] prac ce in OOP.

Example 1
class Student:
def __str__(self):
return "Student object"
s = Student()
print(s)
Example 2
class Book:
def __init__(self, tle):
self. tle = tle
def __str__(self):
return f"Book: {self. tle}"
print(Book("Python"))

17. What is Polymorphism? Demonstrate with func ons. (10


Marks)
1. Polymorphism = many forms.
2. Same func on behaves differently.
3. In Python achieved via overriding.
4. Func ons can accept any type.
5. Operator overloading is polymorphism.
6. Method overloading simulated with default args.
7. Improves flexibility.
8. Code reuse.
9. Example: + works for int and str.
[Link] typing helps polymorphism.
Example 1
print(5+10)
print("Hello " + "World")
Example 2
def add(a, b, c=0):
return a+b+c
print(add(2,3))
print(add(2,3,4))

18. Explain Deck methods to add, remove, shuffle and sort


cards. (10 Marks)
1. Deck = collec on of cards.
2. append() adds card.
3. remove() deletes card.
4. shuffle() randomizes.
5. sort() orders deck.
6. Implemented using lists.
7. [Link]ffle() used.
8. Useful in games.
9. Example: 52-card deck.
[Link] OOP makes simula on easy.
Example 1
import random
deck = [1,2,3,4,5]
[Link]ffle(deck)
print(deck)

Example 2
deck = [10, 5, 7, 2]
[Link]()
print(deck)

19. Explain __init__() and __str__() methods with examples. (6


Marks)
1. __init__() → constructor.
2. Called at object crea on.
3. Ini alizes a ributes.
4. __str__() → returns string rep.
5. Called when prin ng object.
6. Provides readability.
7. __repr__() is similar.
8. Both are magic methods.
9. Improves usability.
[Link] in OOP.
Example 1
class Student:
def __init__(self, name):
[Link] = name
s = Student("Ananya")
print([Link])
Example 2
class Car:
def __str__(self):
return "Car object"
print(Car())
20. What is JSON? Compare with Dic onary and explain with
example. (8 Marks)
1. JSON = JavaScript Object Nota on.
2. Lightweight data format.
3. Key-value pairs.
4. Similar to Python dict.
5. Keys must be strings.
6. Values: string, number, list, object.
7. Used in APIs, web.
8. Conversion: [Link](), [Link]().
9. Human-readable.
[Link] is Python-specific, JSON is universal.
Example 1
import json
d = {"name":"Ananya","age":20}
print([Link](d))
Example 2
s = '{"name":"Ananya","age":20}'
print([Link](s))

Common questions

Powered by AI

The `print()` function in Python outputs data to the console, supporting various parameters like `sep` for separator and `end` for specifying what to print at the end, such as a newline. For example, `print("Hello")` outputs "Hello". The `input()` function reads a user's input from the console and returns it as a string, which needs type conversion if numerical data is required, exemplified by `name = input("Enter your name: ")` to capture and print with `print("Hello,", name)`. String replication allows repeating strings using the `*` operator, useful in pattern creation or formatting, e.g., `print("*" * 10)` outputs "**********" .

Local variables exist only within the function or block in which they are declared, and they are destroyed when the function exits. Global variables are declared outside of any function and can be accessed anywhere in the code. Local variables can shadow global variables of the same name within their scope. The `global` keyword can be used inside a function to modify a global variable . For example, `x = 10` (global) and within a function `def func(): x = 5` (local) will print `5` for the local scope and `10` when printing globally outside the function. An example with modification is `count = 0` defined globally, and a subsequent use of `global count` within a function to modify its value. On calling the function, the global count will be updated .

Polymorphism in Python allows functions or methods to operate on different types of objects, providing flexibility and code reusability. Python supports polymorphism both through dynamic typing and method overriding. For example, the `+` operator is overloaded to work with both integers and strings, demonstrated by `print(5 + 10)` resulting in `15` and `print("Hello " + "World")` resulting in "Hello World", showcasing operator overloading. Function polymorphism is supported using method overriding or default arguments like `def add(a, b, c=0): return a+b+c`, which can accept two or three arguments, enhancing function versatility .

Python's logging module provides a standardized way to log program execution progress and issues, differentiated by levels: DEBUG (detailed diagnose), INFO (general events), WARNING (potential problems), ERROR (serious issues), and CRITICAL (highest severity). Proper logging aids in debugging and monitoring applications effectively. Logging is initiated via `logging.basicConfig()`, and messages are recorded with functions like `logging.info()` or `logging.error()`. For example, `import logging; logging.basicConfig(level=logging.INFO); logging.info("Program started")` logs an informational message, while `logging.error("File not found!")` logs an error, aiding issue identification and resolution in production environments .

Assertions in Python provide a mechanism for debugging by allowing assertions of conditions thought to be true in the code flow. They are implemented using the `assert` keyword, typically following the format `assert condition, message`. If the condition evaluates to false, an `AssertionError` is raised, halting the program and displaying the message. Assertions are useful for catching developer-introduced logical errors more rapidly and are used primarily during development. For example, `x = 10; assert x > 0, "x must be positive"` ensures `x` remains positive. Assertions should not replace exceptions for handling regular program errors and may be disabled in running code with the `-O` flag .

Tuples and lists in Python differ primarily in mutability; lists are mutable, allowing modifications like insertions and deletions, while tuples are immutable, leading to faster performance for fixed data collections due to their immutable nature. Tuples are denoted using parentheses `()` and are hashable, making them suitable for use as dictionary keys. Lists, designated by brackets `[]`, allow for dynamic resizing. The performance benefit of tuples over lists arises because immutability allows Python to optimize storage and access. This inherently leads to tuples using less memory and typically being faster for iteration over their elements .

User-defined functions in Python are blocks of reusable code defined using the `def` keyword, allowing for modular programming and reducing repetition. Parameters can be passed to these functions in several ways: positional arguments, which are passed in order; default arguments, which provide default values if none are specified; keyword arguments, which allow you to pass arguments using the parameter names, thereby improving code clarity; and variable-length arguments using `*args` for tuples and `**kwargs` for dictionaries of arguments. For example, a function `def greet(name="Guest"): return f"Hello {name}"` can be called with `print(greet("Ananya"))` to output "Hello Ananya". Similarly, a function `def add(*nums): return sum(nums)` can sum a variable set of numbers, as in `print(add(2, 3, 4))` which outputs 9 .

In Python dictionaries, `keys()` returns a view object displaying a list of all the keys used in the dictionary. `values()` returns a view object of all the values in the dictionary, while `items()` returns a view object of the dictionary's key-value pairs as tuples. These methods are particularly useful for iterating over a dictionary. For example, `d = {'a': 1, 'b': 2}` allows calling `d.keys()` to obtain `dict_keys(['a', 'b'])`, `d.values()` to return `dict_values([1, 2])`, and using `d.items()` within a for loop allows the iteration over pairs to print keys and values .

In Python, the `append()` method adds an element to the end of the list. For example, `lst = [1, 2, 3]; lst.append(4)` results in `[1, 2, 3, 4]`. The `insert()` method adds an element to a specific position in the list, as in `lst.insert(1, 'z')` where `lst = ['a', 'b', 'c']` would become `['a', 'z', 'b', 'c']`. The `remove()` method deletes the first match of a value. For example, in a list `lst = ['a', 'z', 'b', 'c']`, using `lst.remove('c')` would result in `['a', 'z', 'b']`. These methods allow dynamic modification of list content .

In Python, the `__init__()` method acts as a class constructor, called automatically when creating a new instance, allowing attributes initialization. For example, `class Student: def __init__(self, name): self.name = name` assigns the name provided during instantiation. The `__str__()` method provides a human-readable string representation of an object, used when an instance is printed. It is overridden from the object class. For example, `class Car: def __str__(self): return "Car object"; print(Car())` will output "Car object". These methods facilitate attribute management and improve readability, essential for debugging and data presentation .

You might also like