Python Syntax – Take your first step in the Python Programming World

Python course with 57 real-time projects - Learn Python

Today, we will learn about Python syntax in which, we will see what is Python syntax and how it is different from Java and C++.

After reading this article of DataFlair, you will be able to identify and debug Python syntax.

So, let’s first understand Python Syntax with the help of examples.

Do not forget to check Important Interview Questions from this topic at the end.

What is Python Syntax?

The Python syntax defines all the set of rules that are used to create sentences in Python programming.

For example –  We have to learn grammar to learn the English language. In the same way, you will need to learn and understand the Python syntax in order to learn the Python language.

Example of Python Syntax

Python is a popular language because of its elegant syntax structure.

Let’s take a quick look at a simple Python program and you will get an idea of how programming in Python looks like.

#Simple Python Program to see if a user is eligible to vote or not.

# getting user’s name 
print("Enter your name:")
name = input()

# getting user’s age
print("Enter your age:")
age = int(input())

# condition to check if user is eligible or not
if( age >= 18 ):
    print( name, ' is eligible to vote.')
else:
    print( name, ' is not eligible to vote.')

Output

Enter your name:
Harsh
Enter your age:
19
Harsh is eligible to vote.

Types of Syntax Structures in Python

Types of syntax in Python

1. Python Line Structure

A Python program comprises logical lines. A NEWLINE token follows each of those. The interpreter ignores blank lines.

The following line causes an error.

>>> print("Hi
How are you?")

Output:

SyntaxError: EOL while scanning string literal

2. Python Multiline Statements

This one is an important Python syntax. We saw that Python does not mandate semicolons.

A new line means a new statement. But sometimes, you may want to split a statement over two or more lines.

It may be to aid readability. You can do so in the following ways.

a. Use a backward slash

>>> print("Hi\
how are you?")

Output:

Hihow are you?

You can also use it to distribute a statement without a string across lines.

>>> a\
=\
10
>>> print(a)

Output:

10

b. Put the String in Triple Quotes

>>> print("""Hi
       how are you?""")

Output:

Hi
how are you?

However, you can’t use backslashes inside a docstring for statements that aren’t a string.

>>> """b\
=\
10"""

Output:

‘b=10’
>>> print(b)

Output:

Traceback (most recent call last):
File “<pyshell#6>”, line 1, in <module>
print(b)
NameError: name ‘b’ is not defined

3. Python Comments

Python Syntax ‘Comments’ let you store tags at the right places in the code. You can use them to explain complex sections of code.

The interpreter ignores comments. Declare a comment using an octothorpe (#).

>>> #This is a comment

Python does not support general multiline comments like Java or C++.

4. Python Docstrings

A docstring is a documentation string. As a comment, this Python Syntax is used to explain code.

But unlike comments, they are more specific. Also, they are retained at runtime.

This way, the programmer can inspect them at runtime. Delimit a docstring using three double-quotes. You may put it as a function’s first line to describe it.

>>> def func():
	"""
		This function prints out a greeting
	"""
	print("Hi")
>>> func()

Output:

Hi

5. Python Indentation

Since Python doesn’t use curly braces to delimit blocks of code, this Python Syntax is mandatory.

You can indent code under a function, loop, or class.

>>> if 2>1:
      print("2 is the bigger person");
      print("But 1 is worthy too");

Output:

2 is the bigger person
But 1 is worthy too

You can indent using a number of tabs or spaces, or a combination of those.

But remember, indent statements under one block of code with the same amount of tabs and spaces.

>>> if 2>1:
     print("2 is the bigger person");
   print("But 1 is worthy too");

Output:

SyntaxError: unindent does not match any outer indentation level

6. Python Multiple Statements in One Line

You can also fit in more than one statement on one line. Do this by separating them with a semicolon.

But you’d only want to do so if it supplements readability.

>>> a=7;print(a);

Output:

7

7. Python Quotations

Python supports the single quote and the double quote for string literals. But if you begin a string with a single quote, you must end it with a single quote.

The same goes for double-quotes.

The following string is delimited by single quotes.

>>> print('We need a chaperone');

Output:

We need a chaperone

This string is delimited by double-quotes.

>>> print("We need a 'chaperone'");

Output:

We need a ‘chaperone’

Notice how we used single quotes around the word chaperone in the string? If we used double quotes everywhere, the string would terminate prematurely.

>>> print("We need a "chaperone"");

Output:

SyntaxError: invalid syntax

8. Python Blank Lines

If you leave a line with just whitespace, the interpreter will ignore it.

9. Python Identifiers

An identifier is a name of a program element, and it is user-defined. This Python Syntax uniquely identifies the element.

There are some rules to follow while choosing an identifier:

  • An identifier may only begin with A-Z, a-z, or an underscore(_).
  • This may be followed by letters, digits, and underscores- zero or more.
  • Python is case-sensitive. Name and name are two different identifiers.
  • A reserved keyword may not be used as an identifier. The following is a list of keywords.
anddefFalseimportnotTrue
asdelfinallyinortry
assertelifforispasswhile
breakelsefromlambdaprintwith
classexceptglobalNoneraiseyield
continueexecifnonlocalreturn

Apart from these rules, there are a few naming conventions that you should follow while using this Python syntax:

  • Use uppercase initials for class names, lowercase for all others.
  • Name a private identifier with a leading underscore ( _username)
  • Name a strongly private identifier with two leading underscores ( __password)
  • Special identifiers by Python end with two leading underscores.

10. Python Variables

In Python, you don’t define the type of the variable. It is assumed on the basis of the value it holds.

>>> x=10
>>> print(x)

Output:

10
>>> x='Hello'
>>> print(x)

Output:

Hello

Here, we declared a variable x and assigned it a value of 10. Then we printed its value. Next, we assigned it the value ‘Hello’ and printed it out.

So, we see, a variable can hold any type of value at a later instant. Hence, Python is a dynamically-typed language.

11. Python String Formatters

Now let us see the different types of String formatters in Python:

a. % Operator

You can use the % operator to format a string to contain text as well as values of identifiers. Use %s where you want a value to appear.

After the string, put a % operator and mention the identifiers in parameters.

>>> x=10;  printer="HP"
>>> print("I just printed %s pages to the printer %s" % (x, printer))

Output:

I just printed 10 pages to the printer HP

b. Format Method

The format method allows you to format a string in a similar way. At the places, you want to put values, put 0,1,2,.. in curly braces.

Call the format method on the string and mention the identifiers in the parameters.

>>> print("I just printed {0} pages to the printer {1}".format(x, printer))

Output:

I just printed 10 pages to the printer HP

You can also use the method to print out identifiers that match certain values.

>>> print("I  just printed {x} pages to the printer {printer}".format(x=7, printer='HP'))

Output:

I just printed 7 pages to the printer HP

c. f-strings

If you use an f-string, you just need to mention the identifiers in curly braces. Also, write ‘f’ right before the string, but outside the quotes used.

>>> print(f"I just printed {x} pages to the printer {printer}")

Output:

I just printed 10 pages to the printer HP

So, this was all about the Python Syntax tutorial. I hope you liked our explanation.

Python Interview Questions on Python Syntax

  1. What are Python Identifiers?
  2. Name various string formatters in Python.
  3. What is the use of Python Docstrings?
  4. What is the use of Python Multiline Statements?
  5. Explain Python Quotations.

Summary

In this Python Syntax tutorial, we learned about the basic Python syntax.

We learned about its line structure, multiline statements, comments and docstrings, indentation, and quotations.

We also learned about blank lines, identifiers, variables, multiple statements in one line, and string formatters.

You give me 15 seconds I promise you best tutorials
Please share your happy experience on Google

follow dataflair on YouTube

81 Responses

  1. Racks says:

    Very nice article for python beginners. I like your blog design and your presentation.

    • Data Flair says:

      Thank you, for such nice words for our “Python Syntax Tutorial”. Feel free to share this blog with Python beginners to understand and Learn Python Programming.

  2. Venugopal says:

    I have never seen these type of Python tutorial anywhere. I hope this Python syntax tutorial will be helpful for python beginners. The Python Syntax Examples were of great use.
    Keep rocking…

  3. Vasantharaj says:

    Great effort and well organised

    • Data Flair says:

      Thanks for being a loyal reader of Python Syntax Tutorial, your comments keep us Motivated to bring you nothing but the best.
      Keep Learning….. Keep Visiting Data-Flair.

  4. Shubham Panchal says:

    In Indentation part, both the parts of code seems same to me
    What’s the difference there ?

  5. hieudoanitus says:

    Series of material in that site is good. I’ve already read many tutorial sites but this site is very clear and comprehensive. Thanks your team.

    • Data Flair says:

      Hii Hieudoanitus,
      Thank you for giving such a fab review on Python Syntax. Hope you have checked our Python Tutorial. If not then we recommend you to check that. Also, you can check more new Python articles and if there is any topic which you want to learn with us please let us know. We will be happy to help you.
      Try out latest Python blog
      https://data-flair.training/blogs/python-slice/

  6. Pooja tomar says:

    I want to know will you people provide any online python course in which you will provide us a certificate of the course

    • Data Flair says:

      Hi Pooja
      As you ask for the online Python Course, currently we don’t have such a course. Soon, we will start the Python online course with Video Tutorials. Till then you can take knowledge from our published Python material. This will guide to learn Python easily.
      Thank you for visiting Data Flair.

  7. Rishi says:

    Hi,
    Thanks for such a wonderful tutorial, its very easy to learn here. But from few days now I am unable to get the content tree page to jump on to a particular section. It was working fine before, but now i am unable to proceed to the topics, Can you please check?

    • DataFlair Team says:

      Hi Rishi,
      Thanks for the comment on Python syntax tutorial. The sidebar which was on the under construction mode. Now, it is working fine. You can refer and explore more about Python programming Language.
      Regards,
      Data Flair

  8. Hiren says:

    Hi, great tutorial about Python…
    Will you please describe f-string with example??

    • RahulD says:

      f-string didn’t work in case .
      >>> print(f” I just printed {x} pages on printer {printer}”)
      SyntaxError: invalid syntax

      x=10; printer=”HP”

      • sahastra says:

        even I got same error.
        what’s the syntax

        • DataFlair Team says:

          Hi Sahastra,
          Thanks for the feedback, we have corrected our mistake. Now, you can learn Python Syntax easily with all the exmaple.
          Regards,
          DataFlair

      • DataFlair Team says:

        Hello RahulD,
        Thanks for pointing out, it was our typo mistake in Python Syntax Tutorial. We have made the necessary changes. Now, you can run all the programs.
        Keep learning and keep exploring DataFlair

    • DataFlair Team says:

      Hey there, Hiren,
      Thanks for interacting through Python Syntax Tutorial. Sometimes, you may want to embed the values of variables in the middle of the strings. To do that, you can precede a string with the character ‘f’. Within the string then, you can surround variables names in curly braces {}. Here’s an example:

      >>> a,b=2,3
      >>> print(f“{a}+{b}={a+b}”)
      2+3=5

      This piece of code assigns values 2 and 3 to the variables a and b, then prints their sum.
      Hope, it will help you!
      Regards DataFlair

  9. Jeelani says:

    print(“I just printed {x} pages to the printer {printer}”.format(x=7, printer=’HP’))

    • DataFlair Team says:

      Hi Jeelani,
      We are glad our readers trying to interact with us, through there valuable feedbacks. We have updated our Python Syntax tutorial, all the programmes and syntax were reviewed by our Python expert. Now onwards, you will not find any difficulties.
      Regards,
      DataFlair

  10. Brian Kamanga says:

    Great introduction, thank you! I couldn’t get around running the function though, but I believe I will find it in the tutorials as I go on.

    • DataFlair Team says:

      Hi Brian,
      Thanks for referring to our Python Syntax tutorial. You did not fail in making a function; this is just inspiration to practice ahead. So, keep exploring and keep practising Python programs from DataFlair.

  11. Amrita saini says:

    hats off to this blog i loveee thiss

  12. Raffui samal says:

    what is Python Docstrings? how to use it.

  13. Raffui samal says:

    its give error syntax

    • DataFlair Team says:

      Hi Raffui
      It was our typing mistake, we have corrected it.
      Now the code is running sucessfully.
      Thanks for the comment

  14. Asbul yamen says:

    help I got error syntax docstrings

    • DataFlair Team says:

      Hi Asbul,
      Thanks for visiting DataFlair. If you are getting an error, maybe you’re copy-pasting it all at once? You need to copy the function definition first, and then, the call to it.
      Hope, it helps!

  15. Bonaventura says:

    Don’t know why, but link at the end of section 11 (https://data-flair.training/blogs/python-operators/) redirects to this image: https://data-flair.training/blogs/wp-content/uploads/sites/2/2017/12/Python-Operators.jpg

    Could you please fix that? Thanks!

  16. SKM says:

    Superb Guys, No special word is coming in my mind. Just AWESOME..

    • DataFlair Team says:

      We are eternally grateful for your feedback. There are many more Python Tutorials, we hope you will find them of use.

  17. Payam Sarwar says:

    Hi Team,

    Please show the output after giving input. It might help in understanding the result of that code.

    Thank you!
    Warm Regards,
    Payam Sarwar

    • DataFlair Team says:

      We have added all the outputs in the article. Thank you for your suggestion and keep visiting DataFlair for regular updates on Python programming.

  18. santosh mandal says:

    describe about python docstring

  19. dakshit says:

    your blog is like an online python book
    well done

    • DataFlair Team says:

      Hello Dakshit,

      Thank you for your appreciation, do share this blog on social media with your friends to help them.

  20. jishan bukhari says:

    hello, thank you for this.
    i m having INDENTATION ERROR entering after typing line no. 4 , in DOCSTRING TOPIC.

    • DataFlair Team says:

      Hi Jishan
      Indentation error occurs when you have missed out to indent the code ie adding tabs or spaces. please check the same and rerun your code.

  21. Jeevan says:

    docstrings error
    it is showing error after printing many times the output
    k (most recent call last):
    File “”, line 1, in
    File “”, line 6, in func
    File “”, line 6, in func
    File “”, line 6, in func
    [Previous line repeated 992 more times]
    File “”, line 5, in func
    RecursionError: maximum recursion depth exceeded while calling a Python object
    hello

  22. Mantripat says:

    This tutorial is very well organised. Helped me a lot in my learning… Thank you so much

  23. Jason says:

    In the python string formaters section, what is the difference between % operator, f-strings and format method? Will it make an great impact during the code is run?

    • DataFlair says:

      % is an operator, format() is an inbuilt method and f-string is a literal string in python.
      .format() Speed: 1.615438
      % Speed: 1.2333532999999999
      f-string Speed: 1.2435527000000004

  24. Mukul Sharma says:

    print(“Today i enjoyed this arrticle very much”)
    i have some doubts kindly solve my doubta. you can reply in points same as i asked
    1. 4th point – Python Docstrings ( i was unable to understand this point )
    2. in 6th point a=7; print(a); show errror
    3. in 7th point can i use this
    pint( ‘we need a ‘chaperone”)
    if No then why ?

    • DataFlair says:

      • Docstring is used to explain code, just like comments.
      • There might be some syntactical error, check once again from the website
      • No, you cannot because print() accepts a string argument and you’re not providing string

  25. Mukul Sharma says:

    print(“Today i enjoyed this article very much”)
    i have some doubts kindly solve my doubta. you can reply in points same as i asked
    1. 4th point – Python Docstrings ( i was unable to understand this point )
    2. in 6th point a=7; print(a); show error
    3. in 7th point can i use this
    pint( ‘we need a ‘chaperone”)
    if No then why ?

    • DataFlair Team says:

      Point – 4
      Python docstrings are the strings literals that appears right after a function, method, class or a module.
      For Example
      >>> def func():
      “””
      This function prints out a greeting
      “””
      print(“Hi”)
      >>> func()

      Point – 6

      please post the complete stacktrace of error

      Point – 7

      No you can’t use this type of code because at the starting the sting is delimited by single quote and at the ending it is delimited by double quotes, then you will face error
      The correct code is
      print(“We need a ‘chaperone’ “);

      OUTPUT – We need a ‘chaperone’

  26. TLMutz says:

    I cannot seem to get 4: docstring to work. I always end up with an “IndentationError: expected an indented block” when i input the second “””.

    • DataFlair says:

      You have to check the indentation of opening quotation matches the closing ones. Or you can copy from the article and then try.

  27. Diego Bejar says:

    the python interpreter is telling you that the indentation is not set correctly, check that and try again.

    • DataFlair says:

      Actually the example is given purposely to intoduce the indentation error to the reader. Thank you by the way and Happy learning!

  28. mithun chowdary says:

    Hi, in Docstrings section, why do we need to define a function? Can we type directly
    “””
    This function prints out a greeting
    “””
    print(“Hi”)

    What is the use of defining function here?

    • DataFlair says:

      Docstring is actually a string that is defined for a function and that represents the operations in the function. The code you have mentioned executes without giving any error. But we cannot name it as a docstring, it would just be a string.

  29. Data Scientist says:

    Honestly its too tough for beginner user.

  30. Tshegofatso Ramela says:

    Am a python beginner and just started today the 24th of May 2022. This site just welcomed me, hope ill have the experience and get to understand more of this python language.

Leave a Reply

Your email address will not be published. Required fields are marked *