Python Notes Basics

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 18

UNIT-1

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.

DATA TYPES IN PYTHON:

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

float: Float data type represents numbers with a decimal point.

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
("").

Example: name = "Alice"

list: List data type represents an ordered collection of items enclosed within square brackets ([]).

Example: my_list = [1, 2, 3]

tuple: Tuple data type represents an ordered, immutable collection of items enclosed within parentheses ().

Example: my_tuple = (4, 5, 6)

3.Boolean Type:

bool: Boolean data type represents the truth values True and False.

Example: is_valid = True

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:

Variables in Python are declared by simply assigning a value to a name.

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 Naming Rules:

Variable names can contain letters (a-z, A-Z), digits (0-9), and underscores (_).

They cannot start with a digit.

Variable names are case-sensitive (my_variable is different from My_Variable).

Python keywords cannot be used as variable names.

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

height = 5.9 # Float


name = "chandu" # String

is_valid = True # Boolean

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: x, my_variable, calculate_area, Employee, my_module, etc.

Rules for Naming Identifiers:

Must begin with a letter (a-z, A-Z) or an underscore (_).

Subsequent characters can be letters, digits (0-9), or underscores (_).

Cannot begin with a digit.

Cannot be a Python keyword or reserved word.

Should be descriptive and meaningful to convey their purpose.

Example of valid identifiers: my_var, _myVar, calculate_area, employee_name, etc.

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 :

Taking inputs of different data types from the user

m=input() # takes string as a input

n=int(input()) #takes numbers as a input

k=float(input()) #takes pointes values as a input eg: 2.3,234.2,2.2

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)

p = 2 ** 3 # Exponentiation (2 raised to the power of 3)

2. Comparison (Relational) Operators:

- Comparison operators are used to compare the values of operands. They return a Boolean value (True or
False) based on the comparison result.

- Examples:

x>y # Greater than


a<b # Less than

c == d # Equal to

m != n # Not equal to

p >= q # Greater than or equal to

r <= s # Less than or equal to

3. Logical Operators:

- Logical operators are used to combine conditional statements and return a Boolean result (True or False).

- Examples:

x > 5 and y < 10 # Logical AND

a < 20 or b > 30 # Logical OR

not (c == d) # Logical NOT (negation)

4. Assignment Operators:

- Assignment operators are used to assign values to variables.

- Examples:

x = 10 # Assign value 10 to variable x

y += 5 # Add 5 to the current value of y and assign the result back to y

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:

x in my_list # True if x is found in my_list

y not in my_set # True if y is not found in my_set

6. Identity Operators:
- Identity operators are used to compare the memory locations of two objects.

- Examples:

x is y # True if x and y refer to the same object

a is not b # True if a and b do not refer to the same object

7. Bitwise Operators:

- Bitwise operators are used to perform bit-level operations on binary numbers.

- Examples:

x&y # Bitwise AND

a|b # Bitwise OR

~c # Bitwise NOT

d^e # Bitwise XOR

f << 2 # Left shift by 2 bits

g >> 3 # Right shift by 3 bits

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.

The + operator is used for concatenation.

Example:

first_name = "John"

last_name = "Doe"

full_name = first_name + " " + last_name

print(full_name) # Output: John Doe


String Length:

The len() function is used to get the length of a string, i.e., the number of characters in the string.

Example:

message = "Hello, World!"

length = len(message)

print(length) # Output: 13

Other data types in python:


In addition to the fundamental data types like integers, floats, strings, and booleans, Python supports several
other data types that are useful for specific scenarios. Here are some of the other data types in Python:

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.

Lists are created using square brackets [].

Example:

my_list = [1, 2, 3, 'a', 'b', 'c']

2.Tuples:

Tuples are similar to lists, but they are immutable, meaning their elements cannot be changed after creation.

Tuples are created using parentheses ().

Example:

python

Copy code

my_tuple = (1, 2, 3, 'a', 'b', 'c')

3.Sets:

Sets are unordered collections of unique elements.

Sets do not allow duplicate elements.

Sets are created using curly braces {} or the set() function.

Example: my_set = {1, 2, 3, 3, 4}

4.Dictionaries:
Dictionaries are collections of key-value pairs, where each key is associated with a value.

Dictionaries are unordered and mutable.

Dictionaries are created using curly braces {} with key-value pairs separated by colons (:).

Example:

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}

Type conversions in python:

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():

Converts a value to an integer data type.

Example:

x = int("10") # Converts the string "10" to the integer 10

2.float():

Converts a value to a floating-point data type.

Example:

y = float("3.14") # Converts the string "3.14" to the float 3.14

3.str():

Converts a value to a string data type.

Example:

z = str(100) # Converts the integer 100 to the string "100"

4.bool():

Converts a value to a boolean data type.

Example:

a = bool(0) # Converts the integer 0 to the boolean False

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.

It helps in making decisions based on whether a condition evaluates to true or false.

If the condition is true, the code block following the if statement is executed; otherwise, it is skipped.

It's a fundamental building block of decision-making in programming.

Example:

if condition:

# Code block to execute if condition is true

Example:

x = 10

if x > 5:

print("x is greater than 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:

# Code block to execute if condition is true

else:
# Code block to execute if condition is false

Example:

x=3

if x > 5:

print("x is greater than 5")

else:

print("x is not greater than 5")

3.Nested if statement:

A nested if statement is an if statement inside another if statement.

It allows for more complex decision-making by evaluating multiple conditions sequentially.

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:

A nested if statement is an if statement inside another if statement.

It allows you to check for multiple conditions sequentially.

Syntax:

if condition1:

# Code block to execute if condition1 is true

if condition2:

# Code block to execute if both condition1 and condition2 are true

Example:

x = 10

if x > 5:

print("x is greater than 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.

The if-elif-else statement allows you to check multiple conditions sequentially.

It executes the code block associated with the first true condition and skips the remaining conditions.

Syntax:

python

Copy code

if condition1:

# Code block to execute if condition1 is true

elif condition2:

# Code block to execute if condition1 is false and condition2 is true

else:

# Code block to execute if both condition1 and condition2 are false

Example:

python

Copy code

x = 20

if x > 10:

print("x is greater than 10")


elif x == 10:

print("x is equal to 10")

else:

print("x is less than 10")

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

(like lists, strings, or tuples). The loop automatically iterates through


each item in the sequence, assigning it to a variable you define.
o Syntax:
o for item in sequence:
o # code to be executed for each item

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})")

This code will print:


(0, 0) (0, 1) (0, 2)
(1, 0) (1, 1) (1, 2)

Loop Control Statements


 Break Statement:
o Exits (terminates) the current loop immediately, regardless of the loop
condition.
o Syntax:
o break

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)

This code will print only odd numbers (1, 3, 5, 7, 9).


 Pass Statement:
o Acts as a placeholder within a loop or other control flow construct,
indicating that no action should be taken at that point. It's often used to
maintain the structure of your code for future modifications.
o Syntax:
o pass

Else Statement with Loops


The else statement can be used optionally with for loops. It's executed only if the
loop completes normally (i.e., without encountering a break). This allows you to
perform some action after the loop finishes iterating through the sequence.
Example:
for num in range(5):
print(num)
else:
print("Loop completed!")

This code will print numbers 0 to 4 and then "Loop completed!".

Some practice codes using loops:

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)

You might also like