Python Tutorial
Python Tutorial
Python is a versatile, easy-to-learn programming language that is widely used in various domains
like web development, data science, artificial intelligence, and more. This tutorial will help you get
started with Python by introducing basic concepts with examples.
1. Setting Up Python
Before writing Python code, you need to install Python on your system. You can download it from
Python's official website. Once installed, you can write Python code using any text editor or an
integrated development environment (IDE) like PyCharm, VS Code, or even the built-in IDLE.
2. Python Basics
a. Printing Output
The print() function is used to display output.
print("Hello, World!")
Output:
Hello, World!
Output:
John 25 5.8 True
c. Comments
Comments are lines in the code that Python ignores. Use # for single-line comments.
# This is a single-line comment
print("Learning Python is fun!")
3. Control Structures
a. Conditional Statements
Use if, elif, and else to make decisions in your code.
num = 10
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
Output:
Positive number
b. Loops
i. for Loop
Iterates over a sequence (like a list or a range).
for i in range(5):
print(i)
Output:
0
1
2
3
4
Output:
0
1
2
3
4
4. Functions
Functions are reusable blocks of code that perform a specific task.
def greet(name):
return f"Hello, {name}!"
print(greet("Alice"))
Output:
Hello, Alice!
5. Working with Lists
Lists are used to store multiple items in a single variable.
fruits = ["apple", "banana", "cherry"]
print(fruits)
fruits.append("orange") # Adding an item
print(fruits)
fruits.remove("banana") # Removing an item
print(fruits)
Output:
['apple', 'banana', 'cherry']
['apple', 'banana', 'cherry', 'orange']
['apple', 'cherry', 'orange']
6. Dictionaries
Dictionaries store data as key-value pairs.
person = {"name": "John", "age": 30, "city": "New York"}
print(person)
print(person["name"])
Output:
{'name': 'John', 'age': 30, 'city': 'New York'}
John
{'name': 'John', 'age': 31, 'city': 'New York'}
def introduce(self):
return f"My name is {self.name} and I am {self.age} years old."
Output:
My name is Alice and I am 28 years old.
8. File Handling
Python allows you to read from and write to files.
Writing to a File
with open("example.txt", "w") as file:
file.write("This is a test file.")
Output:
This is a test file.
Output:
4.0