python programming examples
时间: 2023-07-16 20:10:25 浏览: 100
Sure! Here are a few examples of Python programming:
1. Hello World:
python
print("Hello, World!")
```
2. Fibonacci Series:
```python
def fibonacci(n):
sequence = [0, 1]
while len(sequence) < n:
next_number = sequence[-1] + sequence[-2]
sequence.append(next_number)
return sequence
# Print the first 10 numbers in the Fibonacci sequence
fib_sequence = fibonacci(10)
print(fib_sequence)
```
3. Factorial Calculation:
```python
def factorial(n):
result = 1
for i in range(1, n+1):
result *= i
return result
# Calculate the factorial of a number
num = 5
factorial_num = factorial(num)
print(f"The factorial of {num} is {factorial_num}")
```
4. String Manipulation:
```python
sentence = "Python Programming is fun!"
print(sentence.upper()) # Convert to uppercase
print(sentence.lower()) # Convert to lowercase
print(sentence.split()) # Split into a list of words
print(sentence.replace("fun", "awesome")) # Replace a word
```
5. File Handling:
```python
# Read contents from a file
with open("file.txt", "r") as file:
contents = file.read()
print(contents)
# Write contents to a file
with open("file.txt", "w") as file:
file.write("Hello, World!")
```
These are just a few examples to illustrate some common programming tasks in Python. You can explore further and try out different concepts and functionalities based on your learning goals and interests.
阅读全文