Python is a versatile and widely-used programming language known for its simplicity and readability. It's a great language for beginners and experienced developers alike. Here are the basics of Python:
Hello, World!
- A simple Python program that prints "Hello, World!" to the screen:
pythonprint("Hello, World!")
Comments:
- You can add comments to your code using the
#
symbol. Comments are ignored by the Python interpreter and are useful for explaining code to others.
python# This is a comment
- You can add comments to your code using the
Variables:
- Variables are used to store data. Python is dynamically typed, so you don't need to declare the data type explicitly.
pythonname = "Alice" age = 30
Data Types:
- Python has several data types, including integers, floats, strings, lists, dictionaries, and more.
pythonnum = 42 # Integer pi = 3.14 # Float name = "Alice" # String colors = ['red', 'green', 'blue'] # List person = {'name': 'Bob', 'age': 25} # Dictionary
Basic Operators:
- Python supports common operators like
+
,-
,*
,/
, and%
for arithmetic operations.
pythonresult = 10 + 5 # Addition
- Python supports common operators like
Control Flow:
- Python uses indentation (whitespace) to indicate code blocks, rather than braces or keywords like
end
.
pythonif age < 18: print("You are a minor.") else: print("You are an adult.")
- Python uses indentation (whitespace) to indicate code blocks, rather than braces or keywords like
Loops:
- You can use
for
andwhile
loops for iteration.
pythonfor i in range(5): print(i) while condition: # Loop code
- You can use
Functions:
- Functions are reusable blocks of code. You define functions using the
def
keyword.
pythondef greet(name): print("Hello, " + name) greet("Alice")
- Functions are reusable blocks of code. You define functions using the
Lists:
- Lists are ordered collections of items, and they can contain elements of different data types.
pythoncolors = ['red', 'green', 'blue']
Dictionaries:
- Dictionaries are collections of key-value pairs.
pythonperson = {'name': 'Bob', 'age': 25}
Input and Output:
- You can interact with users by taking input and displaying output.
pythonname = input("Enter your name: ") print("Hello, " + name)
Modules and Libraries:
- Python has a vast standard library and a rich ecosystem of third-party libraries. You can import modules to access additional functionality.
pythonimport math result = math.sqrt(16)
Error Handling:
- Python provides ways to handle errors using
try
andexcept
blocks.
pythontry: result = 10 / 0 except ZeroDivisionError: print("Division by zero is not allowed.")
- Python provides ways to handle errors using
These basics should give you a good start with Python. As you continue your Python journey, you can explore more advanced topics like object-oriented programming, file handling, and web development with Python frameworks like Django and Flask.
No comments:
Post a Comment