Python Syntax Guide for Beginners
What is Python syntax?
When learning to code in Python, understanding its syntax is the first step.
In programming, syntax refers to the rules that define the correct structure of code. Like grammar in human languages, programming syntax tells the computer how to interpret our writing.
Python is known for having a clear, readable syntax, which makes it a top choice for beginners. Unlike many other programming languages, Python doesn’t use curly braces {}
or semicolons ;
to define blocks of code. Instead, it uses indentation, making the code look clean and easy to follow. So, let us start by understanding what indentation is.
Python for Programmers
An introduction to the basic syntax and fundamentals of Python for experienced programmers.Try it for freeIndentation in Python
In Python, indentation isn’t just for readability - it’s required. Unlike other languages that use braces or keywords to define code blocks, Python uses whitespace (indentation) to group statements together.
Why is indentation important in Python?
Indentation tells Python where blocks of code begin and end. This is especially important in control flow structures like if
, for
, while
, and function
definitions. If our indentation is incorrect, Python will raise an IndentationError
.
Example:
if score > 80:print("You passed!")
In this example, the print()
statement is indented in the if
block and won’t raise any error. However:
if score > 80:print("You passed!")
This will raise an IndentationError
, as the print()
statement is incorrectly indented.
Next, it’s time to explore the print()
function we’ve used in these code examples.
The print()
function in Python
The print()
function is the easiest way to display output in Python. Whether we’re printing a message to the screen or checking variable values during debugging, print()
is the go-to tool. An example of print()
is as follows:
print("Hello, world!")
Here:
- The text inside quotes is a string.
- The output will be shown in the console when we run the script.
We can also print more than one item by separating them with commas:
name = "Alice"age = 12print("Name:", name, "Age:", age)
The output of this code will be:
Name: Alice Age: 12
Using sep
and end
parameters in the print()
function
sep
: Defines what separates multiple items (default is a space).end
: Defines what appears at the end (default is a newline\n
).
An example using these parameters is:
print("Python", "is", "fun", sep="-")print("Let's learn", end=" ")print("together!")
The output generated will look like:
Python-is-funLet's learn together!
Now that we’ve seen how to display output with print()
, let’s explore how to make our code more understandable with comments.
Comments in Python
Comments in Python are lines in our code that the interpreter ignores. They’re written to explain what the code does, making it easier to understand and maintain.
Single-line comments
Use the #
symbol to write a comment on a single line:
# This is a single-line commentname = "Alice" # You can also comment beside the code
Multi-line comments
While Python doesn’t have a specific multi-line comment syntax, we can use a triple-quoted string ('''
or """
) that isn’t assigned to any variable. Technically, this is a string, but it’s often used as a workaround for block comments.
'''This is a multi-line commentspanning multiple lines'''print("Hello!")
Note: This technique is not officially a comment but is commonly used.
So, can we only print strings? What if we want to store data for later use? That’s where variables come in!
Variables in Python
In Python, variables store data that can be referenced and manipulated later in the code. They act as containers for values like numbers, text, or other objects.
To use a variable, we need to declare it. To declare a variable, assign a value to a name:
name = "Alice"age = 25
Here, name
is assigned the string "Alice"
and age
is assigned the integer 25
.
Rules to follow when naming the variables
- Valid names: They can contain letters, numbers, and underscores but must not start with a number.
- Case-sensitive:
age
andAge
are different variables. - No keywords: Avoid using Python reserved keywords (e.g.,
if
,else
,print
).
Note: Python is a dynamically typed language, meaning we don’t need to explicitly declare the data type of a variable. The interpreter automatically determines it based on the assigned value.
x = 10 # Integerx = "Hello" # String
Now that we understand variables, let’s explore how to name these variables using identifiers properly.
Identifiers and naming rules
In Python, identifiers are the names we give to variables, functions, and other objects. They follow specific rules to ensure our code is valid and easily understood.
Rules for naming identifiers
- Starts with a letter or underscore (
_
):- Valid:
age
,_value
,x1
- Invalid:
1value
(cannot start with a number)
- Valid:
- Can contain letters, digits, and underscores:
- Valid:
user_name
,temp1
,score_2
- Invalid:
user-name
(dashes are not allowed)
- Valid:
- Case-sensitive:
Age
,age
, andAGE
are different identifiers.
- Cannot be a Python keyword:
- Keywords like
if
,while
, andimport
cannot be used as identifiers.
- Keywords like
Ever wondered which words are off-limits when naming the variables? Let’s understand the Python keywords that are reserved for special use.
Python keywords
In Python, certain words are reserved for specific programming functions and cannot be used as identifiers (e.g., variable names). These are called keywords.
List of Python keywords
Here’s a list of common Python keywords we should be aware of:
False | await | else | import | pass |
---|---|---|---|---|
None | break | except | in | raise |
True | class | finally | is | return |
and | continue | for | lambda | try |
as | def | from | nonlocal | while |
assert | del | global | not | with |
async | elif | if | or | yield |
These keywords are part of the Python syntax and are reserved for specific programming purposes.
Okay, we’ve got the names and the no-go words, now let’s see how Python does the math and logic with operators.
Python operators
Operators in Python are special symbols used to perform operations on variables and values. Python supports a wide range of operators based on their functionality.
Types of Python operators
Operator Type | Description | Example |
---|---|---|
Arithmetic | Performs mathematical operations | + , - , * , / |
Comparison | Compares two values | == , != , > , < |
Logical | Combines conditional statements | and , or , not |
Assignment | Assigns values to variables | = , += , -= |
Bitwise | Performs operations on bits | & , ` |
Membership | Tests membership in a sequence | in , not in |
Identity | Compares memory locations of two objects | is , is not |
Example:
# Arithmetica = 10 + 5 # 15b = 4 * 2 # 8# Comparisonprint(10 > 5) # True# Logicalprint(True and False) # False# Assignmentx = 5x += 2 # Now x is 7# Membershipprint('a' in 'cat') # True# Identityprint(x is 7) # True
But what happens when our code gets too long to fit on a single line? That’s where statement continuation comes into play!
Statement continuation in Python
Python usually treats each line as a separate statement. But when our code gets too long, we can split it across multiple lines using implicit or explicit continuation.
Explicit line continuation
Use the backslash \
to explicitly continue a statement on the next line:
total = 10 + 20 + \30 + 40print(total) # Output: 100
Implicit line continuation
Python allows you to break lines implicitly when using parentheses ()
, square brackets []
, or curly braces {}
:
numbers = [1, 2, 3,4, 5, 6]result = (10 + 20 +30 + 40)print(result) # Output: 100
So far, we’ve learnt how our code talks, now let’s make it listen.
Taking input from users in Python
Python allows us to take user input using the built-in input()
function. It reads data as a string by default, which can then be converted into other data types as needed:
Example:
name = input("What is your name? ")print("Hello, " + name + "!")
Input with type conversion
Since input()
returns a string, we’ll often need to convert it to the correct type using int()
, float()
, or other conversion functions.
age = input("Enter your age: ") # This is a stringage = int(age) # Now it's an integerprint("You will be", age + 1, "next year.")
With the fundamentals of Python syntax in place, we’re all set to bring our coding ideas to life.
Conclusion
In this article, we’ve explored the core concepts of Python syntax, including variables, operators, comments, and taking user input. With this solid foundation, we’re now prepared to tackle more advanced projects and continue growing as Python programmers by applying what we’ve learned.
To further enhance your Python skills, take Codecademy’s Learn Python 3 course and dive deeper into coding with Python.
Frequently asked questions
1. Why can’t I use Python keywords to name variables?
Keywords are reserved in Python with specific meanings, such as if
, else
, class
, and def
. Using them as variable names would confuse the Python interpreter, leading to syntax errors.
2. How to code 1 to 100 in Python?
You can use a simple for loop to print numbers from 1 to 100 in Python:
for i in range(1, 101):print(i)
3. Is Python easier than Java?
Python is generally considered easier to learn than Java because of its simple, clean syntax and less verbose structure. Java’s syntax tends to be more rigid and requires more boilerplate code.
4. What is Python used for?
Python is a versatile language used for web development, data analysis, artificial intelligence, machine learning, automation, game development, and more. Its easy-to-learn syntax makes it ideal for both beginners and professionals.
5. What is +=
in Python?
The +=
operator is used for in-place addition. It adds the value on the right-hand side to the variable on the left-hand side. For example:
x = 5x += 3 # Now x is 8
It’s shorthand for x = x + 3
.
'The Codecademy Team, composed of experienced educators and tech experts, is dedicated to making tech skills accessible to all. We empower learners worldwide with expert-reviewed content that develops and enhances the technical skills needed to advance and succeed in their careers.'
Meet the full teamRelated articles
- Article
How to Build a Python Script: A Beginner’s Guide to Python Scripting
Learn scripting and how to build Python scripts from scratch. Set up your environment, structure your code, run the script, and explore real examples with tips to get started. - Article
What is Python?
What is Python, and what can it do? - Article
Python Glossary
Programming reference for Python
Learn more on Codecademy
- Free course
Python for Programmers
An introduction to the basic syntax and fundamentals of Python for experienced programmers.Intermediate3 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours - Free course
Learn Python 2
Learn the basics of the world's fastest growing and most popular programming language used by software engineers, analysts, data scientists, and machine learning engineers alike.Beginner Friendly17 hours