Python Basic Syntax
Indentation
- Whitespace matters: Python uses indentation to define code blocks.
- Consistent indentation: Use either 4 spaces or one tab for each indentation level.
- Incorrect indentation: Leads to
IndentationError
.
Python
if condition:
# Indented block for true condition
else:
# Indented block for false condition
Variables and Data Types
- Variables: Named containers for storing data values.
- Data types: Numbers (integers, floats), strings, booleans, lists, tuples, dictionaries.
- Dynamic typing: No need to declare variable types explicitly.
Python
x = 10 # Integer
name = "Alice" # String
is_active = True # Boolean
Operators
- Arithmetic operators: +, -, *, /, //, %, **
- Comparison operators: ==, !=, <, >, <=, >=
- Logical operators: and, or, not
Keywords
- Reserved words: Cannot be used as variable names.
- Examples: if, else, for, while, def, class, import, etc.
Comments
- Single-line comments: Start with
#
- Multi-line comments: Use triple quotes (“”” or ”’).
Input and Output
print()
function: Displays output to the console.input()
function: Takes user input.
Python
name = input("Enter your name: ")
print("Hello,", name)
Basic Control Flow
if
statements: Execute code based on conditions.for
loops: Iterate over sequences.while
loops: Execute code as long as a condition is true.
Python
for i in range(5):
print(i)
Functions
def
keyword: Define functions.- Parameters: Pass values to functions.
- Return values: Send values back from functions.
Python
def greet(name):
print("Hello,", name)
greet("Alice")
By understanding these fundamental concepts, you can start building more complex Python programs.
What is the difference between if
and elif
?
if
is used for the first condition, while elif
is used for subsequent conditions.
How do for
and while
loops differ?
for
loops iterate over a sequence, while while
loops continue as long as a condition is true.
How do I define a function in Python?
Use the def
keyword followed by the function name, parameters, and the function body.
What is a return statement?
A return statement specifies the value to be returned from a function.
Can I use Python for web development?
Yes, Python has frameworks like Django and Flask for web development.
Is Python suitable for data science?
Absolutely, Python is widely used for data science with libraries like NumPy, Pandas, and Scikit-learn.
What are the basic data types in Python?
Integers, floats, strings, booleans, lists, tuples, and dictionaries.