Parts of Python Programming
Parts of Python Programming
Python code tends to be short and when compared to compile languages like C and C++
that executes programs slower. Its user-friendliness makes it a popular language for
developers working with machine learning algorithms in low-code no-code (LCNC)
software applications.
Python is developed under an OSI-approved open source license, making it freely usable
and distributable, even for commercial use. Python's license is administered by the Python
Software Foundation. Open source software plays a very important role in our daily life.
Some of the most popular open source software is Android, Firefox, Linux, WordPress,
Python and others.
Python has a simple syntax and is known for having a large community that actively
contributes to a growing selection of software modules and libraries. Python’s initial
development was spearheaded by Guido van Rossum in the late 1980s. Today, Python is
managed by the Python Software Foundation.
The history of the Python programming language dates back to the late 1980s. Python was
developed in the late 1980s and its implementation was started in December 1989 by
Guido van Rossum, at the National Research Institute for Mathematics and Computer
Science in the Netherlands.
Python is derived from many other languages, including ABC, Modula-3, C, C++,
Algol-68, SmallTalk, and Unix shell and other scripting languages.
Python was developed as a successor to the ABC programming language.
Python labelled version was first published in February 1991 whereas, Python 1.0 was
launched in 1994. In 2000, Python 2.0 was released. Python 3.0 was released in 2008. It is
commonly known as “Py3K”.
Python is copyrighted. Like Perl, Python source code is now available under the GNU
General Public License (GPL).
Python is now maintained by a core development team at the institute, although Guido van
Rossum still holds a vital role in directing its progress.
Python Features: Python has become popular over the years. Python's popularity is due
to many factors. Some of the important features of Python Programming are:
Python is a simple programming language, means that Python has few keywords,
simple structure and clearly defined syntax.
When compared with other languages, we can write programs with very less
number of lines in Python. Hence more readability and simplicity in the Python
code.
The indentation is used instead of flower brackets in Python which makes it very
easy to read Python code.
2. Interpreted Language:
Note: Bytecode is a computer object code that an interpreter converts into binary
machine code so it can be read by a computer's hardware processor. The interpreter is
typically implemented as a virtual machine (VM) that translates the bytecode for the
target platform.
Platform independence refers to writing program once and can be run in any
platforms. It follows "Write Once Run Any Where" concept.
Example: If we write a Python program on Windows operating system then we
can run the same code in Linux or any other operating system without any
changes. This is because the Python code first is converted to an intermediate
form known as "Bytecode" and then it is executed.
6. High Level Language:
Python is extremely large with a diverse set of packages and modules. If the code
of some functionality is already present in these modules and packages, the
developers need not rewrite them from scratch saving both time and effort on the
developers end.
Python offers various libraries for creating graphical user interface for any
application.
The toolkits like wxPython or JPython allows for easy and fast development of
GUI.
Now a days almost every application need a database and Python Database API
(DB-API) that provides an interface to almost most of the major commercial
databases.
12. Procedure Oriented Programming:
Python is one of the few programming language that supports both object oriented
programming as well as a procedure oriented programming and hence it is called as
multi paradigm programming language.
Procedure oriented programming aims at creating various function or procedures to
solve specific task or set of task and aggregate them together in one piece of code.
A program can call the function as and when required. It purely depends on a
programmer whether to choose a procedure oriented programming or object
oriented programming style.
Python is one of the few languages that are capable of supporting exception
handling to a great extent which makes it a developer and programmer’s favourite
language.
14. Robust:
Robust means strong. Python's ability to work well with exceptions and exception
handling as well as its ease of use and comprehension has reduced the error rate in
the code. This makes the language very reliable and robust language to work with.
The Python source code goes through the following to generate an executable code
Step 1: The Python compiler reads a Python source code or instruction in the code editor.
In this first stage, the execution of the code starts.
Step 2: After writing Python code it is then saved as a .py file in our system. In this, there
are instructions written by a Python script for the system.
Step 3: In this the compilation stage comes in which source code is converted into a byte
code. Python compiler also checks the syntax error in this step and generates a .pyc file.
Step 4: Bytecode that is .pyc file is then sent to the Python Virtual Machine(PVM) which
is the Python interpreter. PVM converts the Python bytecode into machine-executable
code and in this interpreter reads and executes the given file line by line. If an error occurs
during this interpretation then the conversion is halted with an error message.
Step 5: Within the PVM the bytecode is converted into machine code that is the binary
language consisting of 0’s and 1’s. This binary language is only understandable by the
CPU of the system as it is highly optimized for the machine code.
Step 6: In the last step, the final execution occurs where the CPU executes the machine
code and the final desired output will come as according to the program.
Compiler Interpreter
The compiler is faster, as conversion The interpreter runs slower as the execution
occurs before the program executes. occurs simultaneously.
Errors are detected during the compilation Errors are identified and reported during the
phase and displayed before the execution given actual runtime.
of a program.
Compile code needs to be recompiled to Interpreted code is more portable as it can
run on different machines. run on any machine with the appropriate
interpreter.
It requires more memory to translate the It requires less memory than compiled ones.
whole source code at once.
Debugging is more complex due to batch Debugging is easier due to the line-by-line
processing of the code. execution of a code.
Applications of Python:
Python is known for its general-purpose nature that makes it applicable in almost every
domain of software development. Python makes its presence in every emerging field. It is
the fastest-growing programming language and can develop any application.
Some of the applications of Python are:
Web Development
Game Development
Machine Learning and Artificial Intelligence
Data Science and Data Visualization
Desktop GUI
Software Development
Operating Systems
Network Programming
Embedded Software
Web Scraping Applications
Business Applications
Language Development
Audio and Video Applications
Robotics
Console - based application
Differences between C and Python
C Python
C is a general-purpose, procedural Python is an interpreted, high-level,
computer programming language. general-purpose programming language.
Compiled programs execute faster as Interpreted programs execute slower as
compared to interpreted programs. compared to compiled programs.
Program syntax is harder than Python. It is easier to write a code in Python as the
number of lines is less comparatively.
In C, the type of a variable must be There is no need to declare the type of
declared when it is created, and only variable. A given variable can be stuck on
values of that type must be assigned to it. values of different types at different times
during the program execution
In C, error debugging is difficult as it is a Error debugging is simple. This means it
compiler dependent language. This means takes only one in instruction at a time and
that it takes the entire source code, compiles and executes simultaneously.
compiles it and then shows all the errors. Errors are shown instantly and the
execution is stopped, at that instruction.
C does not support function renaming Supports function renaming mechanism i.e,
mechanism. This means the same function the same function can be used by two
cannot be used by two different names. different names.
The syntax of a C program is harder than Syntax of Python programs is easy to learn,
Python. write and read.
C is generally used for hardware related Python is a General-Purpose programming
applications. language.
Platform Dependent Platform Independent
Installing Python
Installing and using Python on Windows Operating System is very simple. The installation
procedure involves the following steps:
Step 1 - Select Version of Python to Install
Python has various versions available with differences between the syntax and
working of different versions of the language. We need to choose the version which
we want to use or need. There are different versions of Python 2 and Python 3
available.
Step 2 − Download Python Executable Installer
On the web browser, in the official site of Python (www.Python.org), move to the
Download for Windows section.
All the available versions of Python will be listed. Select the version required by
you and click on Download. Let suppose, we chose the Python 3.9.1 version.
On clicking download, various available executable installers shall be visible with
different operating system specifications. Choose the installer which suits your
system operating system and download the instlaller. Let suppose, we select the
Windows installer(64 bits).
Step 3 − Run Executable Installer
We downloaded the Python 3.9.1 Windows 64 bit installer.
Run the installer. Make sure to select both the checkboxes at the bottom and then
click Install New.
The installation process will take few minutes to complete and once the
installation is successful, the following screen is displayed.
Step 4 − Verify Python is installed on Windows
To ensure if Python is successfully installed on your system.
Follow the given steps:
Open the command prompt.
Type ‘Python’ and press enter.
The version of the Python which you have installed will be displayed if the
Python is successfully installed on your windows.
Step 5 − Verify Pip was installed
Pip (Preferred Installer Program – used to install packages) is a powerful
package management system for Python software packages. Thus, make sure
that you have it installed.
To verify if pip was installed, follow the given steps −
Open the command prompt.
Enter pip –V to check if pip was installed.
We have successfully installed Python and pip on our Windows system.
In the Python programming language, there are two ways in which we can run our
code:
1. Interactive mode
2. Script mode
1. Interactive Mode:
In the interactive mode as we enter a command and press enter, the very next step
we get the output.
The output of the code in the interactive mode is influenced by the last command we
give.
Interactive mode is very convenient for writing very short lines of code.
It is not user friendly way to write long code.
In Python it is also known as REPL which stands for Read Evaluate Print Loop.
The read function reads the input from the user and stores it in memory.
Eval function evaluates the input to get the desired output.
Print function outputs the evaluated result.
The loop function executes the loop during the execution of the entire program and
terminates when our program ends.
This mode is very suitable for beginners in programming as it helps them evaluate
their code line by line and understand the execution of code well.
Working in the interactive mode is convenient for testing a single line of code for
instant execution. but in the interactive mode, we cannot save the statements for
future use and we have to retype the statements to run them again.
To close the interactive session we can type quit() or exit().
Interactive mode using Command Prompt
In order to run our program in the interactive mode, we can use command prompt in
windows, terminal in Linux, and macOS.
Example:
To run Python in command prompt type “Python”. Then simply type the Python statement
on >>> prompt. As we type and press enter we can see the output in the very next line.
2. Script Mode: In the script mode, a Python program can be written in a file. This
file can then be saved and executed using the command prompt. We can view the
code at any time by opening the file and editing becomes quite easy as we can open
and view the entire code as many times as we want. Script mode is very suitable for
writing long pieces of code. It is much preferred over interactive mode by experts in
the program. The file made in the script mode is by default saved in the Python
installation folder and the extension to save a Python file is “.py”.
Execution of Python code in script mode
In order to run a code in script mode follow the following steps.
Step 1: Make a file using a text editor.
Step 2: After writing the code save the file using “.py” extension.
Step 3: Now open the command prompt and command directory to the one where your
file is stored.
Step 4: Type Python “filename.py” and press enter.
Step 5: You will see the output on your command prompt.
Executing a Python Program Script
We have to execute a Python program script in order to get the output of the program, and
we have two ways for it.
1. Executing using command prompt terminal
Step 1: Open the command prompt and go to the directory where the Python script
file is saved.
Step2: Type Python followed by the file name. When we press enter key, Python
will start executing the script file in the command prompt terminal. We can see the
output as shown below:
Python Tokens:
A token is the smallest individual unit in a Python program. The different types of
tokens in Python are:
Continue This keyword is used to take the control back to the loop.
Output: 3
Note:
The execution of a statement changes state
Execution of a statement may or may not produces or displays a result value, it only
does whatever the statement says.
VARIABLES: Variable is a name given to hold any type of data which the program can
use to assign and modify during the course of execution. In Python, there is no need to
declare a variable explicitly by specifying whether the variable is an integer or a float or
any other type. To define a new variable in Python, we simply assign a value to a name. If
a need for variable arises you need to think of a variable name based on the rules
mentioned in the following subsection and use it in the program.
Legal Variable Names:
Rules for creating legal variable names in Python.
Variable names can consist of any number of letters, underscores and digits.
Variable should not start with a number.
Python Keywords are not allowed as variable names.
Variable names are case-sensitive. For example, computer and Computer are
different variables.
The guidelines while naming a variable are, as having a consistent naming convention
helps in avoiding confusion and can reduce programming errors.
• Python variables use lowercase letters with words separated by underscores as
necessary to improve readability, like this whats_up, how_are_you. Although this is not
strictly enforced, it is considered a best practice to adhere to this convention.
• Avoid naming a variable where the first character is an underscore. While this is legal in
Python, it can limit the interoperability of your code with applications built by using other
programming languages.
• Ensure variable names are descriptive and clear enough. This allows other programmers
to have an idea about what the variable is representing.
Assigning Values to Variables: The general format for assigning values to variables
is as follows:
variable_name = expression
The equal sign (=) also known as simple assignment operator is used to assign values to
variables. In the general format, the operand to the left of the = operator is the name of the
variable and the operand to the right of the = operator is the expression which can be a
value or any code snippet that results in a value. That value is stored in the variable on
the execution of the assignment statement. Assignment operator should not be confused
with the = used in algebra to denote equality. For example, enter the code shown below in
interactive mode and observe the results.
1. >>> number =100
2. >>> miles =1000.0
3. >>> name ="Python"
4. >>> number
100
5. >>> miles
1000.0
6. >>> name
'Python'
In ➀ integer type value is assigned to a variable number, in ➁ float type value has been
assigned to variable miles and in ➂ string type value is assigned to variable name. ➃, ➄
and ➅ prints the value assigned to these variables.
In Python, not only the value of a variable may change during program execution but also
the type of data that is assigned. You can assign an integer value to a variable, use it as an
integer for a while and then assign a string to the variable. A new assignment overrides
any previous assignments. For example,
1. >>> century = 100
2. >>> century
100
3. >>> century = "hundred"
4. >>> century
'hundred'
In ➀ an integer value is assigned to century variable and then in ➂ you are assigning a
string value to century variable. Different values are printed in each case as seen in ➁ and
➃. Python allows you to assign a single value to several variables simultaneously. For
example,
1. >>> a = b = c =1
2. >>> a
1
3. >>> b
1
4. >>> c
1
An integer value is assigned to variables a, b and c simultaneously ➀. Values for each of
these variables are displayed as shown in ➁, ➂ and ➃.
3. Operators: Operators are symbols, such as +, –, =, >, and <, that perform certain
mathematical or logical operation to manipulate data values and produce a result
based on some rules. An operator manipulates the data values called operands.
Consider the expression,
>>> 4 + 6
where 4 and 6 are operands and + is the operator.
Python language supports a wide range of operators. They are
1. Arithmetic Operators
2. Assignment Operators
3. Comparison Operators
4. Logical Operators
5. Bitwise Operators
1. Arithmetic Operators: Arithmetic operators are used to execute arithmetic operations
such as addition, subtraction, division, multiplication etc. The following table shows all
the arithmetic operators.
For example,
1. >>> 10+35
45
2. >>> −10+35
25
3. >>> 4*2
8
4. >>> 4**2
16
1. + Addition operator Adds two operands, producing their sum.
Eg: p + q = 5
2. − Subtraction operator Subtracts the two operands, producing their difference.
Eg: p – q = −1
3.* Multiplication operator Produces the product of the operands.
Eg: p * q = 6
4. / Division operator Produces the quotient of its operands where the
left operand is the dividend and the right operand is the divisor.
Eg: q / p = 1.5
5. % Modulus operator Divides left hand operand by right hand operand
and returns a remainder.
Eg: q % p = 1
6. ** Exponent operator Performs exponential (power) calculation on
operators.
Eg: p**q = 8
7. // Floor division operator Returns the integral part of the quotient.
Eg: 9//2 = 4 and 9.0//2.0 = 4.0
Note: The value of p is 2 and q is 3.
For example,
1. >>> 10+35
45
2. >>> −10+35
25
3. >>> 4*2
8
4. >>> 4**2
16
5. >>> 45/10
4.5
6. >>> 45//10.0
4.0
7. >>> 2025%10
5
8. >>> 2025//10
202
Above code illustrates various arithmetic operations ➀–➇.
2.Assignment Operators: Assignment operators are used for assigning the values
generated after evaluating the right operand to the left operand. Assignment operation
always works from right to left.
Assignment operators are either simple assignment operator or compound assignment
operators.
Simple assignment is done with the equal sign (=) and simply assigns the value of its
right operand to the variable on the left. For example,
1. >>> x = 5
2. >>> x = x + 1
3. >>> x
6
In ➀ you assign an integer value of 5 to variable x. In ➁ an integer value of 1 is added to
the variable x on the right side and the value 6 after the evaluation is assigned to the
variable x. The latest value stored in variable x is displayed in ➂Compound assignment
operators support shorthand notation for avoiding the repetition of the left-side variable on
the right side. Compound assignment operators combine assignment operator with another
operator with = being placed at the end of the original operator.
For example, the statement
>>> x = x + 1
can be written in a compactly form as shown below.
>>> x += 1
If you try to update a variable which doesn’t contain any value, you get an error.
1. >>> z = z + 1
NameError: name 'z' is not defined
Trying to update variable z which doesn’t contain any value results in an error because
Python evaluates the right side before it assigns a value to z ➀.
1. >>> z = 0
2. >>> x = z + 1
Before you can update a variable ➁, you have to assign a value to it ➀.
List of Assignment Operators
1. = Assignment Assigns values from right side operands to left side operand.
z = p + q assigns value of p + q to z
2. += Addition Assignment Adds the value of right operand to the left operand and
assigns the result to left operand.
z += p is equivalent to z = z + p
3. −= Subtraction Assignment Subtracts the value of right operand from the left operand
and assigns the result to left operand.
z −= p is equivalent to z = z – p
4. *= Multiplication Assignment Multiplies the value of right operand with the left
operand and assigns the result to left operand.
z *= p is equivalent to z = z * p
5. /= Division Assignment Divides the value of right operand with the left operand and
assigns the result to left operand.
z /= p is equivalent to z = z / p
6.**= Exponentiation Assignment Evaluates to the result of raising the first operand to
the power of the second operand.
z**= p is equivalent to z = z ** p
7. //= Floor Division Assignment Produces the integral part of the quotient of its
operands where the left operand is the dividend and the right operand is the divisor.
z //= p is equivalent to z = z // p
8. %= Remainder Assignment Computes the remainder after division and assigns the
value to the left operand.
z %= p is equivalent to z = z % p
For example,
1. >>> p = 10
2. >>> q = 12
3. >>> q += p
4. >>> q
22
5. >>> q *= p
6. >>> q
220
7. >>> q /= p
8. >>> q
22.0
9. >>> q %= p
10. >>> q
2.0
11. >>> q **= p
12. >>> q
1024.0
13. >>> q //= p
14. >>> q
102.0
Above code illustrates various assignment operations ➀–14 .
3.Comparison Operators: When the values of two operands are to be compared then
comparison operators are used. The output of these comparison operators is always a
Boolean value, either True or False. The operands can be Numbers or Strings or Boolean
values. Strings are compared letter by letter using their ASCII values, thus, “P” is less than
“Q”, and “Aston” is greater than “Asher”.
List of Comparison Operators
1.== Equal to If the values of two operands are equal, then the condition becomes True.
Eg: (p == q) is not True.
2.!= Not Equal to If values of two operands are not equal, then the condition becomes
True.
Eg: (p != q) is True
3.> Greater than If the value of left operand is greater than the value of right operand, then
condition becomes True.
Eg: (p > q) is not True.
4. < Lesser than If the value of left operand is less than the value of right operand, then
condition becomes True.
Eg: (p < q) is True.
5. >= Greater than or equal to If the value of left operand is greater than or equal to the
value of right operand, then condition becomes True.
Eg: (p >= q) is not True.
6. <= Lesser than or equal to If the value of left operand is less than or equal to the value
of right operand, then condition becomes True.
Eg: (p <= q) is True.
Note: The value of p is 10 and q is 20.
For example,
1. >>>10 == 12
False
2. >>>10 != 12
True
3. >>>10 < 12
True
4. >>>10 > 12
False
5. >>>10 <= 12
True
6. >>>10 >= 12
False
7. >>> "P" < "Q"
True
8. >>> "Aston" > "Asher"
True
9. >>> True == True
True
Above code illustrates various comparison operations ➀–➈.
4. Logical Operators: The logical operators are used for comparing or negating the
logical values of their operands and to return the resulting logical value. The values of the
operands on which the logical operators operate evaluate to either True or False. The result
of the logical operator is always a Boolean value, True or False.
List of Logical Operators
1. and Logical AND Performs AND operation and the result is True when both operands
are True
Eg: p and q results in False
2. or Logical OR Performs OR operation and the result is True when any one of both
operand is True
Eg: p or q results in True
3. not Logical NOT Reverses the operand state
Eg: not p results in False
Note: The Boolean value of p is True and q is False.
Boolean Logic Truth Table
P Q P and Q P or Q Not P
True True True True False
True False False True
False True False True True
False False False False
For example,
1. >>> True and False
False
2. >>> True or False
True
3. >>> not(True) and False
False
4. >>> not(True and False)
True
5. >>> (10 < 0) and (10 > 2)
False
6. >>> (10 < 0) or (10 > 2)
True
7. >>> not(10 < 0) or (10 > 2)
True
8. >>> not(10 < 0 or 10 > 2)
False
Above code illustrates various comparison operations ➀–➇.
For example,
1. >>> 1 > 2 and 9 > 6
False
2. >>> 3 > 2 or 8 < 4
True
In ➀ the expression 1 > 2 is evaluated to False. Since and operator is used in the statement
the expression is evaluated to False and the remaining expression 9 > 6 is not evaluated.
In ➁ the expression 3 > 2 is evaluated to True. As or operator is used in the statement the
expression is evaluated to True while the remaining expression 8 < 4 is ignored.
5. Bitwise Operators: Bitwise operators treat their operands as a sequence of bits (zeroes
and ones) and perform bit by bit operation.
For example, the decimal number ten has a binary representation of 1010. Bitwise
operators perform their operations on such binary representations, but they return standard
Python numerical values. TABLE below shows all the bitwise operators.
The Bitwise Truth table is shown below
The figure below shows examples for bitwise logical operations. The value of operand a is
60 and value of operand b is 13
Examples of bitwise logical operators.
The figure below shows how the expression 60 << 2 would be evaluated in a byte.
Data types specify the type of data like numbers and characters to be stored and
manipulated within a program. Basic data types of Python are:
• Numbers
• Boolean
• Strings
• None
1. Numbers: Integers, floating point numbers and complex numbers fall under Python
numbers category. They are defined as int, float and complex class in Python. Integers can
be of any length; it is only limited by the memory available. A floating point number is
accurate up to 15 decimal places. Integer and floating points are separated by decimal
points. 1 is an integer, 1.0 is floating point number. Complex numbers are written in the
form, x + yj, where x is the real part and y is the imaginary part.
2. Boolean: Booleans may not seem very useful at first, but they are essential when you
start using conditional statements. In fact, since a condition is really just a yes-or-no
question, the answer to that question is a Boolean value, either True or False. The Boolean
values, True and False are treated as reserved words.
3. Strings: A string consists of a sequence of one or more characters, which can include
letters, numbers, and other types of characters. A string can also contain spaces. You can
use single quotes or double quotes to represent strings and it is also called a string literal.
Multiline strings can be denoted using triple quotes, ''' or """. These are fixed values, not
variables that you literally provide in your script.
For example : -
1. >>> s = 'This is single quote string'
2. >>> s = "This is double quote string"
3. >>> s = '''This is
Multiline
string'''
4. >>> s = "a"
In ➀ a string is defined using single quotes, in ➁ a string is defined using double quotes
and a multiline string is defined in ➂, a single character is also treated as string ➃.
4. None: None is another special data type in Python. None is frequently used to represent
the absence of a value. For example:-
1. >>> money = None
None value is assigned to variable money ➀.
Indentation: In Python, Programs get structured through indentation. Usually, we expect
indentation from any program code, but in Python it is a requirement and not a matter of
style. This principle makes the code look cleaner and easier to understand and read. Any
statements written under another statement with the same indentation is interpreted to
belong to the same code block.
Figure representing Code blocks and Indentation in Python
If there is a next statement with less indentation to the left, then it just means the end of the
previous code block. In other words, if a code block has to be deeply nested, then the
nested statements need to be indented further to the right. In the above diagram, Block 2
and Block 3 are nested under Block 1. Usually, four whitespaces are used for indentation
and are preferred over tabs. Incorrect indentation will result in IndentationError.
Comments: Comments are an important part of any program. A comment is a text that
describes what the program or a particular part of the program is trying to do and is
ignored by the Python interpreter. Comments are used to help you and other programmers
understand, maintain, and debug the program. Python uses two types of comments: single-
line comment and multiline comments.
1. Single Line Comment: In Python, use the hash (#) symbol to start writing a comment.
Hash (#) symbol makes all text following it on the same line into a comment. For example,
#This is single line Python comment
2. Multiline Comments: If the comment extends multiple lines, then one way of
commenting those lines is to use hash (#) symbol at the beginning of each line. For
example,
#This is
#multiline comments
#in Python
Another way of doing this is to use triple quotes, either ''' or """. These triple quotes are
generally used for multiline strings. However, they can be used as a multiline comment as
well.
For example,
'''This is
multiline comment
in Python using triple quotes'''
Reading Input: In Python, input() function is used to gather data from the user. The
syntax for input function is,
variable_name = input([prompt])
prompt is a string written inside the parenthesis that is printed on the screen. The prompt
statement gives an indication to the user of the value that needs to be entered through the
keyboard. When the user presses Enter key, the program resumes and input returns what
the user typed as a string. Even when the user inputs a number, it is treated as a string
which should be casted or converted to number explicitly using appropriate type casting
function.
1. >>> person = input("What is your name?")
2. What is your name? Carrey
3. >>> person
'Carrey'
➀ the input() function prints the prompt statement on the screen (in this case "What is
your name?") indicating the user that keyboard input is expected at that point and then it
waits for a line to be typed in. User types in his response in ➁. The input() function reads
the line from the user and converts the line into a string. As can be seen in ➂, the line
typed by the user is assigned to the person variable.
Print Output: The print() function allows a program to display text onto the console. The
print function will print everything as strings and anything that is not already a string is
automatically converted to its string representation. For example,
1. >>> print("Hello World!!")
Hello World!!
➀ prints the string Hello World!! onto the console. Notice that the string Hello World is
enclosed within double quotes inside the print() function.
Even though there are different ways to print values in Python, we discuss two major
string formats which are used inside the print() function to display the contents onto the
console as they are less error prone and results in cleaner code. They are
1. str.format()
2. f-strings
1. str.format( ): Use str.format() method if you need to insert the value of a variable,
expression or an object into another string and display it to the user as a single string. The
format() method returns a new string with inserted values. The format() method works for
all releases of Python 3.x. The syntax for format() method is,
str.format(p0, p1, ..., k0=v0, k1=v1, ...)
where p0, p1,... are called as positional arguments and, k0, k1,... are keyword arguments
with their assigned values of v0, v1,... respectively.
Positional arguments are a list of arguments that can be accessed with an index of
argument inside curly braces like {index}. Index value starts from zero.
Keyword arguments are a list of arguments of type keyword = value, that can be accessed
with the name of the argument inside curly braces like {keyword}.
Here, str is a mixture of text and curly braces of indexed or keyword types. The indexed or
keyword curly braces are replaced by their corresponding argument values and is
displayed as a single string to the user.
Output
Which country do you live in? India
I live in India
Program 2: Program to Demonstrate the Positional Change of Indexes of Arguments
a = 10
b = 20
print("The values of a is {0} and b is {1}".format(a, b))
print("The values of b is {1} and a is {0}".format(a, b))
Output
The values of a is 10 and b is 20
The values of b is 20 and a is 10