Basic Python

Basic Python Syntax

Your First Python Program

Let's start with the classic "Hello, World!" program:

print("Hello, World!")

Explanation:

The print() function is used to output text or variables to the console. When you run this code, the text "Hello, World!" will be printed.

Variables and Data Types

In Python, variables are used to store data values. Below are some common data types:

Examples:


name = "Alice"        # String
age = 25              # Integer
height = 5.9          # Float
is_active = True      # Boolean
    

Control Structures

If-Else Statements


age = 20
if age >= 18:
    print("You are an adult.")
else:
    print("You are a minor.")
    

For Loop


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

While Loop


count = 0
while count < 5:
    print(count)
    count += 1
    

Functions

Functions allow you to group code into reusable blocks. Here's how you define a function in Python:


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

Lists and Dictionaries

Lists

Lists are ordered collections of items. Here's an example:

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

Dictionaries

Dictionaries store key-value pairs. Here's an example:


student = {"name": "Alice", "age": 20, "courses": ["Math", "Science"]}
print(student["name"])  # Output: Alice
    

Exceptions

Try-Except Block

Use try-except to handle errors gracefully:


try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
    

Conclusion

Now that you have a basic understanding of Python syntax, you're ready to dive deeper into Python programming!

Continue exploring more advanced topics like object-oriented programming, data manipulation, and more. Happy coding!

Want to revisit the installation process? Check out our Python Installation & Setup guide.

Embeded Python Interpreter:

Test Your Code Here