0% found this document useful (0 votes)
72 views6 pages

Python Programming Basics for VTU

The document provides an overview of various Python programming concepts including flow control statements, built-in functions, module importing, exception handling, and user-defined functions. It also covers list operations, dictionary methods, and statistical calculations like mean and standard deviation. Additionally, it includes examples of string manipulation, local vs global scope, and character frequency counting.
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)
72 views6 pages

Python Programming Basics for VTU

The document provides an overview of various Python programming concepts including flow control statements, built-in functions, module importing, exception handling, and user-defined functions. It also covers list operations, dictionary methods, and statistical calculations like mean and standard deviation. Additionally, it includes examples of string manipulation, local vs global scope, and character frequency counting.
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

1.

Flow Control Statements in Python


Python includes:
- if, elif, else: decision making
Example:
x = 10
if x > 0:
print("Positive")
elif x == 0:
print("Zero")
else:
print("Negative")

- for loop: iterates over a sequence


for i in range(5):
print(i)

- while loop: repeats while condition is true


count = 0
while count < 3:
print(count)
count += 1

- break, continue, pass for loop control.

2. Built-in Functions
print(): prints output
input(): takes user input
len(): returns length
str(): converts to string
int(): converts to integer
float(): converts to float

Examples:
print("Hello")
x = input("Enter name: ")
print(len("Python"))
print(str(123))
print(int("10"))
print(float("3.14"))

3. Importing Modules
import math
print([Link](16))

from math import pi


print(pi)

4. Exceptions and Handling


try-except block:
try:
x = 10 / 0
except ZeroDivisionError:
print("Error!")

try-except-finally:
try:
x = int("abc")
except ValueError:
print("Invalid input")
finally:
print("Runs always")

5. Factorial and Binomial Coefficient


Factorial:
def factorial(n):
return 1 if n == 0 else n * factorial(n-1)
print(factorial(5))

Binomial:
def fact(n):
return 1 if n == 0 else n * fact(n - 1)
def binomial(n, k):
return fact(n) // (fact(k) * fact(n - k))
print(binomial(5, 2))

6. Output of Code Snippets


i.
eggs = 'bacon'
print("Before:", eggs)
update_global_variable()
print("After:", eggs)
# Output: bacon -> spam

ii.
eggs = 'spam'
print("Before:", eggs)
function_bacon()
print("After:", eggs)
# Output: spam -> spam

iii. Same as ii

8. String Concatenation and Replication


Concatenation:
s1 = "Hello"
s2 = "World"
print(s1 + " " + s2)

Replication:
print("Hi" * 3)

9. User Defined Functions


def greet(name):
print("Hello", name)
greet("Alice")

10. elif, for, while, break, continue


elif:
x = 20
if x < 10:
print("Low")
elif x < 30:
print("Medium")

for:
for i in range(3): print(i)

while:
x=0
while x < 3:
print(x)
x += 1

break/continue in loops

11. Local vs Global Scope


x = 10 # Global
def my_func():
x = 5 # Local
print(x)
my_func()
print(x)
Using global:
def change():
global x
x = 20

12. List Operations


my_list = [4, 2, 9]
my_list.append(5)
my_list.remove(2)
print(9 in my_list)
my_list.sort()
my_list.reverse()

13. List Slicing


S = ['cat', 'bat', 'rat', 'elephant', 'ant']
S[1:5] -> ['bat', 'rat', 'elephant', 'ant']
S[:5] -> ['cat', 'bat', 'rat', 'elephant', 'ant']
S[3:-1] -> ['elephant']
S[:] -> full list

14. Dictionary in Python


dict = {'name': 'Alice', 'age': 25}
for key in dict:
print(key)

List vs Dictionary:
- List uses index, dict uses keys.

15. Program for Mean, Variance and Standard Deviation


import statistics
data = [10, 20, 30]
mean = [Link](data)
variance = [Link](data)
std_dev = [Link](data)

print("Mean:", mean)
print("Variance:", variance)
print("Standard Deviation:", std_dev)

16. Dictionary Methods: keys(), values(), items()


my_dict = {'a': 1, 'b': 2}
print(my_dict.keys()) # dict_keys(['a', 'b'])
print(my_dict.values()) # dict_values([1, 2])
print(my_dict.items()) # dict_items([('a', 1), ('b', 2)])

17. Dictionary with 10 Key-Value Pairs


d = {i: chr(65 + i) for i in range(10)}
print([Link]())

18. Frequency of Characters using pprint


import pprint

message = "hello world"


count = {}
for char in message:
[Link](char, 0)
count[char] += 1

[Link](count)

Common questions

Powered by AI

In Python, the factorial of a number can be calculated recursively by defining a base case (factorial(0) = 1) and a recursive step (n * factorial(n-1)). The function calls itself with decremented values until the base case is reached. Example: def factorial(n): return 1 if n == 0 else n * factorial(n-1). While recursion is elegant, it can lead to stack overflow for large input due to deep call stacks, is generally slower due to function call overhead, and can be less readable for those unfamiliar with recursive patterns .

In Python, 'break' and 'continue' are loop control statements that alter iteration flows. 'Break' terminates the loop, stopping further iterations and exiting the loop entirely. It is useful when a terminating condition is met early, like finding an item in a list. Conversely, 'continue' skips the current loop iteration and proceeds with the next, useful for bypassing parts of the loop body under specific conditions without exiting the loop, such as ignoring even numbers in an odd-number summation loop. Their usage provides more controlled and efficient loop execution .

The for and while loops in Python are both iteration constructs but differ significantly in their usage. The 'for' loop is used for iterating over a sequence (like a list, tuple, or string) with a definite iteration count determined at loop entry, often using functions like range(). It's preferred when the number of iterations is known prior to the start of the loop. In contrast, the 'while' loop repeats execution based on a Boolean condition that is checked before each iteration, making it ideal for cases where iterations continue until a certain condition is false. It is preferred when the number of iterations is not predetermined and might depend on dynamic factors during execution .

The 'setdefault' method in dictionaries simplifies character frequency counting by initializing a key with a default value if it doesn't exist, avoiding a manual check before updating values. For example, by counting frequencies in a string 'hello world', 'setdefault' is called (count.setdefault(char, 0)) to initialize each character at 0 on its first occurrence, incrementing on subsequent encounters. This method reduces error-prone boilerplate code and simplifies logic compared to an approach that manually checks for key existence before initializing, which can be more verbose and prone to errors .

Function scope in Python defines the accessibility of variables; variables declared within a function are by default local to that function. A function can access but not alter a global variable unless declared using the 'global' keyword. For instance, if a global variable x = 10 exists, a function can access x, but to modify it, one must use: def modify_global(): global x; x = 20. This modification affects the global scope, changing x globally, demonstrating how scope impacts variable access and modification .

The 'global' keyword in Python is used to declare variables that are defined outside the current scope, allowing modification of global variables within a local (typically function) scope. This interaction facilitates access and modification of global variables, avoiding the creation of local instances shadowing the global variable with the same name. However, using 'global' can potentially lead to code that is harder to follow and debug, as it breaks the local encapsulation of functions, increases dependencies, and can inadvertently alter global state, leading to unexpected behavior especially in large programs .

The 'if', 'elif', and 'else' statements in Python are used for decision-making by evaluating conditions that alter the flow of execution. The 'if' statement evaluates the initial condition; if true, the block of code within it executes. If false, the program control bypasses it and can evaluate an 'elif' (else-if) condition if present. This allows for multiple conditions to be checked sequentially. The 'else' statement follows an 'if' or 'elif' statement and executes when none of the preceding conditions are true, providing a default action. This chain allows for branching decision-making based on varying conditions .

String concatenation in Python involves using the '+' operator to join two or more strings into a single string. It's suitable when constructing a new string from parts, like generating a message from user input or merging titles and names. For example, concatenating 'Hello' and 'World' results in 'Hello World'. String replication uses the '*' operator to repeat strings a specified number of times, useful for generating repetitive string patterns, such as padding or formatting outputs. For example, 'Hi' * 3 produces 'HiHiHi', suitable for creating separators or repeated elements .

In Python, the try-except block is used for handling errors by isolating potentially problematic code within a 'try' block. When an error occurs within this block, execution is transferred to an 'except' block where specific error management logic can be applied, such as logging the error or providing user feedback. Including a 'finally' clause ensures that crucial operations (such as resource release or cleanup tasks) are executed regardless of whether an error occurs or not, providing robustness by ensuring such operations aren't skipped due to exits from the try block .

Lists and dictionaries in Python are both used to store collections of data, but their indexing and access times differ. A list is an ordered collection accessed via integer indices, with an access time complexity of O(1) under the assumption of constant-time random access. Lists are ideal for sequences where the order matters and elements are accessed through their positions. In contrast, dictionaries use keys for indexing data, providing faster average search times (O(1) on average) due to hashing, which makes them suitable for cases where direct access through unique identifiers is required. The key-based nature of dictionaries also means that they offer flexible indexing compared to lists .

You might also like