Python Playground
Site Builder
Explore and run Python code directly in your browser
Code Editor
# Trainable Chat Bot knowledge_base = {} def train_bot(): print("\nBot: Teach me something new!") question = input("You say: ") answer = input("I respond: ") knowledge_base[question.lower()] = answer print("Bot: Got it! I've learned something new.") def save_knowledge(): with open('bot_knowledge.txt', 'w') as f: for q, a in knowledge_base.items(): f.write(f"{q}|{a}\n") print("Bot: My knowledge has been saved!") def load_knowledge(): try: with open('bot_knowledge.txt', 'r') as f: for line in f: q, a = line.strip().split('|') knowledge_base[q] = a except FileNotFoundError: pass def chat_bot(): load_knowledge() print("Bot: Hi there! I'm a trainable BotBuddy. Type 'train' to teach me or 'quit' to exit.") while True: message = input("\nYou: ").lower() if message == 'quit': save_knowledge() print("Bot: Goodbye! Thanks for chatting.") break elif message == 'train': train_bot() elif message in knowledge_base: print(f"Bot: {knowledge_base[message]}") else: print("Bot: I don't know how to respond to that. Type 'train' to teach me!") chat_bot()
Run Code
Clear
How to use this bot:
Type normal messages to chat
Type 'train' to teach the bot new responses
Type 'quit' to end the session
The bot saves everything you teach it!
Output
Your output will appear here...
Python Resources
Python Documentation
Real Python Tutorials
Python Cheat Sheet
Example Snippets
Fibonacci Sequence
def
fib(n):
if
n <=
1
:
return
n
return
fib(n-
1
) + fib(n-
2
)
# Print first 10 Fibonacci numbers
for
i
in
range
(
10
):
print
(fib(i))
List Comprehension
# Squares of even numbers
numbers = [
1
,
2
,
3
,
4
,
5
,
6
]
squares = [x**
2
for
x
in
numbers
if
x %
2
==
0
]
print
(squares)
# Output: [4, 16, 36]
API Request
import
requests
# Fetch data from JSONPlaceholder API
response = requests.get(
"https://jsonplaceholder.typicode.com/todos/1"
)
data = response.json()
print
(
"Todo:"
, data[
"title"
])
print
(
"Completed:"
, data[
"completed"
])