Title: Python Syntax Guide for Beginners | Codecademy
Open Graph Title: Python Syntax Guide for Beginners | Codecademy
X Title: Python Syntax Guide for Beginners | Codecademy
Description: Learn Python syntax with this beginner-friendly guide. Understand Python indentation, print statements, variables, comments, user input, and more with examples.
Open Graph Description: Learn Python syntax with this beginner-friendly guide. Understand Python indentation, print statements, variables, comments, user input, and more with examples.
X Description: Learn Python syntax with this beginner-friendly guide. Understand Python indentation, print statements, variables, comments, user input, and more with examples.
Opengraph URL: https://www.codecademy.com/article/learn-python-python-syntax
X: @codecademy
Domain: www.codecademy.com
{"@context":"https://schema.org","@type":"Article","name":"Python Syntax Guide for Beginners","headline":"Python Syntax Guide for Beginners","abstract":"Learn Python syntax with this beginner-friendly guide. Understand Python indentation, print statements, variables, comments, user input, and more with examples.","description":"Learn Python syntax with this beginner-friendly guide. Understand Python indentation, print statements, variables, comments, user input, and more with examples.","articleBody":"## What is Python syntax? \n\nWhen learning to code in Python, understanding its **syntax** is the first step. \n\nIn [programming](/article/what-is-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. \n\nPython 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.\n\n## Indentation in Python \n\nIn 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. \n\n### Why is indentation important in Python? \n\nIndentation tells Python where blocks of code begin and end. This is especially important in control flow structures like [`if`](https://www.codecademy.com/resources/docs/python/conditionals), [`for`, `while`](https://www.codecademy.com/resources/docs/python/loops), and [`function`](https://www.codecademy.com/resources/docs/python/functions) definitions. If our indentation is incorrect, Python will raise an `IndentationError`. \n\n**Example:** \n\n```py \nif score > 80: \n print("You passed!")\n``` \n\nIn this example, the `print()` statement is indented in the `if` block and won't raise any error. However: \n\n```py \nif score > 80: \nprint("You passed!")\n``` \n\nThis will raise an `IndentationError`, as the `print()` statement is incorrectly indented. \n\nNext, it's time to explore the `print()` function we’ve used in these code examples.\n\n## The `print()` function in Python \n\nThe [`print()`](https://www.codecademy.com/resources/docs/python/built-in-functions/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: \n\n```py \nprint("Hello, world!") \n``` \n\nHere: \n\n- The text inside quotes is a [string](https://www.codecademy.com/resources/docs/python/strings). \n- The output will be shown in the console when we run the script. \n\nWe can also print more than one item by separating them with commas: \n\n```py \nname = "Alice" \nage = 12 \nprint("Name:", name, "Age:", age) \n```\n\nThe output of this code will be: \n \n```shell \nName: Alice Age: 12 \n```\n\n### Using `sep` and `end` parameters in the `print()` function \n\n- `sep`: Defines what separates multiple items (default is a space). \n- `end`: Defines what appears at the end (default is a newline `\\n`). \n\nAn example using these parameters is: \n\n```py \nprint("Python", "is", "fun", sep="-") \nprint("Let's learn", end=" ") \nprint("together!") \n```\n\nThe output generated will look like: \n\n```shell\nPython-is-fun \nLet's learn together! \n```\n\nNow that we've seen how to display output with `print()`, let's explore how to make our code more understandable with comments.\n\n## Comments in Python \n\nComments 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. \n\n### Single-line comments \n\nUse the `#` symbol to write a comment on a single line: \n\n```py \n# This is a single-line comment \nname = "Alice" # You can also comment beside the code \n```\n\n### Multi-line comments \n\nWhile 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. \n\n```py \n''' \nThis is a multi-line comment \nspanning multiple lines \n''' \nprint("Hello!") \n``` \n\n> **Note:** This technique is not officially a comment but is commonly used. \n\nSo, can we only print strings? What if we want to store data for later use? That’s where variables come in! \n\n## Variables in Python \n\nIn Python, [variables](https://www.codecademy.com/resources/docs/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. \n\nTo use a variable, we need to declare it. To declare a variable, assign a value to a name: \n\n```py \nname = "Alice" \nage = 25 \n``` \n\nHere, `name` is assigned the string `"Alice"` and `age` is assigned the integer `25`.\n\n### Rules to follow when naming the variables \n\n- **Valid names:** They can contain letters, numbers, and underscores but must not start with a number. \n- **Case-sensitive:** `age` and `Age` are different variables. \n- **No keywords:** Avoid using Python reserved keywords (e.g., `if`, `else`, `print`). \n\n> **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. \n\n> ```py \n> x = 10 # Integer \n> x = "Hello" # String \n> ``` \n\nNow that we understand variables, let's explore how to name these variables using identifiers properly.\n\n## Identifiers and naming rules\n\nIn 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. \n\n### Rules for naming identifiers \n\n- Starts with a letter or underscore (`_`): \n - Valid: `age`, `_value`, `x1` \n - Invalid: `1value` (cannot start with a number) \n- Can contain letters, digits, and underscores: \n - Valid: `user_name`, `temp1`, `score_2` \n - Invalid: `user-name` (dashes are not allowed) \n- Case-sensitive: \n - `Age`, `age`, and `AGE` are different identifiers. \n- Cannot be a Python keyword: \n - Keywords like `if`, `while`, and `import` cannot be used as identifiers. \n\nEver wondered which words are off-limits when naming the variables? Let’s understand the Python keywords that are reserved for special use. \n\n## Python keywords \n\nIn Python, certain words are reserved for specific programming functions and cannot be used as identifiers (e.g., variable names). These are called keywords. \n\n### List of Python keywords \n\nHere’s a list of common Python keywords we should be aware of:\n\n| False | await | else | import | pass |\n|------------|------------|------------|------------|------------|\n| None | break | except | in | raise |\n| True | class | finally | is | return |\n| and | continue | for | lambda | try |\n| as | def | from | nonlocal | while |\n| assert | del | global | not | with |\n| async | elif | if | or | yield |\n\n\nThese keywords are part of the Python syntax and are reserved for specific programming purposes. \n\nOkay, we’ve got the names and the no-go words, now let’s see how Python does the math and logic with operators. \n\n## Python operators \n\nOperators in Python are special symbols used to perform operations on variables and values. Python supports a wide range of operators based on their functionality. \n\n### Types of Python operators \n\n| Operator Type | Description | Example |\n|---------------|------------------------------------------|----------------------------|\n| Arithmetic | Performs mathematical operations | `+`, `-`, `*`, `/` |\n| Comparison | Compares two values | `==`, `!=`, `>`, `<` |\n| Logical | Combines conditional statements | `and`, `or`, `not` |\n| Assignment | Assigns values to variables | `=`, `+=`, `-=` |\n| Bitwise | Performs operations on bits | `&`, `|`, `^`, `~` |\n| Membership | Tests membership in a sequence | `in`, `not in` |\n| Identity | Compares memory locations of two objects | `is`, `is not` |\n\n**Example:** \n\n```py \n# Arithmetic \na = 10 + 5 # 15 \nb = 4 * 2 # 8 \n\n# Comparison \nprint(10 > 5) # True \n\n# Logical \nprint(True and False) # False \n\n# Assignment \nx = 5 \nx += 2 # Now x is 7 \n \n# Membership \nprint('a' in 'cat') # True \n\n# Identity \nprint(x is 7) # True \n``` \n\nBut what happens when our code gets too long to fit on a single line? That's where statement continuation comes into play! \n\n## Statement continuation in Python \n\nPython 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. \n\n### Explicit line continuation \n\nUse the backslash `\\` to explicitly continue a statement on the next line: \n\n```py \ntotal = 10 + 20 + \\ \n 30 + 40 \nprint(total) # Output: 100 \n```\n\n### Implicit line continuation \n\nPython allows you to break lines implicitly when using parentheses `()`, square brackets `[]`, or curly braces `{}`: \n\n```py \nnumbers = [ \n 1, 2, 3, \n 4, 5, 6 \n]\n\nresult = ( \n 10 + 20 + \n 30 + 40 \n) \n\nprint(result) # Output: 100 \n``` \n\nSo far, we've learnt how our code talks, now let’s make it listen. \n\n## Taking input from users in Python \n\nPython 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: \n\n**Example:**\n\n```py \nname = input("What is your name? ") \nprint("Hello, " + name + "!") \n``` \n\n### Input with type conversion \n\nSince `input()` returns a string, we'll often need to convert it to the correct type using `int()`, `float()`, or other conversion functions. \n\n```py \nage = input("Enter your age: ") # This is a string \nage = int(age) # Now it's an integer \nprint("You will be", age + 1, "next year.") \n```\n\nWith the fundamentals of Python syntax in place, we're all set to bring our coding ideas to life. \n\n## Conclusion \n\nIn 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. \n\nTo further enhance your Python skills, take Codecademy's [Learn Python 3](https://www.codecademy.com/enrolled/courses/learn-python-3) course and dive deeper into coding with Python. \n\n## Frequently asked questions \n\n### 1. Why can't I use Python keywords to name variables? \n\nKeywords 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. \n\n### 2. How to code 1 to 100 in Python? \n\nYou can use a simple for loop to print numbers from 1 to 100 in Python: \n```py \nfor i in range(1, 101): \n print(i) \n``` \n\n### 3. Is Python easier than Java? \n\nPython 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. \n\n### 4. What is Python used for? \n\nPython is a versatile language used for [web development](https://www.codecademy.com/resources/blog/what-is-web-development/), [data analysis](https://www.codecademy.com/learn/paths/data-analyst), [artificial intelligence](https://www.codecademy.com/resources/docs/ai), [machine learning](https://www.codecademy.com/learn/paths/machine-learning-engineer), automation, game development, and more. Its easy-to-learn syntax makes it ideal for both beginners and professionals. \n\n\n### 5. What is `+=` in Python? \n\nThe `+=` 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: \n\n```py \nx = 5 \nx += 3 # Now x is 8 \n``` \n\nIt’s shorthand for `x = x + 3`. ","wordCount":1788,"author":{"@type":"Organization","name":"Codecademy","sameAs":"https://www.codecademy.com/"},"publisher":{"@type":"Organization","name":"Codecademy","sameAs":"https://www.codecademy.com/"}}
| apple-itunes-app | app-id=1376029326 |
| theme-color | #10162F |
| fb:app_id | 307818116683104 |
| fb:profile_id | codecademy |
| og:site_name | Codecademy |
| og:type | website |
| og:rich_attachment | true |
| og:image | https://images.codecademy.com/social/logo-codecademy-social.png |
| twitter:card | summary_large_image |
| twitter:image | https://images.codecademy.com/social/logo-codecademy-social.png |
| next-head-count | 34 |
| None | https://images.codecademy.com/social/logo-codecademy-social.png |
Links:
Viewport: width=device-width