Let's start with the classic "Hello, World!" program:
print("Hello, World!")
The print()
function is used to output text or variables to the console. When you run this code, the text "Hello, World!" will be printed.
In Python, variables are used to store data values. Below are some common data types:
name = "Alice" # String
age = 25 # Integer
height = 5.9 # Float
is_active = True # Boolean
age = 20
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
for i in range(5):
print(i)
count = 0
while count < 5:
print(count)
count += 1
Functions allow you to group code into reusable blocks. Here's how you define a function in Python:
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
Lists are ordered collections of items. Here's an example:
fruits = ["apple", "banana", "cherry"]
Dictionaries store key-value pairs. Here's an example:
student = {"name": "Alice", "age": 20, "courses": ["Math", "Science"]}
print(student["name"]) # Output: Alice
Use try-except
to handle errors gracefully:
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
Now that you have a basic understanding of Python syntax, you're ready to dive deeper into Python programming!
Continue exploring more advanced topics like object-oriented programming, data manipulation, and more. Happy coding!
Want to revisit the installation process? Check out our Python Installation & Setup guide.
Test Your Code Here