Basic Syntax
Basic Syntax of Python
Section titled “Basic Syntax of Python”Python is designed to be simple, readable, and expressive. Its syntax is intentionally minimal compared to many other programming languages, which makes it a popular choice for beginners and professionals alike.
1. Printing Output
Section titled “1. Printing Output”The print() function is used to display output to the console.
print("Hello, World!")Output:
Hello, World!This is usually the first program people write when learning Python.
2. Variables and Assignment
Section titled “2. Variables and Assignment”Variables store data. In Python, you do not need to declare the type of a variable.
name = "Alice"age = 25height = 5.6Python automatically determines the variable type.
3. Basic Data Types
Section titled “3. Basic Data Types”Some commonly used built-in data types include:
integer_number = 10 # intdecimal_number = 3.14 # floattext = "Python" # stringis_active = True # booleanPython is dynamically typed, meaning variable types are determined at runtime.
4. Comments
Section titled “4. Comments”Comments are used to explain code and are ignored during execution.
Single-line comment:
# This is a commentMulti-line comment (commonly done with triple quotes):
"""This is amulti-line comment"""5. Indentation
Section titled “5. Indentation”Unlike many languages that use braces {}, Python uses indentation to define code blocks.
if age > 18: print("You are an adult")Improper indentation will cause an error.
6. Conditional Statements
Section titled “6. Conditional Statements”Python uses if, elif, and else for decision-making.
score = 85
if score >= 90: print("Grade A")elif score >= 75: print("Grade B")else: print("Grade C")7. Loops
Section titled “7. Loops”For Loop
Section titled “For Loop”Used to iterate over a sequence.
for i in range(5): print(i)Output:
01234While Loop
Section titled “While Loop”Executes as long as a condition is true.
count = 0
while count < 3: print(count) count += 18. Functions
Section titled “8. Functions”Functions allow code reuse.
def greet(name): return "Hello " + name
message = greet("Alice")print(message)9. Importing Modules
Section titled “9. Importing Modules”Python has many built-in modules that extend functionality.
import math
print(math.sqrt(16))Output:
4.0Conclusion
Section titled “Conclusion”Python’s syntax emphasizes readability and simplicity. Core features like dynamic typing, indentation-based blocks, and built-in libraries allow developers to write powerful programs with relatively little code.