Python Basics Code Full Notes
Python Basics Code Full Notes
print("Hello, World!")
Output: Hello, World!
Explanation:
● The print keyword is a built-in Python function.
name = "Meghna"
age = 25
print("Name:", name, "Age:", age)
Output:
Python-is-fun!
3. Understanding Variables
A variable is like a container that stores data values. In Python,
variables are created when you assign a value to them.
Example:
x = 10
name = "Meghna"
is_active = True
Explanation:
♦ x = 10: Assigns an integer value to x.
4. Printing Variables
You can combine variables with text in the print function:
Example:
name = "Meghna"
age = 25
printf("My name is {name} and I am {age} years old.")
Multiple Variables:
x, y, z = 10, 20, 30
print(f"x = {x}, y = {y}, z = {z}")
Chapter 2: Data Types in Python
1. Numeric Types
◦ Integer (int)
◦ Floating-point (float)
◦ Complex (complex)
2. Text Type
◦ String (str)
3. Boolean Type
◦ Boolean (bool)
4. Sequence Types
◦ List (list)
◦ Tuple (tuple)
◦ Range (range)
5. Mapping Type
◦ Dictionary (dict)
6. Set Types
◦ Set (set)
◦ Frozen Set (frozenset)
7. Binary Types
◦ Bytes (bytes)
◦ Byte Array (bytearray)
◦ Memory View (memoryview)
3. Detailed Overview of Data Types
A. Numeric Types
1. Integer (int):
o Stores whole numbers without a decimal point.
o Example:
x = 10
y = -5
print(type(x)) # Output: <class 'int'>
2. Floating-point (float):
o Stores numbers with a decimal point.
o Example:
x = 10
y = -5
print(type(x)) # Output: <class 'int'>
3. Complex (complex):
o Stores numbers with a real and imaginary part.
o Example:
num = 4 + 3j
print(type(num)) # Output: <class 'complex'>
B. Text Type
1. String (str):
o A sequence of characters enclosed in single, double, or triple
quotes.
o Example:
name = "Python"
print(type(name)) # Output: <class 'str'>
Strings are immutable, meaning they cannot be changed
after creation.
C. Boolean Type
1. Boolean (bool):
o Represents one of two values: True or False.
o Example:
is_active = True
print(type(is_active)) # Output: <class 'bool'>
D. Sequence Types
1. List (list):
o An ordered collection of items, which can be modified
(mutable).
o Example:
fruits = ["apple", "banana", "cherry"]
print(type(fruits)) # Output: <class 'list'>
2. Tuple (tuple):
o An ordered collection of items, which cannot be modified
(immutable).
o Example:
person = {"name": "John", "age": 30}
print(type(person)) # Output: <class 'dict'>
E. Set Types
1. Set (set):
o An unordered collection of unique items.
o Example:
colors = {"red", "green", "blue"}
print(type(colors)) # Output: <class 'set'>
2. Frozen Set (frozenset):
o Like a set, but immutable.
o Example
frozen_colors = frozenset(["red", "green", "blue"])
print(type(frozen_colors)) # Output: <class 'frozenset'>
F. Binary Types
1. Bytes (bytes):
o Immutable sequence of bytes.
o Example
data = b"Python"
print(type(data)) # Output: <class 'bytes'>
Hands-on Practice
1. Create variables of each type (int, float, str, bool, list, dict, etc.)
and print their types.
2. Write a program to convert a string of digits (e.g., "12345") into
an integer and add 10 to it.
3. Create a dictionary to store the names and ages of your friends.
Print the dictionary.
Lists, tuples, sets, and dictionaries in Python are considered both data
types and data structures, depending on the context. Here's a detailed
explanation to clarify this:
As Data Types
1. Definition: In Python, everything is an object, and every object
has a type. Lists, tuples, sets, and dictionaries are built-in data types
that represent collections of data.
2. Why Data Types?
◦ They define the kind of data being stored (e.g.,
ordered/unordered, mutable/ immutable).
◦ The type() function confirms their data type:
As Data Structures
1. Definition: A data structure refers to how data is organized,
stored, and manipulated in memory. Lists, tuples, sets, and
dictionaries provide structures to store multiple elements efficiently.
Summary
Concept Data Type Data Structure
Definition Predefined types in Python How data is organized for
(list, etc.). efficient use.
Focus Type/class of the object. Logical organization of data.
Example type([1, 2, 3]) returns <class Used to store, access, and
'list'>. manipulate data.
In essence:
• Technically: They are data types in Python because they belong
to predefined classes (list, tuple, etc.).
Syntax of input()
input(prompt)
• prompt: A string that is displayed on the screen to instruct or
request the user to provide input. This is optional.
• The function waits for the user to type something and press
Enter, then returns the entered value as a string.
Output:
What is your name? Alice Hello, Alice!
Explanation: The program asks the user for their name and greets
them using the provided input.
value = input()
print("You entered:", value)
Output:
Python is fun!
You entered: Python is fun!
Explanation: If no prompt is given, the program still waits for the
user’s input.
Since the input() function returns a string, you need to convert it into
the desired numeric type (e.g., int, float) for mathematical operations.
Output:
Enter your age: 25
Next year, you will be 26 years old.
Output:
# Incorrect
num1 = input("Enter first number: ")
num2 = input("Enter second number: ")
print("The sum is:", num1 + num2)
Output:
Enter first number: 5
Enter second number: 10
The sum is: 510
Explanation:
The input values are strings, so the + operator concatenates them
instead of performing arithmetic addition.
Solution:
2. Number Validation
Write a program that asks the user to enter a number and validates
the input. If the input is not a number, it should display an error
message.
3. Simple Calculator
Create a program that takes two numbers from the user and prints
their sum, difference, product, and quotient.
What is a String?
A string in Python is a sequence of characters enclosed within single
quotes ('), double quotes ("), or triple quotes (''' or """). Strings are one
of the most commonly used data types in Python and are immutable,
meaning their content cannot be changed once created.
Examples:
# Single-quoted string string1 = 'Hello, World!'
# Double-quoted string
string2 = "Python is awesome!"
string3 = '''This is
a multi-line string.'''
Creating Strings
Strings can be created using:
1. Single quotes ('example')
2. Double quotes ("example")
3. Triple quotes for multi-line strings ('''example''' or """example""")
Example:
Accessing Strings
You can access individual characters or slices of a string using
indexing and slicing.
Indexing:
Strings are indexed, starting from 0 for the first character and -1 for
the last character.
Example:
string = "Python"
print(string[0]) #
print(string[-1])
Output: P(first character)
Output: n(last character)
string = "Python"
print(string[0:4]) #
Output: Pyth (characters from index 0 to 3)
print(string[::2]) #
Output: Pto (every second character)
String Methods
Python provides several built-in methods to manipulate and interact
with strings. These methods do not modify the original string
(because strings are immutable) but return a new string.
string = "Hello"
print(len(string))
# Output: 5
String Operations
Concatenation:
Joining two or more strings using the + operator.
str1 = "Hello" str2 = "World"
print(str1 + " " + str2) # Output: Hello World
Repetition:
Repeating a string using the * operator.
string = "Hello"
print(string * 3) # Output: HelloHelloHello
Membership:
Checking if a substring exists within a string using in and not in.
string = "Python"
print("Py" in string) # Output: True print("Java" not in string)
#Output: True
String Types
1. Empty String: A string with no characters.
empty = ""
print(empty)
# Output: (blank line)
.””"
Types of Operators:
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Membership Operators
7. Identity Operators
1. Arithmetic Operators
Arithmetic operators are used to perform mathematical operations.
Example:
num1 = 15
num2 = 4
print("Addition:", num1 + num2) # Output: 19
print("Subtraction:", num1 - num2) # Output: 11
print("Multiplication:", num1 * num2) # Output: 60
print("Division:", num1 / num2) # Output: 3.75
print("Modulus:", num1 % num2) # Output: 3
print("Exponentiation:", num1 ** num2) # Output: 50625
print("Floor Division:", num1 // num2) # Output: 3
Example:
x = 10
y = 20
print("x == y:", x == y) # False
print("x != y:", x != y) # True
print("x > y:", x > y) # False
print("x < y:", x < y) # True
print("x >= y:", x >= y) # False
print("x <= y:", x <= y) # True
3. Logical Operators
Logical operators are used to combine conditional statements.
Example:
x=5
y = 10
print((x > 2) and (y > 5)) # True
print((x > 6) or (y > 5)) # True
print(not(x > 2)) # False
4. Bitwise Operators
Bitwise operators work on binary numbers at the bit level.
Operator Description Example Output
& AND 5&3 1
` ` `5 OR `3 7
^ XOR 5^3 6
~ NOT ~5 -6
<< Left Shift 5 << 1 10
>> Right Shift 5 >> 1 2
Example:
a = 5 # 0b0101 b = 3 # 0b0011
print("AND:", a & b) # Output: 1
print("OR:", a | b) # Output: 7
print("XOR:", a ^ b) # Output: 6
print("NOT:", ~a) # Output: -6
print("Left Shift:", a << 1) # Output: 10
print("Right Shift:", a >> 1) # Output: 2
5. Assignment Operators
Operato
Description Example Equivalent To
r
= Assigns value x=5 -
+= Add and assign x+=3 x=x + 3
-= Subtract and assign x-=3 x=x - 2
*= Multiply and assign x*=4 x=x * 4
/= Divide and assign x/=2 x=x / 2
%= Modulus and assign x%=3 x=x % 3
**= Exponent and assign x**=2 x=x **2
//= Floor divide and assign x//=3 x=x //3
Example:
x = 10
x += 5 # Equivalent to x = x + 5
print(x) # Output: 15
6. Membership Operators
Example:
my_list = [1, 2, 3, 4]
print(3 in my_list) # True
print(5 not in my_list) # True
7. Identity Operators
Identity operators compare memory locations of two objects.
Example:
a =b =[1, 2, 3]
c = [1, 2, 3,4]
print(a is b) # True
print(a is c) # False
print(a is not c)# True
Summary
This chapter introduces Python operators and their applications in
performing various operations. Operators are essential in
programming and are used across a variety of scenarios. By
mastering them, you’ll be able to write powerful and efficient Python
code!
• if
• else
• elif (short for "else if")
if condition1:
# Code block to execute if condition1 is true elif condition2:
# Code block to execute if condition2 is true else:
# Code block to execute if none of the conditions are
True
6.3 Understanding Conditions
Conditions in Python are usually comparisons or logical expressions
that evaluate to True or
False.
Examples of conditions:
age = 18
if age >= 18:
print("You are eligible to vote!")
age = 16
if age >= 18:
print("You are eligible to vote!") else:
print("You are not eligible to vote yet.")
6.4.3 The elif Statement
Example:
marks = 85
if marks >= 90:
print("Grade: A+")
elif marks >= 75:
print("Grade: A")
elif marks >= 60:
print("Grade: B")
else:
print("Grade: C")
Example:
number = 10
if number > 0:
if number % 2 == 0:
print("The number is positive and even.")
else:
print("The number is positive but odd.")
else:
print("The number is not positive.")
Example:
age = 20
citizenship = "Indian"
if age >= 18 and citizenship == "Indian":
print("You are eligible to vote.")
Example:
x = 10
if x > 0:
pass # Code to be written later
# Correct
if x == 10:
print("x is 10")
Key Takeaways
• Conditional statements allow programs to make decisions based
on conditions.
• Use if for a single condition, else for alternative actions, and elif
for multiple conditions.
• Logical operators (and, or, not) help in combining conditions.
• Always test and debug your conditions to ensure logical
correctness.
Exercise:
1. Write a program to check whether a number is positive,
negative, or zero.
2. Create a program that asks for a user's age and prints whether
they are a child, teenager, adult, or senior citizen.
# With a loop
for i in range(1, 4):
print(i)
Syntax:
apple
banana
cherry
Example 2: Using range()
for i in range(5):
print(i)
Output:
0
1
2
3
4
Syntax:
counter = 0
while counter < 5:
print(counter)
counter += 1
Output:
0
1
2
3
4
password = "python123"
user_input = ""
while user_input != password:
user_input = input("Enter password: ")
print("Access granted!")
4. Nested Loops
Loops can be nested, meaning one loop is inside another.
Example:
5. Control Statements
break
Exits the loop prematurely.
for i in range(10):
if i == 5:
break
print(i)
Output:
0
1
2
3
4
continue
Skips the current iteration and moves to the next one.
for i in range(5):
if i == 2:
continue
print(i)
Output:
0
1
3
4
pass
Does nothing; acts as a placeholder.
for i in range(3):
pass
Problem 1: Multiplication Table
while True:
# Code block if condition:
break
How It Works
1. Condition Check: The while loop checks the condition, which in
this case is True. Since True is always True, the loop runs infinitely.
2. Execution of Code Block: The statements inside the loop are
executed repeatedly.
3. Termination: The loop is terminated when a break statement is
encountered or the program is stopped manually.
Example 1: Basic Infinite Loop
while True:
print("This will print endlessly unless we stop it.")
while True:
user_input = input("Enter something (type 'exit' to quit): ")
if user_input.lower() == "exit":
print("Exiting the loop. Goodbye!")
break
print(f"You entered: {user_input}")
Explanation:
• The loop keeps asking for user input until the user types exit.
• When exit is typed, the if condition becomes True, and the break
statement stops the loop.
Sample Output:
while True:
guess = int(input("Guess the number (between 1 and 10): "))
if guess == number_to_guess:
print("Correct! You guessed the number!")
break
elif guess < number_to_guess:
print("Too low. Try again!")
else:
print("Too high. Try again!")
Explanation:
Precautions
Practice Problems
1. Write a while True loop that asks for a password. Break out of
the loop when the correct password is entered.
2. Create a loop to simulate a basic ATM system where users can
check their balance, deposit, or withdraw money until they choose to
exit.
Practice Problems
1. Guess the Number Game
Write a program where the user has to guess a randomly generated
number between 1 and 100. The program should provide feedback if
the guess is too high or too low and continue until the user guesses
correctly.
high or too low and continue until the user guesses correctly.
import random
number_to_guess = random.randint(1, 100)
while True:
guess = int(input("Guess the number (between 1 and
100):"))
if guess == number_to_guess:
print("Congratulations! You guessed the
correctnumber.")
break
elif guess < number_to_guess:
print("Too low! Try again.")
else:
print("Too high! Try again.")
Explanation:
• Uses the random library to generate a random number.
• Implements a while loop to repeatedly take guesses.
• Uses conditional statements to guide the user.
2. Palindrome Checker
def is_palindrome(string):
string = string.lower().replace(" ", "") # Normalize the string
return string == string[::-1]
Explanation:
• Converts the string to lowercase and removes spaces.
• Compares the string with its reverse using slicing.
• Uses an if statement to check the condition.
3. Multiplication Table
Print the multiplication table of a number provided by the user.
number = int(input("Enter a number: "))
for i in range(1, 11):
print(f"{number} x {i} = {number * i}")
Explanation:
• Uses a for loop to iterate from 1 to 10.
• Prints the result of the multiplication using an f-string.
4. Calculate Factorial
Calculate the factorial of a given number using a while loop.
Explanation:
• Multiplies the number by decrementing it in a while loop.
• Stops when the number becomes 1.
Explanation:
• Uses a for loop to iterate through the string.
• Checks if each character is in the set of vowels.
Exploring Libraries
1. Math Library
The math library provides mathematical functions.
Example Functions:
import math
# Square root
print(math.sqrt(16)) # Output: 4.0
# Power
print(math.pow(2, 3)) # Output: 8.0
# Trigonometric functions
print(math.sin(math.pi / 2)) # Output: 1.0
# Rounding
print(math.floor(4.7)) # Output: 4 print(math.ceil(4.3)) #
Output: 5
2. Random Library
The random library is used to generate random numbers and choices.
Example Functions:
import random
# Random integer
print(random.randint(1, 10)) # Random number between 1 and
10
# Random choice
colors = ["red", "blue", "green"]
print(random.choice(colors))
# Shuffle a list
numbers = [1, 2, 3, 4, 5] random.shuffle(numbers)
print(numbers)
# Random float
print(random.uniform(1.5, 3.5)) # Random float between 1.5 and
3.5
3. Time Library
The time library is used to manage time-related tasks.
Example Functions:
import time
print(time.ctime())
4. OS Library
The os library provides a way to interact with the operating system.
Example Functions:
import os
import random
import string
1. Lists
Definition:
A list is an ordered collection of items that can hold elements of any
data type. Lists are mutable, meaning their contents can be changed
after creation.
Characteristics:
• Ordered: Elements maintain their insertion order.
• Mutable: Elements can be added, modified, or removed.
• Heterogeneous: Can store elements of different data types.
Examples:
# Creating a list
fruits = ["apple", "banana", "cherry"]
print(fruits) # Output: ['apple', 'banana', 'cherry']
Needs to be table
Method Description Example
append(element) Adds an element to the end of the
fruits.append("orang
insert(index, element) Inserts an element at a specified index
fruits.insert(1, "grape")
pop([index]) Removes and returns an element at an index
fruits.pop(2)
remove(element) Removes the first occurrence of a
fruits.remove("banan
sort() Sorts the list in ascending order fruits.sort()
reverse() Reverses the list order fruits.reverse()
len() Returns the number of elements in len(fruits)
Why Mutable?
Lists are mutable because they allow in-place modifications, making
them suitable for scenarios where the data needs to change
dynamically.
2. Tuples
Definition:
A tuple is an ordered collection of items similar to a list, but tuples
are immutable.
Characteristics:
• Ordered: Elements maintain their insertion order.
• Immutable: Cannot modify elements after creation.
• Heterogeneous: Can store elements of different data types.
Examples:
# Creating a tuple
tuple_example = ("apple", "banana", "cherry")
print(tuple_example) # Output: ('apple', 'banana', 'cherry')
# Single-element tuple
single = ("hello",) # Comma is necessary for a single- element
tuple
print(single) # Output: ('hello',)
Common Methods:
Needs to be a table
Method Description Example
count(value) Counts occurrences of a value
tuple_example.count("apple")
index(value) Returns the index of the value
tuple_example.index("banana")
Why Immutable?
Tuples are immutable to ensure data integrity, making them suitable
for fixed collections of data such as coordinates or configuration
values.
3. Sets
Definition:
Characteristics:
• Unordered: Does not maintain any specific order.
• Mutable: Elements can be added or removed.
• Unique: No duplicate elements.
Examples:
# Creating a set
numbers = {1, 2, 3, 4, 5}
print(numbers) # Output: {1, 2, 3, 4, 5}
Why Unordered?
Sets are unordered because they are optimized for fast lookups and
ensure uniqueness, making them ideal for membership tests.
4. Dictionaries
Definition:
A dictionary is an unordered collection of key-value pairs, where
each key is unique.
Characteristics:
• Unordered (Python < 3.7): Keys are not stored in any specific
order.
• Ordered (Python ≥ 3.7): Maintains insertion order.
• Mutable: Can add, modify, or delete key-value pairs.
• Unique Keys: Keys must be unique, but values can repeat.
Examples:
# Creating a dictionary
person = {"name": "John", "age": 30, "city": "New York"}
print(person) # Output: {'name': 'John', 'age': 30, 'city': 'New
York'}
Common Methods:
Why Mutable?
Dictionaries are mutable because they often store dynamic data that
may change during program execution.
Summary Table
Conclusion
Understanding Python's built-in data structures is crucial for writing
efficient and readable code. By leveraging the unique features of lists,
tuples, sets, and dictionaries, you can solve various programming
problems effectively. Their characteristics—such as mutability, order,
and uniqueness—determine how and when to use them.
import random
# List of fruits
fruits = ["apple", "banana", "cherry", "date", "elderberry"]
import random
import random
nested_dict = {
f"list_{i}": [random.randint(1, 10) for _ in range(5)] for i in
range(3)
}
# Draw 5 cards
hand = [deck.pop() for _ in range(5)] print("Your hand:")
for card in hand:
print(card)
import random
# Generate random numbers and group them into even and odd
numbers = [random.randint(1, 50) for _ in range(20)]
print(f"Numbers: {numbers}")
print(f"Even numbers: {even_numbers}")
print(f"Odd numbers: {odd_numbers}")
These examples highlight the versatility of Python's data structures
and their seamless integration
with libraries like random. Feel free to modify and expand upon
them!
1. What is a Function?
A function is a block of code that runs only when it is called.
Functions allow us to pass data, known as parameters, and return
data as a result.
Syntax:
def greet(name):
return f"Hello, {name}!"
2. Types of Functions
2.1 Built-in Functions
Python comes with many built-in functions, such as print(), len(),
sum(), etc. Example:
numbers = [1, 2, 3, 4, 5]
print(len(numbers)) # Output: 5
print(sum(numbers)) # Output: 15
result = add_numbers(3, 7)
print(result) # Output: 10
square = lambda x: x ** 2
print(square(5)) # Output: 25
3. Function Arguments
Functions can accept arguments (inputs) to work with.
def greet(name="Guest"):
print(f"Hello, {name}!")
greet() # Output: Hello, Guest!
greet("Alice") # Output: Hello, Alice!
def add_all(*numbers):
return sum(numbers)
print(add_all(1, 2, 3, 4)) # Output: 10
def print_details(**details):
for key, value in details.items():
print(f"{key}: {value}")
print_details(name="Alice", age=30, city="New York")
4. Returning Values
Functions can return a value using the return statement.
Example:
Example:
global_var = 20
def my_function():
print(global_var)
my_function() # Output: 20
global_var = 20
def modify_global():
global global_var
global_var += 10
modify_global()
print(global_var) # Output: 30
6. Advanced Examples
Example 1: Factorial Function(with recursion)
def factorial(n):
if n == 0 or n == 1:
return 1
return n * factorial(n - 1)
print(factorial(5)) # Output: 120
fibonacci(10) # Output: 0 1 1 2 3 5 8 13 21 34
def is_palindrome(string):
return string == string[::-1]
print(is_palindrome("radar")) # Output: True
print(is_palindrome("hello")) # Output: False
import random
def generate_random_list(size, start, end):
return [random.randint(start, end) for _ in range(size)]
random_list = generate_random_list(5, 1, 100)
print(random_list)