0% found this document useful (0 votes)
7 views5 pages

Python Programming Basics Guide

This document provides detailed notes on Python programming, covering essential topics such as input/output, variables, data types, type conversion, operators, conditional statements, loops, functions, data structures, file handling, exception handling, and object-oriented programming. Each section includes examples to illustrate the concepts. The notes serve as a comprehensive guide for understanding and using Python effectively.

Uploaded by

Sanjay Thorat
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views5 pages

Python Programming Basics Guide

This document provides detailed notes on Python programming, covering essential topics such as input/output, variables, data types, type conversion, operators, conditional statements, loops, functions, data structures, file handling, exception handling, and object-oriented programming. Each section includes examples to illustrate the concepts. The notes serve as a comprehensive guide for understanding and using Python effectively.

Uploaded by

Sanjay Thorat
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Python Detailed Notes with

Programming

1. Input and Output


Input → input() is used to take user input (always as string).
Output → print() is used to display data.

Example:
name = input("Enter your name: ")
print("Hello,", name)

2. Variables
A variable stores data. No need to declare type (Python is dynamically typed).
x = 10
y = "Python"
z = 3.5

3. Data Types
- int → integers (10, -5)
- float → decimal numbers (3.14)
- str → text ("Hello")
- bool → True/False
- list → ordered collection [1,2,3]
- tuple → immutable collection (1,2,3)
- dict → key-value pairs {"name": "Sanjay"}
- set → unique unordered items {1,2,3}

a = 10 # int
b = 3.5 # float
c = "Python" # str
d = True # bool

4. Type Conversion
Converting one data type into another.

x = "100"
y = int(x) # string → int
print(y + 50) # Output: 150

5. Operators
- Arithmetic: +, -, *, /, %, **, //
- Relational: >, <, >=, <=, ==, !=
- Logical: and, or, not
- Assignment: =, +=, -=, *=

a = 10
b=3
print(a+b, a-b, a*b, a/b, a%b)

6. Conditional Statements
Used for decision making.

marks = 75
if marks >= 90:
print("Grade A")
elif marks >= 60:
print("Grade B")
else:
print("Grade C")

7. Loops
For Loop Example:

for i in range(1, 6):


print("Day", i)

While Loop Example:

n=5
while n > 0:
print("Countdown:", n)
n -= 1

8. Functions
Reusable block of code.

def greet(name):
return "Hello, " + name

print(greet("Amit"))
9. Data Structures
List Example:

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


print(fruits[0]) # apple

Dictionary Example:

student = {"name": "Priya", "marks": 88}


print(student["name"])

10. File Handling


Writing to file and reading from file.

# Writing to file
with open("[Link]", "w") as f:
[Link]("Hello, Python!")

# Reading from file


with open("[Link]", "r") as f:
print([Link]())

11. Exception Handling


Handle errors gracefully.

try:
num = int("abc")
except ValueError:
print("Invalid number!")

12. Object-Oriented Programming (OOP)


OOP uses classes & objects.
Key Concepts: Encapsulation, Inheritance, Polymorphism, Abstraction.
class Student:
def __init__(self, name, marks):
[Link] = name
[Link] = marks

def display(self):
print(f"Name: {[Link]}, Marks: {[Link]}")

s1 = Student("Sanjay", 90)
[Link]()

Common questions

Powered by AI

Python implements object-oriented programming using classes and objects. A class serves as a blueprint for objects, encapsulating data and behavior. For instance, the class Student is defined with attributes name and marks, and a method display(): class Student: def __init__(self, name, marks): self.name = name; self.marks = marks; def display(self): print(f'Name: {self.name}, Marks: {self.marks}'). You can create an object of the class like s1 = Student('Sanjay', 90); s1.display(), which will utilize the class-defined structure and behavior.

Python provides several basic data structures to store and manage data efficiently. Lists are used for ordered collections, allowing duplicate entries (e.g., fruits = ['apple', 'banana']). Dictionaries store data in key-value pairs, useful for quick lookups (e.g., student = {'name': 'Priya', 'marks': 88}). Each data structure has unique characteristics, serving different needs depending on the type and organization of data required.

File handling in Python allows programs to read from and write to files, enabling data persistence beyond program execution. Writing data to a file involves opening the file in write mode and using the write() method: with open('data.txt', 'w') as f: f.write('Hello, Python!'). To read data, open the file in read mode: with open('data.txt', 'r') as f: print(f.read()). File handling is essential for storing data that should not be lost when a program stops, supporting scenarios like saving user preferences or log records.

In Python, loops are used to execute a block of code repeatedly. The for loop iterates over a sequence of elements, such as a list or range, and executes the block of code for each element: for i in range(1, 6): print('Day', i). The while loop, however, continues execution as long as a specified condition is true: n = 5; while n > 0: print('Countdown:', n); n -= 1. The key difference is that for loops are used for known iterations, while while loops are used when the number of iterations is uncertain until a condition changes.

In Python, the division operator '/' generally performs floating-point division, returning a float result. For example, 5 / 2 yields 2.5. Conversely, the '//' operator performs integer division (floor division), returning the greatest whole number less than or equal to the division result, such as 5 // 2 yielding 2.

Python handles user input using the input() function, which always reads data as a string. To display output, the print() function is commonly used. For example, you can take a user's name as input and greet them with: name = input('Enter your name: '); print('Hello,', name)

Type conversion in Python is the process of changing a variable from one data type to another. This can be done explicitly using functions like int(), float(), and str(). For example, to convert a string representing a number to an integer, you can use the int() function: x = '100'; y = int(x). This converts the string '100' into the integer 100.

Python's exception handling using try and except blocks improves program reliability by allowing the program to manage and recover from errors without terminating unexpectedly. For example, converting a string to an integer might fail if the string is non-numeric. Instead of crashing, you can handle the error gracefully: try: num = int('abc'); except ValueError: print('Invalid number!'). This catches the error and displays a user-friendly message.

Python's list data type is mutable, meaning that you can modify, add, or remove items after the list is created. In contrast, a tuple is immutable, so once it is created, its values cannot be changed. Lists are used when you need a collection of items that can be modified, whereas tuples are preferable for fixed collections of items that should not change throughout the program.

Conditional statements in Python are used to execute certain code segments based on specific conditions, facilitating decision-making. The if-elif-else structure allows a program to choose between multiple paths of execution. For example, checking a student’s marks to assign grades: marks = 75; if marks >= 90: print('Grade A'); elif marks >= 60: print('Grade B'); else: print('Grade C'). This code decides the grade based on the value of marks.

You might also like