Installation and Setup

First, you need to install Python on your computer. You can download it from the official Python website (python.org) and follow the installation instructions for your operating system.

Once installed, you can open a terminal or command prompt and type python to enter the Python interactive shell. You can also use an Integrated Development Environment (IDE) like PyCharm or Visual Studio Code for writing and running Python code.

First Program

Python uses the print() function to display output. Let’s start with a simple “Hello, World!” program.

print("Hello, World!")

Variables and Data Types

In Python, you can store data in variables. Variables can hold different types of data such as numbers, strings, and lists.

# Assigning values to variables
name = "Alice"
age = 30
height = 5.6

# Printing variables
print("Name:", name)
print("Age:", age)
print("Height:", height)

Comments

You can add comments to your code using the # symbol. Comments are ignored by Python and are used for adding explanations or notes.

# This is a comment
# It is ignored by Python
print("This is not a comment")  # Comments can also be added inline

Basic Operations

Python supports various arithmetic operations such as addition, subtraction, multiplication, and division.

# Arithmetic operations
result = 10 + 5  # Addition
result = 10 - 5  # Subtraction
result = 10 * 5  # Multiplication
result = 10 / 5  # Division
result = 10 % 3  # Modulus (remainder)
result = 10 ** 3 # Exponentiation (power)

Conditional Statements

You can use conditional statements like if, elif, and else to make decisions in your code.

# Conditional statements
x = 10
if x > 0:
    print("Positive")
elif x == 0:
    print("Zero")
else:
    print("Negative")

Loops

Python provides for and while loops for iterating over sequences and executing code repeatedly.

# 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 encapsulate reusable blocks of code. You can define functions using the def keyword.

# Function definition
def greet(name):
    print("Hello,", name)

# Function call
greet("Alice")

Lists

Lists are ordered collections of items. You can add, remove, and modify elements in a list.

# List creation
numbers = [1, 2, 3, 4, 5]

# Accessing elements
print(numbers[0])   # Output: 1

# Modifying elements
numbers[0] = 10

# Adding elements
numbers.append(6)

# Removing elements
numbers.remove(3)

print(numbers)   # Output: [10, 2, 4, 5, 6]

Conclusion

This concludes our basic Python tutorial. We’ve covered fundamental concepts such as variables, data types, operations, conditional statements, loops, functions, and lists. Practice these concepts to become comfortable with Python programming.