All Python Code Example


Certainly! Here are a few examples of Python code to demonstrate different aspects of the language:

1. **Hello, World!**
“`python
print(“Hello, World!”)
“`

2. **Variables and Data Types**
“`python
# Integer variable
age = 25

# Floating-point variable
temperature = 98.6

# String variable
name = “John Doe”

# Boolean variable
is_valid = True
“`

3. **Conditional Statements (if-else)**
“`python
x = 10

if x > 0:
print(“Positive”)
elif x < 0:
print(“Negative”)
else:
print(“Zero”)
“`

4. **Loops (for and while)**
“`python
# For loop
fruits = [“apple”, “banana”, “cherry”]
for fruit in fruits:
print(fruit)

# While loop
count = 0
while count < 5:
print(count)
count += 1
“`

5. **Functions**
“`python
def greet(name):
print(“Hello, ” + name + “!”)

greet(“Alice”)
“`

6. **Lists**
“`python
# Creating a list
numbers = [1, 2, 3, 4, 5]

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

# Modifying list elements
numbers[2] = 10
print(numbers) # Output: [1, 2, 10, 4, 5]

# List operations
numbers.append(6)
numbers.remove(2)
print(len(numbers)) # Output: 5
“`

7. **Dictionaries**
“`python
# Creating a dictionary
student = {
“name”: “John Doe”,
“age”: 20,
“major”: “Computer Science”
}

# Accessing dictionary values
print(student[“name”]) # Output: John Doe

# Modifying dictionary values
student[“age”] = 21
print(student) # Output: {‘name’: ‘John Doe’, ‘age’: 21, ‘major’: ‘Computer Science’}
“`

8. **File Operations**
“`python
# Reading from a file
file = open(“data.txt”, “r”)
contents = file.read()
file.close()

# Writing to a file
file = open(“output.txt”, “w”)
file.write(“Hello, World!”)
file.close()
“`

9. **Exception Handling**
“`python
try:
result = 10 / 0
except ZeroDivisionError:
print(“Error: Cannot divide by zero.”)
“`

10. **Importing Modules**
“`python
import math

# Using math module
print(math.sqrt(25)) # Output: 5.0
“`

These examples cover some fundamental concepts of Python, including variables, conditionals, loops, functions, data structures (lists and dictionaries), file operations, exception handling, and module importing. Remember that executing these code snippets requires a Python environment, such as an interpreter or an integrated development environment (IDE).


Leave a comment

Design a site like this with WordPress.com
Get started