0% found this document useful (0 votes)
7 views9 pages

Python Basics: Syntax and Indentation

Uploaded by

VaibhaV GouR
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views9 pages

Python Basics: Syntax and Indentation

Uploaded by

VaibhaV GouR
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Online Summer Training Program – 2020

R - Labs BASICS OF PYTHON


Task 1.2 - Basic Syntax
In Task 0 you learnt how to install Jupyter Notebook. So, now we will go through some very basic
codes snippets to get you familiar with the platform.

Follow the steps in Task 0 to execute/run the code.

Example 1:

Add new cell by clicking on + tab available in menu bar at top

Example 2:

Hope you’ve understood how to write and run a code in Jupyter Notebook.

So, moving forward, in this section you will be learning about the basic syntax of python 3.x. The
prescribed rule of writing a code is called syntax.

1. Lines/statement and Indentation


1.1 Lines/statement
In C/C++/C#, a semicolon (;) denotes the end of a statement. But in Python, a piece of text
terminated by pressing “Enter” key is considered as one statement.

Example:

Outcome:

Here print(“Hello”) and print(“Welcome”) are the 2 lines/statements.


Note: print( )is a function in python used to diplay the output. Detailed examples of the same are
given in point 5 of this section.

St. Vincent Pallotti College


of Engineering & Technology, Nagpur
Online Summer Training Program – 2020
R - Labs BASICS OF PYTHON
1.1.1 Continuation of Statement
However, you can show the text spread over more than one line to be a single statement by
using the backslash (\) as a continuation character. Look at the following example.

Example:

Outcome:

1.1.2 Multiple Statements in Single Line


If you want to print multiple statements on single line, use semicolon

Example:

Outcome:

1.2 Indentation
 The meaning of indentation is “to start a line/ block of text few spaces away from the
margin than from the main part of the text.”
 In C, C++, statements inside curly brackets ‘{’ and ‘}’ are treated as a block.
For example:
void main()
{
Statement 1;
Statement 2;
}
From the above example, Statement 1& Statement 2, are considered as the part of the part
of the ‘main’ function. We could identify it as a part of main function because they were
enclosed in curly brackets.

 Similarly in python, uniform indentation is used to denote a block of statements.


 When a block is to be started, type the colon symbol (:) and press Enter.

St. Vincent Pallotti College


of Engineering & Technology, Nagpur
Online Summer Training Program – 2020
R - Labs BASICS OF PYTHON
 After pressing ‘Enter’, the cursor goes to the next line and automatically leaves an
additional whitespaces (called indent).
Note: By default the indent consists of ‘4 spaces (of spacebar)’ which is equivalent to ‘1
Tab’. So if you want to give indentation you need to give ‘4 spaces’ or ‘1 Tab’.
Example:
// Code in C language # Code in python language
int a = 10; a = 10
if(a = = 10 ) if a = = 10:
{ print(“ Value of a is 10. ”)
printf(" Value of a is 10 " ); else:
} print(“ Value of a is not 10.
else ”)
{
printf(" Value of a is not 10 " );
}

Explanation:
Explanation of C code Explanation of python code
1. After ‘if’ condition is given 1. After ‘if’ condition, a semicolon (:) if given,
a ‘{’ is placed, indicating indicating the start of ‘if’ statement..
the start of ‘if’ statement.
2. Statement is written inside the ‘if’ condition.
if a = = 10:
2. Statement is written inside
print(“ Value of a is 10 ”)
the ‘if’ condition.
Here, you can see the print statement doesn’t
printf(“ Value of a is 10 ”)
start from the level of ‘if’ condition.
It has few spaces called indent.
3. To close ‘if’ condition, the indent on next
line is removed.
3. To close the ‘if’ condition a if a = = 10:
‘}’ is placed. print(“ Value of a is 10. ”)
. else:
Here, the ‘else’ condition starts from the
level of ‘if’ condition.
4. Similarly an else statement 4. Similarly, the statement is also written in
is also written. ‘else’ condition.

You can also add a block inside a block. In such cases, indentation of inner block will increase.
Example:
a =10; b = 6
if a = = 10:
print(“a is equal 10”)
if b = = 6:
print(“b is equal to 6”)

St. Vincent Pallotti College


of Engineering & Technology, Nagpur
Online Summer Training Program – 2020
R - Labs BASICS OF PYTHON
2 Comments
2.1 Single line-comments
 A comment is a piece of text to let someone know what is being done in a block of code.
 It doesn't affect the outcome of a code.
 In a Python, the symbol ‘#’ indicates the start of a comment line. It is effective till the end
of the line in the editor.
 If # is the first character of the line, then the entire line is a comment.

Example:

Here you can see that the output is only “Hello World”. The comments are not reflected in
the output.

 We can also comment after a statement of the code

Example:

2.2 Multi-line Comments


 In Python, there is no provision to write multi-line comments, or a block comment. Each
line should have the # symbol at the start to be marked as a comment.
 A triple quoted multi-line string is also treated as a comment (if it is not a docstring of a
function or a class).

Example:

St. Vincent Pallotti College


of Engineering & Technology, Nagpur
Online Summer Training Program – 2020
R - Labs BASICS OF PYTHON
3 Getting User’s Input
 In some codes you might need to take inputs from the user.
 This is done with the help of input( ) function in python.
 The input taken with the input( ) function is in form of a string (you will learn about strings
in future sections).

Syntax:

input( prompt )

Here, the prompt is the message that you want to display to the user. This message is to be written
between inverted quotes (“message”).

Example 1:

Here, “Enter your college name: ” is the message/prompt, which will be visible to the user once
the code is run.

Once the code is run, you’ll get a block below the cell, with your message/prompt. You need to
type your answer in that block.

Then press Enter. You will get the following output.

Here, the name of the college which you have entered is stored in the variable ‘college’.
So if you print the variable ‘college’, you’ll get the following output.

St. Vincent Pallotti College


of Engineering & Technology, Nagpur
Online Summer Training Program – 2020
R - Labs BASICS OF PYTHON

Example 2:
Writing a code to input 2 numbers from user and perform addition on them.

Note: In the topic ’Getting user’s input’, we learnt that the input( )function always takes inputs in
form of strings. Thus we need to convert it into integer before adding. The ‘int’ written
before input( ) does this conversion for us. This is called ’typecasting’. You will learn about
this in future sections.

Run the code.

You’ll be asked to enter the value for ‘a’.


Enter the value as shown below & press ‘Enter’.

Next you’ll be asked to enter the value for ‘b’.


Enter the value as shown below & press ‘Enter’.

You will get the following output.

Now we will add the values of ‘a’ & ‘b’ and print the result.

St. Vincent Pallotti College


of Engineering & Technology, Nagpur
Online Summer Training Program – 2020
R - Labs BASICS OF PYTHON

4 Keywords
 All computer programming languages comprise of a set of predefined words which are
called keywords.
 These are predefined words, hence cannot be used for any other purpose, than for which it
is defined.
 Some of the keywords which you might come across in this training are mentioned below.

and break class or


continue def del pass
elif else if return
for while import from
not False True in

Note: All these are case sensitive, hence while using these keywords make sure that you use
the correct casing.
 If you want to know what exactly is the use these keywords, then you can use the following
command on Jupyter Notebook.

Syntax:
help(“name_of_the_keyword”)

Example:

Output:

St. Vincent Pallotti College


of Engineering & Technology, Nagpur
Online Summer Training Program – 2020
R - Labs BASICS OF PYTHON
5 Displaying output
Any statement can be displayed in the output with the help of print( ) function in python.
Different ways to use print( ) function is as shown below.
Example 1:
Printing a string.

Output 1:

Example 2:
Printing a value stored in a variable.

Output 2:

Here “college” is the variable.

Example 3:
Printing multiple strings and variable values using single print.

Output 3:

Example 4:
Printing multiple values separated by separators.

From Example 3, it is clear that the default separator is ‘space’.


Thus to replace the space with a separator we use the parameter ‘sep’

Output 4:

In this example, we have used comma (,) as the separator. You can use any symbol, alphabet,
numbers as a separator

St. Vincent Pallotti College


of Engineering & Technology, Nagpur
Online Summer Training Program – 2020
R - Labs BASICS OF PYTHON
Example 5:
Using multiple print statements.

Output 5:

Here you can see that all the elements of same print statement are displayed on the same line.

Example 6:
Display values in separate print functions on single line.

In the previous example you saw that, the elements of separate print functions were displayed
of separate lines.
This is because the output of print function ends with a newline (equivalent to Enter).
Thus to do this we use the parameter ‘end’.

Output 6:

… Happy Learning ! ...

Video link: [Link]

References:

1. [Link]
2. [Link]
3. [Link]

St. Vincent Pallotti College


of Engineering & Technology, Nagpur

Common questions

Powered by AI

In Python, multi-line strings are enclosed in triple quotes (""" or ''') and can span multiple lines . They can also be used as comments if they are not utilized as docstrings for functions or classes, effectively ignoring them during execution. However, they are distinct from multi-line comments as Python lacks explicit block comment syntax. Instead, each line of a comment requires the '#' character at its start to be recognized as a comment . This dual-purpose usage of triple-quoted strings highlights Python's flexibility in distinguishing between string variables and comments within the same syntax construct.

Python's approach to comments, using '#' for single-line comments and triple-quoted strings for emulated multi-line comments, allows for clear and contextual documentation within code. Single-line comments can appear anywhere in the code for line-specific annotations without disrupting execution . The utilization of multi-line strings as comments, while not conventional, allows for block comments and provides flexibility but requires caution to ensure these strings are not mistakenly used as docstrings within classes or functions. This design choice emphasizes coding simplicity and readability, reducing clutter compared to other languages that use explicit multi-line comment markers, yet demands consistent comment practices to ensure maintainability .

Indentation in Python is crucial for defining blocks of code, acting as a syntax rule that distinguishes it from languages like C or C++. In Python, uniform indentation denotes a block of statements, starting with a colon (:) after control flow statements like 'if' or 'for,' followed by pressing 'Enter,' which moves the cursor to the next line with an indent. This indent, by default, consists of 4 spaces . Unlike Python, C or C++ uses curly braces '{}' to indicate the start and end of a code block, making indentation visually helpful but not syntactically required .

In Python, a backslash (\) is used as a continuation character to extend a long statement across multiple lines. It tells the interpreter that the following line is a continuation of the current line, maintaining the structure and readability of code when managing long expressions . In contrast, C/C++ does not require a line continuation character for multi-line statements within single logical operations, as these languages use semicolons to terminate statements, inherently supporting multi-line single statements within blocks delimited by braces .

Keywords in Python are reserved words that have specific meanings and purposes in the language, and cannot be used for any other purpose such as naming variables or functions. Since keywords are predefined, they help structure the language syntax and define its control flow, among other functionalities . It is crucial to note that keywords are case-sensitive, necessitating correct casing for their intended use. Python provides the help() function in platforms like Jupyter Notebook to explain keyword usage, allowing users to quickly reference their functionalities .

Python takes user input using the input() function, which always returns data as a string. This is important to note because if numerical calculations are intended, the input must be explicitly converted to a numeric type, such as an integer or a float, using type casting functions like int() or float(). An example is the addition of two numbers, where inputs are first converted into integers before performing arithmetic addition, ensuring that operations are performed with the correct data type.

The input() function in Python returns user input as a string by default, which may contradict initial user expectations when handling numeric data. Users expecting direct numeric input must explicitly convert input to numeric types using type casting functions like int() or float() before performing arithmetic operations to avoid type errors . For example, when users input numbers intended for addition, they must convert these input strings to integers to perform arithmetic, ensuring the code processes numerical data correctly and preventing unexpected runtime errors due to incorrect data types.

In Python, multiple independent statements can be placed on a single line using a semicolon (;) to separate each statement . This allows for concise expression of logic and can be useful in reducing code length, especially in scripts or interactive environments. However, while it offers a compact syntax, it can also lead to reduced readability and maintainability of code by making it harder to visually parse and debug, as multiple actions occur within a seemingly singular expression line. Thus, its use is generally discouraged in favor of clarity and simplicity, adhering to Python's philosophy of readable and maintainable code.

The print() function in Python offers several flexible options through different parameters. By default, arguments in print() are separated by space, but the 'sep' parameter can change this default separator to any specified character or string . Additionally, the 'end' parameter alters the default behavior of appending a newline character at the end of its output. For instance, setting 'end' to an empty string allows consecutive print statements to output on the same line instead of starting on a new line . These functionalities enhance control over how output is formatted and displayed.

The help() function in Jupyter Notebook provides users with quick access to detailed documentation about Python keywords and functions directly within their coding environment. By invoking help("keyword") or help(function_name), users receive definitions, syntax explanations, and usage examples, enhancing their understanding of complex functionalities on-the-fly . This feature is particularly useful for beginners learning the language, allowing for a deeper exploration of Python's syntax and libraries without leaving the interface, thereby facilitating a smoother learning curve and immediate application of knowledge in code writing.

You might also like