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

Python Basics: Loops & Functions Guide

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)
5 views4 pages

Python Basics: Loops & Functions Guide

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

Unit 1: Python Basics & Loops

1.1 Python Basics

●​ Variables and Data Types: int, float, str, bool, list, tuple, set, dict​

●​ Type conversion: int(), float(), str()​

●​ Input & Output: input(), print()​

●​ Comments & Docstrings​

Example:

# This program takes marks of 3 subjects and calculates total and


average
sub1 = int(input("Enter marks of Subject 1: ")) # int used for
arithmetic
sub2 = int(input("Enter marks of Subject 2: "))
sub3 = int(input("Enter marks of Subject 3: "))
total = sub1 + sub2 + sub3
average = total / 3 # float division
print("Total:", total, "Average:", average)

Line-by-line Explanation:

●​ input() → takes input as string​

●​ int() → converts string to integer for arithmetic​

●​ total → sum of marks​

●​ average → total divided by 3 → float result​

●​ print() → displays output​

Time Complexity: O(1)​


Space Complexity: O(1)
1.2 Python Loops

1.2.1 For Loop

●​ Used when number of iterations is known​

Example: Print even numbers from 1 to 20

for i in range(1,21): # i goes from 1 to 20


if i%2==0: # check even
print(i)

Time Complexity: O(n)​


Space Complexity: O(1)

1.2.2 While Loop

●​ Used when condition-based iteration​

Example: Take input until user types “exit”

while True:
s = input("Enter something (type 'exit' to stop): ")
if [Link]() == "exit":
break
print("You entered:", s)

Explanation:

●​ while True: → infinite loop​

●​ break → exits loop​

●​ [Link]() → handles case-insensitive input​

1.3 Functions

●​ Definition: Reusable block of code​


Example: Function to calculate factorial with error handling

def factorial(n):
if n<0:
return "Error: Negative number"
if n==0 or n==1:
return 1
result = 1
for i in range(2,n+1):
result *= i
return result

print(factorial(5)) # Output: 120


print(factorial(-2)) # Output: Error

●​ Time Complexity: O(n)​

●​ Space Complexity: O(1)​

1.4 Handling Errors (Exceptions)

Example: Handling TypeError

try:
print(5 + "5") # will raise TypeError
except TypeError:
print("Cannot add integer and string")

Explanation:

●​ try → code that may raise exception​

●​ except → handles the exception​

1.5 *args and kwargs

Example: Function to calculate mean using *args


def mean(*args):
if len(args)==0:
return 0
return sum(args)/len(args)

print(mean(1,2,3,4)) # Output: 2.5

●​ *args → variable number of positional arguments​

Common questions

Powered by AI

Type conversion is fundamental in Python programming as it allows for data interoperability and the correct execution of arithmetic and logical operations which rely on specific data types. For example, the input() function returns data as a string, but arithmetic operations require numerical data types, necessitating explicit conversion using int() or float() to perform calculations, such as converting user-typed marks from strings to integers before performing any arithmetic . Similarly, strings can be converted into floats for operations where decimal precision is crucial. The necessary type conversions ensure that operations are semantically and syntactically consistent with data types, preventing runtime errors and ensuring data is manipulated accurately and effectively.

In Python, *args and **kwargs are used in function definitions to allow handling of an arbitrary number of arguments. *args enables the function to accept any number of positional arguments beyond those already specified, storing them as a tuple . For example, the use of *args allows calculating the mean of any number of integers by passing them as arguments . Meanwhile, **kwargs allows for keyword arguments, which are passed to the function as a dictionary. This provides great flexibility, enabling functions to accept any combination of arguments without knowing them in advance, thus making the functions more dynamic and adaptable.

In Python, user input is handled using the input() function, which reads a line from the input (usually from the user) and returns it as a string. A typical use case involves prompting the user to enter data, such as marks in a subject, and converting that input to an appropriate data type like an integer for further mathematical operations. However, pitfalls include receiving unexpected input types, which can lead to errors if not properly managed, like attempting to perform arithmetic on the string rather than its numerical representation . Careful handling with checks and conversions prevents such pitfalls. An example is asking for marks, converting each entry into an integer, and computing their sum and average, expecting numerically valid inputs from the user .

Python handles type conversion both explicitly and implicitly. Explicit conversion, or type casting, involves converting a variable from one type to another using functions like int(), float(), or str(). For example, the input() function returns a string, which can be explicitly converted to an integer using int() for arithmetic operations . Implicit conversion, on the other hand, is performed automatically by Python, where it converts smaller data type to a larger data type during computation to avoid data loss, such as when adding an integer and a float, resulting in a float .

Basic arithmetic operations in Python, such as addition, subtraction, multiplication, and division, typically have a time complexity of O(1) because these operations are executed in constant time regardless of the size of the input . This implies that the execution cost remains constant. Similarly, the space complexity is also O(1) for these operations as they only require a fixed amount of memory space to store operands and the result . These complexities indicate efficient processing capability for basic arithmetic, making them practical for use in extensive calculations.

Python uses try-except blocks to handle errors gracefully during program execution. The 'try' block contains code that may potentially cause an exception, and the 'except' block contains code to handle the exception if one is raised. For example, attempting to add an integer and a string using '5 + "5"' will raise a TypeError, which can be caught and managed using an except block to print a custom error message instead of terminating the program unexpectedly . This approach is crucial for robust applications as it anticipates potential runtime errors and allows the programmer to define specific responses to them, enhancing program users' experience by preventing abrupt crashes and providing meaningful feedback .

Python handles strings in loops by iterating over each character in the string, allowing operations to be performed on an individual character basis. A 'for' loop is commonly used for such iterations, given strings' sequence-like nature. During iterations, operations such as character manipulation, counting, or concatenation can be performed. For instance, one might convert a string to uppercase character by character, or count the occurrences of specific characters . String iteration via loops thus provides flexibility for customized data processing and manipulation.

Functions in Python serve as fundamental building blocks that promote code reusability and organization. They encapsulate a block of code designed to perform a specific task, which can be invoked with varying inputs as needed . Handling errors within functions elevates program reliability by preemptively managing potential runtime disruptions, allowing functions to return meaningful information rather than causing program termination upon exceptions. An example is the factorial function that, before calculation, checks for negative input, returning an error message instead of attempting the calculation, thereby ensuring program continuity and robustness . Effective error management in functions thus underpins stable and user-friendly applications.

In Python, variable scope refers to the accessibility of variables in different parts of the code. Within a function, variables declared are local to that function and do not affect variables with the same name outside the function. This means that if a variable with the same name exists in both the global scope and the function's scope, the function will only consider its local version unless explicitly stated using the 'global' keyword . For example, if a variable 'total' is defined both globally and inside a function, modifications within the function do not affect the global version unless 'global total' is declared inside the function.

A for loop in Python is used when the number of iterations is known and is typically used to iterate over a sequence such as a list, tuple, or range . A typical scenario for using a for loop is printing even numbers within a specified range, where the number of iterations is predetermined . On the other hand, a while loop is used for condition-based iteration, where the number of iterations is not known beforehand and continues until a specific condition is met, such as accepting user input until the input is 'exit' . The choice between a for loop and a while loop is determined by the requirement of the task: if the loop termination depends on a condition rather than a sequence's length, a while loop is more appropriate.

You might also like