[Python Tutorials -Day 1] Python Syntax

by Randy Moore in Tutorial on May 10, 2020

The first and most important thing to learn a language is understanding the syntax of the language. Python is known for its simplicity and easy writing syntaxes. This article is aimed to guide you through all the syntactical structures of Python. If you are a beginner, this is the right place for you. Series about Python Tutorial. Python Syntax article will help you in identifying and debugging the syntax of Python.

Python Syntax 

What is Syntax?

In every programming language, you will come along the word syntax. A programming syntax refers to a set of rules. When we run a Python program, first it is read by a parser. The parser will only understand the Python code if it is according to the predefined rules of Python programming otherwise it will give you syntax errors. That is why it is important to understand the syntax of the language.

Example of Python Syntax

In this Python Tutorial, before learning the syntax of Python, let’s see an example of how a basic Python program looks like.

Code:

#Simple Python Program that compares two numbers.

print(“Enter first integer value”)

first_value = int(input())

print(“Enter second integer value”)

second_value = int(input())

if(first_value > second_value):

print(“First value is greater than second”)

else:

print(“Second value is greater than first”)

The above program takes two values from the user and then we compare which of them is bigger. Don’t worry if you don’t understand the code yet, with this example, you can get a clue about how Python code is written.

Types of Syntax Structures in Python

Now, let’s go through the various syntax structures of Python programming.

1. Python Line Structure

A Python program is divided into logical lines where each line comprises one or more physical lines of code.

The Python interpreter ignores the blank lines, which are the lines that only contain white spaces.

Code:

Msg = “Hi! Welcome to the python syntax article”

print(Msg)

Output:Hi! Welcome to the python syntax article

screenshot

2. Multiline Statements

If you have studied another language like C/C++ or Java then you are used to writing semicolons after every statement. In Python, we don’t use semicolons instead of them we use newlines for separating statements.

Sometimes when you want to write a long code in a single line we can break the statement into multiple lines using the backslash character(\).

Code:

print(“Hi! \

How are you today? \

What are you planning this Sunday? \

”)

Output:Hi! How are you today? What are you planning this Sunday?

3. Multiple Statements in One Line

Python also allows you to write multiple statements in a single line. For this purpose, we use semicolons to separate statements within the same line. This can reduce the readability of code so only use this if it is appropriate in the situation.

Code:

num1 = 10 ; num2 = 20 ; print(“Sum of numbers = ”, num1+num2)

Output:Sum of numbers = 30

4. Comments in Python

Writing comments for our code is useful for programmers to add notes or explanations of the code. Comments are just for reading and Python interpreter ignores whatever we write in comments. Comments can be either single-line or multiline comments.

4.1. Single-Line Comments

The symbol (#) indicates the starting of the comment and everything written after the # is considered as comment.

Code:

  1. #Interpreter will ignore this
  2. print(“python tutorials”)
  3. print(“python tutorials”) #comments can be added after code

Output:

python tutorials
python tutorials

screenshot :

4.2. Multiline Comments

When the comment is large, we can use the triple-double quotes to write comments in multiple lines.

Code:

“””

This is a multiline

Comment

Used for explaining functions,

Codes, etc

“””

print(“Multiline comment example”)

Output:Multiline comment example

5. Python Indentation

The indentation is quite unique syntax of Python. Other languages like C/C++, Java and JavaScript use curly braces ‘{}’ to indicate block of codes. Python uses white spaces (space or tabs) to define the block of functions, flow control and codes of class. It is mandatory to use a consistent amount of spaces for blocks throughout the code.

Let’s see this with an example:

Code:

name = “python tutorials”

if name == “python tutorials”:

print(“We know ”)

else:

print(“We don’t know ”)

Code:

name = “python tutorials”

if name == “python tutorials”:

print(“We know ”)

print(“Unequal spaces in indentation”)

else:

print(“We don’t know ”)

Output:TabError: inconsistent use of tabs and spaces in indentation

6. Python Quotations

The Python string literals can be enclosed in two ways. We can write strings between single quotes(’) or double quotes (“) and they can be used interchangeably.
Code:

message1 = “Hey”

message2 = ‘Hey’

print( message1)

print( message2)

Output:Hey
Hey

When we want to use quotes inside the string then we can combine them.

Code:

print(“ Hey ‘Anna’ ”)

print(‘ Hey “Anna” ’)

Output:Hey ‘Anna’
Hey “Anna”

7. Python Identifier

A program contains variables, functions, classes, modules, packages etc. Identifier is the name given to these programming elements. There are some rules which we have to keep in mind for creating an identifier. Let’s see them one by one.

  • Identifier can only begin with characters starting from A-Z (Uppercase letters), a-z (lowercase letters) or _ (underscore).
  • They can be then followed by any number of letters, digits or underscores.
  • Python is case sensitive language so the identifiers ‘count’ and ‘Count’ are two different identifiers.
  • Python Reserved keywords like for, global, continue, break, etc cannot be used as identifiers.

Examples of Valid Identifiers:

  • name
  • _3name6
  • get_all_names
  • YES

Examples of Invalid Identifiers:

  • 1name
  • name$
  • get-score

8. Getting Users Input

To get the input from the user, Python has input() function in the Python’s core library. It reads the input given by the user as a string and we can store the input in a variable.

Code:

Msg = input()

print(Msg)

When the interpreter reaches the input() function, it will wait for an input from the user. The user can give input, for example, here we can type “Hello” and then after pressing enter, the code will execute in which we store the input in Msg variable and print it afterwards.

Output:>>>Hello
‘Hello’

One important thing to note is that even when you give a number as input, Python will treat it as a string. So, when we want to work with numbers, we can use type conversion methods with input() function to convert strings into numbers.

Code:

num = int( input())

num = num + 10

print(num)

Output:>>>5
15

9. Python String-Formatters

String-formatters are very useful for displaying strings in the format we want. Let’s see the different ways of formatting string:

9.1. % operator

With the % operator, we can format a string to contain both text and values of identifiers. We use %s where we want our value to appear. After the string, we put the % symbol and then mention the identifiers in parameters.

Code:

rollNo= 1

subject= “Maths”

print(“ The roll no. %s studies %s subject” % (rollNo, subject) )

Output:The roll no. 1 studies Maths subject

9.2. format Method

The format method is similar to the above method but instead of %s we put 0,1,2… values or identifiers in curly braces and then use format method on the string.

Code:

rollNo= 1 ; subject= “Maths”

print(“ The roll no. {0} studies {1} subject”. format(rollNo, subject) )

print((“ The roll no. {rollNo} studies {subject} subject”.format(rollNo=10, subject=”Science”))

Output:The roll no. 1 studies Maths subject
The roll no. 10 studies Science subject

9.3. f-strings

F-strings are easier to work with. You just need to put ‘f’ as a prefix before string and then you can put the identifier in curly braces within the string.

Code:

rollNo= 5 ; subject= “Biology”

print( f“The roll no. {rollNo} studies {subject} subject” )

Output:The roll no. 5 studies Biology subject

Summary

In this article, we saw all the Python syntax structures in detail. This will give a good idea about how programming in Python is done. We learned the Python line structure, comments, Python indentation, identifiers, taking input from users and formatting strings.

Now you can start your journey in Python programming. I hope you like this Python syntax tutorial and feel free to ask your queries in the comment section.

Donate via paypal at : HERE . Thank you very much!

Categories

2
Leave a Reply

avatar
1 Comment threads
1 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
2 Comment authors
Randy MoorePerter Pa Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Perter Pa
Guest
Perter Pa

Thank you. Python Tutorial is very good!..