Python Basics

Python Basics

Python is a versatile and powerful programming language that is perfect for both beginners and seasoned developers. Here’s an in-depth look at some fundamental concepts to get you started:

1. Variables and Data Types

Variables are used to store information that can be referenced and manipulated. Python supports various data types, including:

  • Integers (int): Whole numbers. Example: x = 10
  • Floats (float): Decimal numbers. Example: pi = 3.14
  • Strings (str): Text. Example: name = "Alice"
  • Booleans (bool): True or False values. Example: is_student = True

python        

Copy code

x = 10 pi = 3.14 name = "Alice" is_student = True

2. Basic Operations

Python supports various operations for manipulating data:

  • Arithmetic Operations: Addition (+), subtraction (-), multiplication (*), and division (/).
  • Comparison Operations: Equal to (==), not equal to (!=), greater than (>), and less than (<).

python        

Copy code

# Arithmetic sum = x + pi difference = x - pi # Comparison is_equal = (x == 10) is_greater = (pi > 3)

3. Control Structures

Control structures help in making decisions and repeating tasks:

  • If-Else Statements: Execute code blocks based on conditions.

python        

Copy code

if x > 0: print("x is positive") else: print("x is zero or negative")

  • For Loops: Iterate over a sequence (like a list or range).

python        

Copy code

for i in range(5): print(i)

  • While Loops: Repeat as long as a condition is true.

python        

Copy code

while x > 0: print(x) x -= 1

4. Functions

Functions are reusable blocks of code designed to perform a specific task. Define a function using the def keyword.

python        

Copy code

def greet(name): return f"Hello, {name}!" print(greet("Alice"))

5. Lists and Dictionaries

  • Lists: Ordered collections of items.

python        

Copy code

fruits = ["apple", "banana", "cherry"] print(fruits[1]) # Outputs: banana

  • Dictionaries: Collections of key-value pairs.

python        

Copy code

person = {"name": "Alice", "age": 25} print(person["name"]) # Outputs: Alice

6. Modules and Libraries

Python’s rich standard library and external libraries extend its capabilities. Import modules using the import statement.

python        

Copy code

import math print(math.sqrt(16)) # Outputs: 4.0

7. File Handling

Read from and write to files using built-in functions.

python        

Copy code

# Writing to a file with open("example.txt", "w") as file: file.write("Hello, World!") # Reading from a file with open("example.txt", "r") as file: content = file.read() print(content)

Python's simplicity and extensive ecosystem make it a powerful tool for all types of programming tasks. Dive into Python and start building your projects today! 🚀

#Python #Programming #CodingBasics #LearnPython #TechSkills

To view or add a comment, sign in

Explore content categories