Python Syntax
Introduction
Python is a widely-used programming language known for its simplicity and readability. This tutorial will guide you through the basic syntax of Python, which is essential for writing and understanding Python code.
Variables and Data Types
In Python, variables are used to store data. A variable is created the moment you first assign a value to it.
y = "Hello, World!"
Python has several built-in data types, such as:
- Integer (int)
- Floating-point number (float)
- String (str)
- List (list)
- Tuple (tuple)
- Dictionary (dict)
Comments
Comments are used to explain code and make it more readable. They are not executed by Python.
x = 5 # This is an inline comment
Indentation
Python uses indentation to define blocks of code. A block of code is a group of statements that are executed together.
print("x is positive")
Conditional Statements
Python supports the usual logical conditions from mathematics:
- Equals: a == b
- Not Equals: a != b
- Less than: a < b
- Less than or equal to: a <= b
- Greater than: a > b
- Greater than or equal to: a >= b
These conditions can be used in several ways, most commonly in "if statements" and loops.
print("a is greater than b")
Loops
Python has two primitive loop commands:
- while loops
- for loops
While Loop
With the while loop, we can execute a set of statements as long as a condition is true.
while i < 6:
print(i)
i += 1
For Loop
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
for x in fruits:
print(x)
Functions
A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function. A function can return data as a result.
print("Hello from a function")
my_function()
Conclusion
In this tutorial, we covered the basic syntax of Python. Understanding these fundamentals is crucial for writing and debugging Python code effectively. As you continue to learn Python, you will become more comfortable with its syntax and powerful features.