Structuring Python Programs
Last Updated :
13 Mar, 2023
In this article, you would come to know about proper structuring and formatting your python programs.
Python Statements In general, the interpreter reads and executes the statements line by line i.e sequentially. Though, there are some statements that can alter this behavior like conditional statements.
Mostly, python statements are written in such a format that one statement is only written in a single line. The interpreter considers the ‘new line character’ as the terminator of one instruction. But, writing multiple statements per line is also possible that you can find below.
Examples:
print ( 'Welcome to Geeks for Geeks' )
|
Output:
Welcome to Geeks for Geeks
x = [ 1 , 2 , 3 , 4 ]
print (x[ 1 : 3 ])
|
Multiple Statements per Line We can also write multiple statements per line, but it is not a good practice as it reduces the readability of the code. Try to avoid writing multiple statements in a single line. But, still you can write multiple lines by terminating one statement with the help of ‘;’. ‘;’ is used as the terminator of one statement in this case.
For Example, consider the following code.
a = 10 ; b = 20 ; c = b + a
print (a); print (b); print (c)
|
Line Continuation to avoid left and right scrolling
Some statements may become very long and may force you to scroll the screen left and right frequently. You can fit your code in such a way that you do not have to scroll here and there. Python allows you to write a single statement in multiple lines, also known as line continuation. Line continuation enhances readability as well.
# Bad Practice as width of this code is too much.
#code
x = 10
y = 20
z = 30
no_of_teachers = x
no_of_male_students = y
no_of_female_students = z
if (no_of_teachers == 10 and no_of_female_students == 30 and no_of_male_students == 20 and (x + y) == 30):
print('The course is valid')
# This could be done instead:
if (no_of_teachers == 10 and no_of_female_students == 30
and no_of_male_students == 20 and x + y == 30):
print('The course is valid')
Types of Line Continuation
In general, there are two types of line continuation
- Implicit Line Continuation
This is the most straightforward technique in writing a statement that spans multiple lines.
Any statement containing opening parentheses (‘(‘), brackets (‘[‘), or curly braces (‘{‘) is presumed to be incomplete until all matching parentheses, square brackets, and curly braces have been encountered. Until then, the statement can be implicitly continued across lines without raising an error.
Examples:
a = [
[ 1 , 2 , 3 ],
[ 3 , 4 , 5 ],
[ 5 , 6 , 7 ]
]
print (a)
|
Output:
[[1, 2, 3], [3, 4, 5], [5, 6, 7]]
person_1 = 18
person_2 = 20
person_3 = 12
if (
person_1 > = 18 and
person_2 > = 18 and
person_3 < 18
):
print ( '2 Persons should have ID Cards' )
|
Output:
2 Persons should have ID Cards
- Explicit Line Continuation
Explicit Line joining is used mostly when implicit line joining is not applicable. In this method, you have to use a character that helps the interpreter to understand that the particular statement is spanning more than one lines.
Backslash (\) is used to indicate that a statement spans more than one line. The point is to be noted that ” must be the last character in that line, even white-space is not allowed.
See the following example for clarification
x = \
1 + 2 \
+ 5 + 6 \
+ 10
print (x)
|
Comments in Python
Writing comments in the code are very important and they help in code readability and also tell more about the code. It helps you to write details against a statement or a chunk of code. Interpreter ignores the comments and does not count them in commands. In this section, we’ll learn how to write comments in Python.
Symbols used for writing comments include Hash (#) or Triple Double Quotation marks(“””). Hash is used in writing single line comments that do not span multiple lines. Triple Quotation Marks are used to write multiple line comments. Three triple quotation marks to start the comment and again three quotation marks to end the comment.
Consider the following examples:
a = 'How old are you?'
print (a)
|
Note Do note that Hash (#) inside a string does not make it a comment. Consider the following example for demonstration.
a = 'This is # not a comment #'
print (a)
|
White spaces
The most common whitespace characters are the following:
Character |
ASCII Code |
Literal Expression |
Space |
32 (0x20) |
‘ ‘ |
tab |
9 (0x9) |
‘\t’ |
newline |
10 (0xA) |
‘\n’ |
* You can always refer to ASCII Table by clicking here.
Whitespace is mostly ignored, and mostly not required, by the Python interpreter. When it is clear where one token ends and the next one starts, whitespace can be omitted. This is usually the case when special non-alphanumeric characters are involved.
Examples:
x = 10
flag = (x = = 10 ) and (x< 12 )
print (flag)
|
Whitespaces are necessary in separating the keywords from the variables or other keywords. Consider the following example.
x = [ 1 , 2 , 3 ]
y = 2
a = y in x
print (a)
|
Whitespaces as Indentation
Python’s syntax is quite easy, but still you have to take some care in writing the code. Indentation is used in writing python codes.
Whitespaces before a statement have significant role and are used in indentation. Whitespace before a statement can have a different meaning. Let’s try an example.
print ( 'foo' )
print ( 'foo' )
|
Leading whitespaces are used to determine the grouping of the statements like in loops or control structures etc.
Example:
x = 10
while (x ! = 0 ):
if (x > 5 ):
print ( 'x > 5' )
else :
print ( 'x < 5' )
x - = 2
|
Output:
x > 5
x > 5
x > 5
x < 5
x < 5
Similar Reads
Python Programs
Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples. The below Python section contains a wide collection of Python programming examples. These Python c
11 min read
Python Data Structures Practice Problems
Python Data Structures Practice Problems page covers essential structures, from lists and dictionaries to advanced ones like sets, heaps, and deques. These exercises help build a strong foundation for managing data efficiently and solving real-world programming challenges. Data Structures OverviewLi
1 min read
Output of Python programs | Set 8
Prerequisite - Lists in Python Predict the output of the following Python programs. Program 1 [GFGTABS] Python list = [1, 2, 3, None, (1, 2, 3, 4, 5), ['Geeks', 'for', 'Geeks']] print len(list) [/GFGTABS]Output: 6Explanation: The beauty of python list datatype is that within
3 min read
Output of Python programs | Set 7
Prerequisite - Strings in Python Predict the output of the following Python programs. These question set will make you conversant with String Concepts in Python programming language. Program 1[GFGTABS] Python var1 = 'Hello Geeks!' var2 = "GeeksforGeeks" print "var1[0]: ",
3 min read
Output of Python Program | Set 1
Predict the output of following python programs: Program 1: [GFGTABS] Python r = lambda q: q * 2 s = lambda q: q * 3 x = 2 x = r(x) x = s(x) x = r(x) print (x) [/GFGTABS]Output: 24Explanation : In the above program r and s are lambda functions or anonymous functions and q is the argument to both of
3 min read
Python String Input Output
In Python, input and output operations are fundamental for interacting with users and displaying results. The input() function is used to gather input from the user and the print() function is used to display output. Input operations in PythonPythonâs input() function allows us to get data from the
3 min read
Output of Python program | Set 5
Predict the output of the following programs: Program 1: [GFGTABS] Python def gfgFunction(): "Geeksforgeeks is cool website for boosting up technical skills" return 1 print (gfgFunction.__doc__[17:21]) [/GFGTABS]Output: coolExplanation: There is a docstring defined for this method,
3 min read
Understanding the Execution of Python Program
This article aims at providing a detailed insight into the execution of the Python program. Let's consider the below example. Example: C/C++ Code a = 10 b = 10 print("Sum ", (a+b)) Output: Sum 20 Suppose the above python program is saved as first.py. Here first is the name and .py is the e
2 min read
Python List Creation Programs
Python provides multiple ways to create lists based on different requirements, such as generating lists of numbers, creating nested lists, forming lists of tuples or dictionaries, and more. This article covers various ways to create lists efficiently, including: Generating lists of numbers, strings,
2 min read
Python Tutorial | Learn Python Programming Language
Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. Python is: A high-level language, used in web development, data science, automat
10 min read