Python Notes Basics
Python Notes Basics
Python Notes Basics
Features of python:
1. Easy to Learn and Read: Python's syntax is designed to be clear and readable, making it accessible
for beginners and experienced developers alike.
2. Interpreted Language: Python is an interpreted language, meaning that code is executed line by
line, which allows for easier debugging and testing.
3. High-level Language: Python abstracts many complex details away from the programmer,
providing high-level data types and constructs that simplify coding.
4. Dynamic Typing: Python uses dynamic typing, meaning you don't need to declare the type of a
variable before using it. This can lead to faster development times and more flexibility.
5. Rich Standard Library: Python comes with a comprehensive standard library that includes modules
and packages for a wide range of tasks, from file I/O to web development.
6. Object-Oriented: Python supports object-oriented programming (OOP) principles, allowing for the
creation and manipulation of objects with properties and methods.
7. Open Source: Python is open source, meaning that its source code is freely available and can be
modified and distributed by anyone.
In Python, data types represent the type or category of data stored in variables or used in expressions. Python
is dynamically typed, meaning that the interpreter automatically determines the data type of a variable based
on the value assigned to it. Here's an explanation of various data types in Python:
1.Numeric Types:
int: Integer data type represents whole numbers without any decimal point.
Example: x = 5
Example: y = 3.14
complex: Complex data type represents numbers with a real and imaginary part.
Example: z = 2 + 3j
2.Sequence Types:
str: String data type represents a sequence of characters enclosed within single quotes ('') or double quotes
("").
list: List data type represents an ordered collection of items enclosed within square brackets ([]).
tuple: Tuple data type represents an ordered, immutable collection of items enclosed within parentheses ().
3.Boolean Type:
bool: Boolean data type represents the truth values True and False.
COMMENTING IN PYTHON:
comments are used to add explanatory notes or annotations within the source code. They are ignored by the
Python interpreter during execution and serve the purpose of improving code readability and understanding.
Syntax:
Single-line comments start with the # symbol and continue until the end of the line.
Multi-line comments are not supported in Python, but multi-line strings (docstrings) can serve a similar
purpose.
Purpose of Comments:
Clarifying code: Comments can explain complex logic, algorithms, or tricky parts of the code to make it easier
for other developers (or your future self) to understand.
Providing context: Comments can provide context or background information about why certain decisions
were made or why specific code was implemented in a certain way.
Temporary code: Comments can be used to temporarily disable or comment out sections of code during
debugging or testing.
Documentation: Docstrings serve as documentation strings that can be accessed using Python's built-in help()
function or tools like Sphinx for generating documentation.
VARIABLES IN PYTHON:
Variables in Python are used to store and manipulate data. They serve as containers to hold values of different
types.
Variables are fundamental in Python programming and are used extensively to store and manipulate data
throughout the execution of a program. They provide a way to access and work with information dynamically,
making Python a versatile and powerful language for various applications.
Variable Declaration:
No explicit declaration of data type is required; Python infers the data type from the value assigned to the
variable.
Example:
x = 25
name = "chandu"
is_valid = True
Variable names can contain letters (a-z, A-Z), digits (0-9), and underscores (_).
Data Types:
Variables in Python can hold values of different data types, such as integers, floats, strings, booleans, lists,
tuples, dictionaries, etc.
Example:
age = 25 # Integer
IDENTIFIERS IN PYTHON:
In Python, identifiers are names given to various program elements such as variables, functions, classes,
modules, etc. Identifiers are used to uniquely identify these elements throughout the code. Here's an
explanation of identifiers in terms of Python:
Definition:
An identifier is a sequence of characters in Python used to name variables, functions, classes, modules, etc.
It can be of any length and can contain uppercase letters, lowercase letters, digits, and underscores (_).
Identifiers are case-sensitive, meaning myVar and myvar are different identifiers.
Example of invalid identifiers: 1var (starts with a digit), if (keyword), my-var (contains hyphen), etc.
INPUT OPERATIONS:
In Python, the input() function is used to take input from the user through the keyboard. It prompts the user to
enter data and then waits for the user's input.
Working of input():
When the input() function is called, the program pauses execution and waits for the user to input some data.
Once the user enters the data and presses the Enter key, the input is read from the keyboard and returned as a
string.
The program then resumes execution with the input data stored in a variable.
The input() function is a simple yet powerful way to interact with users and receive input data in Python
programs. It's commonly used in command-line interfaces, simple text-based games, and various other
interactive applications. However, when using input(), it's essential to handle user input validation and type
conversion to ensure the robustness and reliability of the program.
Examples :
OPERATORS IN PYTHON:
In Python, operators are special symbols or keywords that perform operations on operands. Operands are the
values or variables operated on by the operators. Python supports various types of operators, including:
1. Arithmetic Operators:
- Arithmetic operators are used to perform mathematical operations such as addition, subtraction,
multiplication, division, modulus, and exponentiation.
x=5+3 # Addition
y = 10 - 4 # Subtraction
z=2*6 # Multiplication
w=8/2 # Division
r = 10 % 3 # Modulus (remainder)
- Comparison operators are used to compare the values of operands. They return a Boolean value (True or
False) based on the comparison result.
- Examples:
c == d # Equal to
m != n # Not equal to
3. Logical Operators:
- Logical operators are used to combine conditional statements and return a Boolean result (True or False).
- Examples:
4. Assignment Operators:
- Examples:
z -= 3 # Subtract 3 from the current value of z and assign the result back to z
5. Membership Operators:
- Membership operators are used to test if a value or variable is present in a sequence (such as strings, lists,
tuples, sets, or dictionaries).
- Examples:
6. Identity Operators:
- Identity operators are used to compare the memory locations of two objects.
- Examples:
7. Bitwise Operators:
- Examples:
a|b # Bitwise OR
~c # Bitwise NOT
operations on strings:
In Python, strings are sequences of characters enclosed within either single quotes ('') or double quotes ("").
Python provides a variety of built-in functions and methods for performing operations on strings. Here are
some common operations on strings in Python:
Concatenation:
Concatenation is the process of combining two or more strings into a single string.
Example:
first_name = "John"
last_name = "Doe"
The len() function is used to get the length of a string, i.e., the number of characters in the string.
Example:
length = len(message)
print(length) # Output: 13
1.Lists:
Lists are ordered collections of items, which can be of any data type (including other lists).
Lists are mutable, meaning their elements can be changed after creation.
Example:
2.Tuples:
Tuples are similar to lists, but they are immutable, meaning their elements cannot be changed after creation.
Example:
python
Copy code
3.Sets:
4.Dictionaries:
Dictionaries are collections of key-value pairs, where each key is associated with a value.
Dictionaries are created using curly braces {} with key-value pairs separated by colons (:).
Example:
In Python, type conversion, also known as type casting or type coercion, refers to the process of converting
one data type into another. Python provides built-in functions for converting between different data types.
1.int():
Example:
2.float():
Example:
3.str():
Example:
4.bool():
Example:
They allow you to convert data from one type to another as needed in your program. Understanding how to
perform type conversion is essential for handling different data types and ensuring compatibility between
them in Python programs.
Selection or conditional branching statements-if, if else , nested if,
if elif else:
1.if statement:
The if statement is used to execute a block of code only if a specified condition is true.
If the condition is true, the code block following the if statement is executed; otherwise, it is skipped.
Example:
if condition:
Example:
x = 10
if x > 5:
2.if-else statement:
The if-else statement extends the functionality of the if statement by providing an alternative code block to
execute if the condition is false.
With if-else, you can handle both true and false outcomes of a condition, enabling different actions based on
whether the condition is met or not.
It's like making a binary decision: if the condition is true, one thing happens; if it's false, something else
happens.
The if-else statement allows you to execute one block of code if a condition is true and another block of code if
the condition is false.
Syntax:
if condition:
else:
# Code block to execute if condition is false
Example:
x=3
if x > 5:
else:
3.Nested if statement:
The inner if statement is only executed if the outer if statement's condition is true.
Nested if statements can be used to check for additional conditions or perform more specific actions based on
the outcome of previous conditions.
Nested if statement:
Syntax:
if condition1:
if condition2:
Example:
x = 10
if x > 5:
if x == 10:
print("x is equal to 10")
4.if-elif-else statement:
The if-elif-else statement provides a way to evaluate multiple conditions sequentially, with each condition
being tested only if the previous conditions are false.
It's useful when you have multiple conditions to check and want to execute different code blocks based on
which condition is true first.
The elif (short for "else if") allows you to check additional conditions after the initial if statement.
If none of the conditions are true, the code block following the else statement is executed.
These conditional branching statements are essential tools for creating programs that can adapt their behavior
based on varying conditions. They enable decision-making and control the flow of execution in Python
programs, making them more dynamic and versatile. Understanding how to use these statements effectively is
fundamental for writing clear, concise, and efficient code.
It executes the code block associated with the first true condition and skips the remaining conditions.
Syntax:
python
Copy code
if condition1:
elif condition2:
else:
Example:
python
Copy code
x = 20
if x > 10:
else:
loops or iterative:
Loops:
Loops are fundamental programming constructs that allow you to execute a block of
code repeatedly until a certain condition is met. They're essential for automating
tasks, iterating over collections of data, and controlling program flow.
Types of Loops:
While Loops:
o In a while loop, the code block is executed as long as a specified
condition remains True. The condition is checked at the beginning of
each iteration.
o Syntax:
o while condition:
o # code to be executed
o Example:
i = 0
while i < 5:
print(i)
i += 1 # Increment i to eventually exit the loop
For Loops:
o for loops provide a concise way to iterate over elements in a sequence
o Example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Nested Loops
Nested loops involve placing one loop inside another loop. The inner loop executes
completely for each iteration of the outer loop. This allows for more complex
operations that require iterating over multiple sequences or data structures.
Example:
for i in range(2):
for j in range(3):
print(f"({i}, {j})")
o Example:
for num in range(10):
if num == 7:
break
print(num)
This code will print numbers 0 to 6 and then exit the loop.
Continue Statement:
o Skips the current iteration of the loop and moves on to the next one.
o Syntax:
o continue
o Example:
for num in range(10):
if num % 2 == 0: # Skip even numbers
continue
print(num)
1.perfect number
# if the sum of divisors is equall to the given number then it is called as perfect number
n= int(input())
s=0
for i in range(1,(n//2)+1):
if(n%i==0):
s+=i
if(s==n):
print("perfect")
else:
print("not perfect")
2. Times table
k=int(input("which table"))
n=int(input("table up to"))
for i in range(0,n+1):
for j in range(0,j+1):
print(k,"x",i,"=",k*i)