0% found this document useful (0 votes)
4 views6 pages

Python Basics: Guide with Examples

This document is a detailed guide to Python basics, covering topics such as variables, data types, operators, control flow, loops, functions, data structures, string operations, input/output, file handling, exception handling, modules, classes, and lambda functions. Each section includes examples and exercises to reinforce learning. The guide emphasizes practical application and encourages users to practice with their own examples.
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)
4 views6 pages

Python Basics: Guide with Examples

This document is a detailed guide to Python basics, covering topics such as variables, data types, operators, control flow, loops, functions, data structures, string operations, input/output, file handling, exception handling, modules, classes, and lambda functions. Each section includes examples and exercises to reinforce learning. The guide emphasizes practical application and encourages users to practice with their own examples.
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

Python Basics - Detailed Guide with Examples and Exercises

1. Introduction to Python

- Python is easy to learn and widely used in web development, AI, ML, data science, etc.

- It is interpreted, meaning you don't need to compile your code.

2. Variables and Data Types

- Example:

name = "Alice"

age = 25

height = 5.4

is_student = True

Exercise: Create variables for your name, age, and whether you're a student.

3. Operators

- Arithmetic: +, -, *, /, %, **

- Comparison: ==, !=, >, <, >=, <=

- Logical: and, or, not

Example:

x = 10

y=5

print(x > y and y < 10) # True

Exercise: Try all arithmetic operators with x = 10 and y = 3


4. Control Flow (if, elif, else)

Example:

score = 75

if score >= 90:

print("A")

elif score >= 70:

print("B")

else:

print("C")

Exercise: Write a program to check if a number is positive, negative, or zero.

5. Loops

- for loop:

for i in range(5):

print(i)

- while loop:

i=0

while i < 5:

print(i)

i += 1

Exercise: Print all even numbers from 1 to 20 using a for loop.

6. Functions
Example:

def greet(name):

return "Hello " + name

print(greet("Alice"))

Exercise: Write a function to return the square of a number.

7. Data Structures

- List: nums = [1, 2, 3]

- Tuple: t = (1, 2)

- Dictionary: person = {"name": "Bob", "age": 30}

- Set: s = {1, 2, 3}

Exercise: Create a dictionary for a student with name, age, and subjects.

8. String Operations

Example:

msg = " hello "

print([Link](), [Link]())

Exercise: Take input from user and reverse the string.

9. Input and Output

Example:

name = input("Enter your name: ")


print("Hello", name)

10. File Handling

Example:

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

[Link]("Hello")

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

print([Link]())

Exercise: Write a program to store user input into a file.

11. Exception Handling

Example:

try:

x = 10 / 0

except ZeroDivisionError:

print("Cannot divide by zero")

Exercise: Handle input errors using try-except

12. Modules and Packages

Example:

import math

print([Link](16))
Exercise: Use datetime module to print current date and time.

13. Classes and Objects

Example:

class Person:

def __init__(self, name):

[Link] = name

def greet(self):

print("Hi", [Link])

p = Person("Alice")

[Link]()

Exercise: Create a class for a Book with title and author.

14. Lambda and Built-in Functions

Example:

square = lambda x: x * x

print(square(5))

nums = [1, 2, 3]

print(list(map(lambda x: x*2, nums)))

Exercise: Use filter to select even numbers from a list.

15. Comments
- Single line: # This is a comment

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

Practice all sections with your own examples!

Common questions

Powered by AI

Python's classes and objects facilitate OOP by encapsulating data and behavior into a single entity, allowing data abstraction, inheritance, and polymorphism. This paradigm offers benefits such as code reusability through inheritance, improved maintainability because of encapsulated structures, and flexibility with polymorphism, leading to scalable and organized code tailored for complex systems development. For example, a 'Book' class can capture the essence of book objects, complete with properties like `title` and `author`, and methods relevant to book operations .

Modules and packages in Python play a crucial role in organizing code and promoting reuse, which significantly impacts software scalability and maintenance. By encapsulating functionalities into modules, developers can manage large codebases better, improving readability and reducing redundancy. This modular approach aligns well with the DRY (Don't Repeat Yourself) principle, facilitates unit testing, and accommodates scalable, collaborative development by distributing functionalities across package structures .

Lambda functions are effective for small, one-time, throw-away functions due to their simplicity and conciseness, as they allow quick implementations without the overhead of defining a full function. For example, using `map(lambda x: x*2, nums)` can quickly double each element in a list without needing a separate definition. However, named functions are more readable and reusable, particularly for more complex operations, facilitating debugging and comprehension, and should be used in such scenarios .

Tuples in Python are beneficial when you need to store a sequence of items that should not change throughout the program. Since tuples are immutable, they are faster to process and provide more robust data integrity if the stored items are not supposed to be altered, making them ideal for fixed collections of constants or for use as keys in dictionaries .

Python being an interpreted language means that it executes code line-by-line, which makes it easier to test and debug code. This characteristic is beneficial for web development and AI since rapid prototyping and iterations are common in these fields. Developers can quickly test parts of their systems and revise them without needing to go through a compile-link-execute cycle common in compiled languages, thus speeding up the development process .

Exception handling in Python allows developers to manage runtime errors gracefully, preventing abrupt program crashes and providing users with informative error messages. For instance, a `try-except` block around division operations can catch potential `ZeroDivisionError`, allowing the program to continue executing other operations or log the error for future debugging, thus improving the overall reliability and robustness of the software .

A Python program using file handling could prompt the user to enter their name and save this input into a `user_data.txt` file using `with open('user_data.txt', 'w') as f: f.write(user_input)`. Such programs are practical for data collection applications, where persistent storage of user input is necessary, facilitating user data management and retrieval in web applications or data logging systems .

Python's logical operators (`and`, `or`, `not`) enhance decision-making by allowing the combination and inversion of conditional expressions, which are fundamental for complex logic decisions. An example is checking if a variable `x` is between two values using `x > 5 and x < 15`. Logical operators enable the creation of multiple conditions that determine the flow of execution, providing flexibility and precision in controlling the program's behavior .

Control flow structures in Python enable the execution of code based on specific conditions, allowing programs to make decisions and perform various actions conditionally. They are implemented using `if`, `elif`, and `else` statements, which evaluate Boolean expressions to control the flow of execution. For example, an `if` statement can check if a score is greater than a threshold and print a message accordingly, enabling the program to react dynamically to different input states .

In Python, dictionaries provide dynamic access to both keys and values via methods like `.items()`, which returns pairs of keys and values, enabling iteration through the dictionary's contents. This approach allows easy access and manipulation, such as using a for-loop to process each key-value pair directly. Additionally, the ability to update values or add new key-value pairs supports dynamic data manipulation while maintaining efficient access .

You might also like