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

B Tech Python Basic 1

Uploaded by

aroraparul160205
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 views12 pages

B Tech Python Basic 1

Uploaded by

aroraparul160205
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
You are on page 1/ 12

Basic Elements of Python:-

Python, as a programming language, has several key elements that form the foundation for writing
programs. Here are the basic elements of Python:

1. Variables

Variables are used to store data values. In Python, you don't need to declare the type of a variable; it is
dynamically inferred.

x = 10 # integer
name = "Alice" # string
pi = 3.14 # float
is_valid = True # boolean

2. Data Types

Python has several built-in data types for handling different kinds of values:

 Basic types:
o int: Integer numbers (e.g., 1, 10, -5)
o float: Decimal numbers (e.g., 3.14, 0.001, -2.5)
o str: Strings for text (e.g., "Hello", 'Python')
o bool: Boolean for true/false values (True, False)
 Advanced types:
o list: Ordered, mutable collection (e.g., [1, 2, 3])
o tuple: Ordered, immutable collection (e.g., (1, 2, 3))
o dict: Key-value pairs (e.g., {"name": "Alice", "age": 25})
o set: Unordered collection of unique items (e.g., {1, 2, 3})

3. Operators

Python supports several types of operators for different operations:

 Arithmetic Operators:

+ # addition
- # subtraction
* # multiplication
/ # division
% # modulus (remainder)
** # exponentiation

 Comparison Operators:

== # equal to
!= # not equal to
> # greater than
< # less than
>= # greater than or equal to
<= # less than or equal to

 Logical Operators:

and # returns True if both statements are true


or # returns True if at least one statement is true
not # reverses the result of the boolean expression
 Assignment Operators:

= # assign value to a variable


+= # add and assign
-= # subtract and assign
*= # multiply and assign
/= # divide and assign

4. Comments

Comments are notes in the code that Python ignores. They are useful for documentation or explaining code.

 Single-line comments start with a #.

# This is a comment
x = 5 # This is another comment

 Multi-line comments can be made using triple quotes (''' or """).

'''
This is a
multi-line comment
'''

5. Input and Output

Python provides simple ways to get input from users and display output.

 input(): Used to take input from the user (always as a string).

name = input("Enter your name: ")


print("Hello", name)

 print(): Used to display output.

print("Hello, World!")

6. Indentation

Unlike many other programming languages, Python uses indentation (spaces or tabs) to define code blocks
rather than braces {}. Consistent indentation is essential.

Example:

if x > 0:
print("Positive number")
else:
print("Negative number or zero")

The basic elements of Python are:

 Variables for storing data.


 Data types like integers, floats, strings, and lists.
 Operators for arithmetic, comparison, and logic.
 Control flow like if-statements and loops.
 Functions to encapsulate reusable code.
 Input/Output functions like input() and print().
 Indentation for defining code blocks.
 Lists and Dictionaries for collections.
 Error Handling using try-except blocks.
 Modules to extend Python's functionality.

These elements form the foundation for writing basic to advance python program.

Branching/Conditional Programs:-
Branching statements in Python are used to execute different blocks of code based on conditions. The most
common branching statements in Python are if, elif, and else. Here's an overview:

1. if Statement

The if statement is used to execute a block of code if a condition is true.

x = 10
if x > 5:
print("x is greater than 5")

2. if else Statement

The else statement follows an if and runs when the condition is false.

x = 3
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")

3. elif Statement

The elif (else if) statement allows you to check multiple conditions.

x = 5
if x > 5:
print("x is greater than 5")
elif x == 5:
print("x is equal to 5")
else:
print("x is less than 5")

Example: Simple Grading System

Here's an example combining all of them:

grade = 85

if grade >= 90:


print("A")
elif grade >= 80:
print("B")
elif grade >= 70:
print("C")
elif grade >= 60:
print("D")
else:
print("F")

Nested if Statements

You can also nest if statements inside others:

x = 10
y = 20

if x > 5:
if y > 15:
print("x is greater than 5 and y is greater than 15")
else:
print("x is greater than 5 but y is not greater than 15")

These statements allow Python to make decisions based on conditions, helping to control the flow of the
program.

Iteration Loops:-
Iteration loops in Python allow you to repeat a block of code multiple times. The two main types of loops
are for loops and while loops. Here's an overview:

1. for Loop

The for loop is used to iterate over a sequence (like a list, tuple, dictionary, or string) and execute a block of
code for each element in that sequence.

Example: Iterating Over a List

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


for fruit in fruits:
print(fruit)

Example: Using range() in a for Loop

The range() function is commonly used to generate a sequence of numbers.

for i in range(5):
print(i) # Prints numbers from 0 to 4

You can also provide start, stop, and step values in range():

for i in range(1, 10, 2):


print(i) # Prints 1, 3, 5, 7, 9

2. while Loop

A while loop repeatedly executes the code block as long as a condition is True.

Example: Basic while Loop


i = 0
while i < 5:
print(i)
i += 1 # Increment i to avoid an infinite loop
3. Loop Control Statements
break

The break statement is used to exit a loop prematurely when a certain condition is met.

for i in range(1,10):
if i == 5:
break
print(i) # print 1 2 3 4

continue

The continue statement skips the rest of the loop body for the current iteration and moves to the next
iteration.

for i in range(1,5):
if i == 2:
continue # Skip the number 2
print(i)

else in Loops

You can also add an else block to loops. The else block will execute when the loop finishes normally (i.e.,
without a break).

for i in range(5):
print(i)
else:
print("Loop finished without break")

Infinite Loops

If the loop's condition never becomes False, the loop will run indefinitely.

Example:

while True:
print("This will run forever unless interrupted!")

To avoid infinite loops, ensure that the condition eventually becomes False.

These loops allow you to repeat actions and iterate over sequences, making your programs more efficient
and dynamic.

String:-
In Python, strings are a sequence of characters used to store text. Here's an overview of important aspects of
Python strings:

Creating Strings

You can create a string by enclosing text in either single quotes (') or double quotes ("):

string1 = 'Hello, World!'


string2 = "Hello, World!"
String Operations

 Concatenation: You can concatenate strings using the + operator.

str1 = 'Hello'
str2 = 'World'
result = str1 + ' ' + str2 # Result: 'Hello World'

 Repetition: Strings can be repeated using the * operator.

python
Copy code
result = 'Hello ' * 3 # Result: 'Hello Hello Hello '

String Indexing & Slicing

 Indexing: Access individual characters using their position (starting from 0).

s = 'Python'
print(s[0]) # P
print(s[-1]) # n (from the end)

 Slicing: Extract parts of the string.

s = 'Python'
print(s[0:3]) # Pyt (from index 0 to 2)
print(s[1:]) # ython (from index 1 to the end)

String Methods

Python strings come with built-in methods for various tasks:

 lower(): Converts string to lowercase.

print('HELLO'.lower()) # 'hello'

 upper(): Converts string to uppercase.

print('hello'.upper()) # 'HELLO'

 strip(): Removes leading/trailing whitespace.

print(' hello '.strip()) # 'hello'

 replace(): Replaces part of the string with another string.

print('hello world'.replace('world', 'Python')) # 'hello Python'

 split(): Splits a string into a list of substrings.

print('apple,banana,orange'.split(',')) # ['apple', 'banana', 'orange']

 join(): Joins elements of a list into a single string.

fruits = ['apple', 'banana', 'orange']


print(', '.join(fruits)) # 'apple, banana, orange'
String Formatting:-

String formatting in Python refers to the process of embedding variables, expressions, or values within a
string while allowing for customization in how these values are displayed. Python offers several methods for
string formatting, each with its strengths:

1. Using the % Operator

This is an old-style string formatting method, similar to C's printf:

Basic Syntax:
'format_string' % (values)

Example:

name = "Alice"
age = 25
formatted_str = "My name is %s and I am %d years old." % (name, age)
print(formatted_str) # Output: My name is Alice and I am 25 years old.

 %s: Inserts a string.


 %d: Inserts an integer.
 %f: Inserts a floating-point number (default precision of 6).
 %x: Inserts a hexadecimal number.

Example with multiple types:

name = "Alice"
age = 25
pi = 3.14159
formatted_str = "Name: %s, Age: %d, Pi: %.2f" % (name, age, pi)
print(formatted_str) # Output: Name: Alice, Age: 25, Pi: 3.14

 %.2f: Limits floating-point precision to 2 decimal places.

Pros & Cons:

 Pros: Simple for basic use cases, especially for C programmers.


 Cons: Limited flexibility, hard to read for complex cases, and considered outdated
compared to newer methods.

2. str.format() Method (Python 2.7+)

Introduced in Python 2.7, this method is more powerful and flexible than the % operator.

Basic Syntax:

"{}".format(value)

Example:

name = "Alice"
age = 25
formatted_str = "My name is {} and I am {} years old.".format(name, age)
print(formatted_str) # Output: My name is Alice and I am 25 years old.
Using Positional and Keyword Arguments

 Positional: You can refer to values using their positions.

print("The first value is {0} and the second value is {1}".format(10, 20))

 Named arguments: You can refer to values using named placeholders.

print("My name is {name} and I am {age} years old.".format(name="Alice", age=25))

3. F-Strings

F-strings (formatted string literals) are the most modern and efficient way to format strings in Python.

Basic Syntax:
f"your text {expression}"

Example:

name = "Alice"
age = 25
formatted_str = f"My name is {name} and I am {age} years old."
print(formatted_str) # Output: My name is Alice and I am 25 years old.

Expression Evaluation

F-strings allow you to insert not just variables, but also arbitrary expressions.

a = 5
b = 10
formatted_str = f"The sum of {a} and {b} is {a + b}."
print(formatted_str) # Output: The sum of 5 and 10 is 15.

Pros & Cons:

 Pros: Fast, concise, easy to read, and supports expressions.


 Cons: Only available in Python 3.6+.

Mutable and Immutable Data types:-


1. Mutable Data Types

List
A list is an ordered collection of items, and it can be modified (mutated) after creation. Here are the
operations you can perform on a list:

Operations:

 Creating a List:

my_list = [1, 2, 3]
 Accessing Elements:

print(my_list[0]) # Output: 1

 Modifying Elements:

my_list[0] = 10
print(my_list) # Output: [10, 2, 3]

 Adding Elements:
o Append: Add an element at the end.

my_list.append(4)
print(my_list) # Output: [10, 2, 3, 4]

o Insert: Add an element at a specific index.

my_list.insert(1, 20)
print(my_list) # Output: [10, 20, 2, 3, 4]

 Removing Elements:
o Remove by Value

my_list.remove(20)
print(my_list) # Output: [10, 2, 3, 4]

o Remove by Index:

my_list.pop(2)
print(my_list) # Output: [10, 2, 4]

 Slicing:

sublist = my_list[1:3]
print(sublist) # Output: [2, 4]

 Sorting:

my_list.sort()
print(my_list) # Output: [2, 4, 10]

Dictionary
A dictionary is a collection of key-value pairs. It is mutable, meaning you can change, add, or remove items.

Operations:

 Creating a Dictionary:

my_dict = {"name": "Alice", "age": 25}

 Accessing Values:

print(my_dict["name"]) # Output: Alice


 Adding/Modifying a Key-Value Pair:

my_dict["city"] = "New York"


print(my_dict) # Output: {'name': 'Alice', 'age': 25, 'city': 'New York'}

 Removing Key-Value Pairs:


o Remove by Key:

del my_dict["age"]
print(my_dict) # Output: {'name': 'Alice', 'city': 'New York'}

 Accessing Keys, Values, and Items:

print(my_dict.keys()) # Output: dict_keys(['name', 'city'])


print(my_dict.values()) # Output: dict_values(['Alice', 'New York'])
print(my_dict.items()) # Output: dict_items([('name', 'Alice'), ('city', 'New
York')])

Set
A set is an unordered collection of unique items. It is mutable, and elements can be added or removed.

Operations:

 Creating a Set:

my_set = {1, 2, 3}

 Adding Elements:

my_set.add(4)
print(my_set) # Output: {1, 2, 3, 4}

 Removing Elements:

my_set.remove(2)
print(my_set) # Output: {1, 3, 4}

 Set Operations:
o Union:

python
Copy code
set_a = {1, 2, 3}
set_b = {3, 4, 5}
union_set = set_a.union(set_b)
print(union_set) # Output: {1, 2, 3, 4, 5}

o Intersection:

intersection_set = set_a.intersection(set_b)
print(intersection_set) # Output: {3}
o Difference:

difference_set = set_a.difference(set_b)
print(difference_set) # Output: {1, 2}

2. Immutable Data Types

String
Strings are sequences of characters that cannot be changed once created. Any operation that "modifies" a
string actually creates a new string.

Operations:

 Creating a String:

python
Copy code
my_str = "Hello"

 Accessing Elements:

python
Copy code
print(my_str[0]) # Output: H

 String Concatenation:

python
Copy code
new_str = my_str + " World"
print(new_str) # Output: Hello World

 String Methods:
o Uppercase:

python
Copy code
print(my_str.upper()) # Output: HELLO

o Replace:

print(my_str.replace("H", "J")) # Output: Jello

 Slicing:

sliced_str = my_str[1:4]
print(sliced_str) # Output: ell

Tuple
A tuple is an immutable, ordered collection of items.
Operations:

 Creating a Tuple:

my_tuple = (1, 2, 3)

 Accessing Elements:

print(my_tuple[0]) # Output: 1

 Concatenating Tuples:

new_tuple = my_tuple + (4, 5)


print(new_tuple) # Output: (1, 2, 3, 4, 5)

 Slicing:

sliced_tuple = my_tuple[1:3]
print(sliced_tuple) # Output: (2, 3)

You might also like