Python is a widely used general-purpose, high-level programming language. In this article we'll check tht basis syntax of the language.
The term syntax refers to the set of rules that define how code should be written in a certain programming language.
Python does not support the use of $ nor is it necessary to end lines with ;.
Let's make an example:
age = 20 #Defining an int variable
name = 'Ulises' #Defining a string variable
age = (age + 20)/2 #Making arithmetic operations.
def func(): #Defining a function
print(f"My name is {name} and I am {age} years old")
func()
#Output: My name is Ulises and I am 20.0 years old
As you can see the syntax is very similar to pseudocode or natural language
Comments in Python.
Comments in Python are statements written within the code. They have no impact on the execution. Are used for explain the context about the code.
a,b = 10, 20
#Printing numbers
print(a,b)
#Output: 10 20
We can also comment many lines of code. For that, it's necessary to use triple quotes (single ' or double ").
"""
Multi
line
comment
"""
Code blocks.
Code blocks are sections of code that are grouped together. Code blocks are defined by indentation rather than brackets or keywords, as is common in some other programming languages.
if condition:
# This is a code block for the "if" statement
print("Condition is true")
In Python, statements that introduce a block (such as if, for, while, def) end with a colon :.
def say_hello():
print("Hello!")
if condition:
#Code block
...
pass
Consistent indentation is crucial because mixing spaces and tabs will raise an IndentationError.
Multiple Line Statements.
In Python, multiline statements allow you to extend a single logical line of code over multiple lines. We can create multiline statements on these ways.
total = 1 + 2 + 3 + \
4 + 5 + 6
#Using Parentheses, Brackets, or Braces
numbers = [
1, 2, 3,
4, 5, 6
]
result = (1 + 2 + 3 +
4 + 5 + 6)
Python allows creating multiline strings for long texts or documentation.
#Using Triple Quotes (''' or """)
message = """This is a
multiline string that spans
several lines."""
To learn more about check out our complete Python course.