Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Python Programming: Ii B.Tech (Cse) - I Semester (R19)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 22

2020-2021

Python Programming
II B.TECH (CSE) – I SEMESTER [R19]

Dr. SAMEENA
RAMACHANDRA COLLEGE OF ENGINEERING
2020-2021
Python Programming 2020-
2021

Unit-I: Introduction to Python, Program Development Cycle, Input, Processing, and Output,
Displaying Output with the Print Function, Comments, Variables, Reading Input from the Keyboard,
Performing Calculations, Operators. Type conversions, Expressions, More about Data Output. Data
Types, and Expression: Strings Assignment, and Comment, Numeric Data Types and Character Sets,
Using functions and Modules. Decision Structures and Boolean Logic: if, if-else, if-elif-else
Statements, Nested Decision Structures, Comparing Strings, Logical Operators, Boolean Variables.
Repetition Structures: Introduction, while loop, for loop, Calculating a Running Total, Input
Validation Loops, Nested Loops.

INTRODUCTION TO PYTHON
Definition: Python is a high-level, interpreted, interactive and object-oriented scripting language.
Python is designed to be highly readable.
It uses English keywords frequently where as other languages use punctuation, and it has fewer
syntactical constructions than other languages.
Python is Interpreted: Python is processed at runtime by the interpreter. You do not need to
compile your program before executing it.
Python is Interactive: You can actually sit at a Python prompt and interact with the interpreter
directly to write your programs.
Python is Object-Oriented: Python supports Object-Oriented style or technique of programming
that encapsulates code within objects.
Python is a Beginner's Language: Python is a great language for the beginner-level programmers
and supports the development of a wide range of applications from simple text processing to WWW
browsers to games.
History of Python
Python was developed by Guido van Rossum in the late 80s and early 90s 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,
Unix shell, and other scripting languages.
Python was named after "Monty Python's Flying Circus" (a BBC comedy series from the 70s).
Python 1.0 was released on 20 February, 1991.
Python 2.0 was released on 16 October 2000 and had many major new features, including a cycle
detecting garbage collector and support for Unicode.
Python 3.0 (which early in its development was commonly referred to as Python 3000 or py3k), a
major, backwards-incompatible release, was released on 3 December 2008 after a long period of

Ramachandra College of Engineering | $@MEEN@ Page 1


Python Programming 2020-
2021

testing. Many of its major features have been back ported to the backwards-compatible Python 2.6.x
and 2.7.x version series.
In January 2017 Google announced work on a Python 2.7 to go transcompiler, which The Register
speculated was in response to Python 2.7's planned end-of-life.
Python Features:
Easy-to-learn: Python has few keywords, simple structure, and a clearly defined syntax. This allows
the student to pick up the language quickly.
Easy-to-read: Python code is more clearly defined and visible to the eyes.
Easy-to-maintain: Python's source code is fairly easy-to-maintain.
A broad standard library: Python's bulk of the library is very portable and crossplatform compatible
on UNIX, Windows, and Macintosh.
Interactive Mode: Python has support for an interactive mode which allows interactive testing and
debugging of snippets of code.
Portable: Python can run on a wide variety of hardware platforms and has the same interface on all
platforms.
Extendable: You can add low-level modules to the Python interpreter. These modules enable
programmers to add to or customize their tools to be more efficient.
Databases: Python provides interfaces to all major commercial databases.
GUI Programming: Python supports GUI applications that can be created and ported to many system
calls, libraries, and windows systems, such as Windows MFC, Macintosh, and the X Window system
of UNIX.
Scalable: Python provides a better structure and support for large programs than shell scripting.

BYTE CODE COMPILATION


Python first compiles your source code (the statements in your file) into a format known as byte
code. Compilation is simply a translation step, and byte code is a lower level, platform independent
representation of your source code. Roughly, Python translates each of your source statements into
a group of byte code instructions by decomposing them into individual steps. This byte code
translation is performed to speed execution —byte code can be run much more quickly than the
original source code statements in your text file.
The Python Virtual Machine: Once your program has been compiled to byte code (or the byte code
has been loaded from existing .pyc file), it is shipped off for execution to something generally known
as the python virtual machine (PVM).

Ramachandra College of Engineering | $@MEEN@ Page 2


Python Programming 2020-
2021

Applications of Python:
1. Systems Programming
2. GUIs
3. Internet Scripting
4. Component Integration
5. Database Programming
6. Rapid Prototyping
7. Numeric and Scientific Programming
What Are Python’s Technical Strengths?
1. It‘s Object-Oriented and Functional
2. It‘s Free
3. It‘s Portable
4. It‘s Powerful
5. It‘s Mixable
6. It‘s Relatively Easy to Use
7. It‘s Relatively Easy to Learn
PYTHON'S DEVELOPMENT CYCLE

Ramachandra College of Engineering | $@MEEN@ Page 3


Python Programming 2020-
2021

Python's development cycle is shorter compared to traditional development cycle. In Python, there
are no compile or link steps -- Python programs simply import modules at runtime and use the
objects they contain. Because of this, Python programs run immediately after changes are made.
And in cases where dynamic module reloading can be used, it's even possible to change and reload
parts of a running program without stopping it at all.

Python's very high-level nature means there's less for us to program and manage. C, C++ language
are too complex. But because Python is also a simple language, coding is intensely faster. For
example, its dynamic typing, built-in objects, and garbage collection eliminate much of the coding
required in lower-level languages such as C and C++. Since things like type declarations, memory
management, and common data structure implementations are all conspicuously absent, Python
programs are typically a fraction of the size of their C or C++ equivalents. There's less to write and
read, and thus less opportunity for coding errors. Python programs are easier to understand and
more closely reflect the actual problem they're intended to address. And Python's high-level nature
makes it easier to learn the language.
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.

Ramachandra College of Engineering | $@MEEN@ Page 4


Python Programming 2020-
2021

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

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 format() method uses its arguments to substitute an appropriate value for each format code in
the template.
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.

Ramachandra College of Engineering | $@MEEN@ Page 5


Python Programming 2020-
2021

f-strings
Formatted strings or f-strings were introduced in Python 3.6. A f-string is a string literal that is
prefixed with “f”. These strings may contain replacement fields, which are expressions enclosed
within curly braces {}. The expressions are replaced with their values. In the real world, it means that
you need to specify the name of the variable inside the curly braces to display its value. An f at the
beginning of the string tells Python to allow any currently valid variable names within the string.

Ramachandra College of Engineering | $@MEEN@ Page 6


Python Programming 2020-
2021

Output
Enter the radius of a circle 5
Area = 78.53750000000001 and Circumference = 31.415000000000003
Get input for radius from the user ➀ and ➁ to calculate the area of a circle using the formula
πr2 and ➂ circumference of a circle is calculated using the formula 2πr. Finally, ➃ print the results.
TYPE CONVERSIONS
You can explicitly cast, or convert, a variable from one type to another.
The int() Function
To explicitly convert a float number or a string to an integer, cast the number using int() function.
Program to Demonstrate int() Casting Function
1. float_to_int = int(3.5)
2. string_to_int = int("1") #number treated as string
3. print(f"After Float to Integer Casting the result is {float_to_int}")
4. print(f"After String to Integer Casting the result is {string_to_int}")
Output
After Float to Integer Casting the result is 3
After String to Integer Casting the result is 1
1. >>>numerical_value = input("Enter a number")
Enter a number 9
2. >>> numerical_value '9'

Ramachandra College of Engineering | $@MEEN@ Page 7


Python Programming 2020-
2021

3. >>> numerical_value = int(input("Enter a number"))


Enter a number 9
4. >>> numerical_value 9
➀–➁ User enters a value of 9 which gets assigned to variable numerical_value and the value is
treated as string type. In order to assign an integer value to the variable, you have to enclose the
input() function within the int() function which converts the input string type to integer type ➂–➃.

The float() Function


The float() function returns a floating point number constructed from a number or string.
Program 2.7: Program to Demonstrate float() Casting Function
1. int_to_float = float(4)
2. string_to_float = float("1") #number treated as string
3. print(f"After Integer to Float Casting the result is {int_to_float}")
4. print(f"After String to Float Casting the result is {string_to_float}")
Output
After Integer to Float Casting the result is 4.0
After String to Float Casting the result is 1.0
Convert integer and string values to float ➀–➁ and display the result ➂–➃.
The str() Function
The str() function returns a string which is fairly human readable.
Program to Demonstrate str() Casting Function
1. int_to_string = str(8)
2. float_to_string = str(3.5)
3. print(f"After Integer to String Casting the result is {int_to_string}")
4. print(f"After Float to String Casting the result is {float_to_string}")
Output
After Integer to String Casting the result is 8
After Float to String Casting the result is 3.5
Here, integer and float values are converted ➀–➁ to string using str() function and results are
displayed ➂–➃.
The chr() Function
Convert an integer to a string of one character whose ASCII code is same as the integer using chr()
function. The integer value should be in the range of 0–255.

Ramachandra College of Engineering | $@MEEN@ Page 8


Python Programming 2020-
2021

Program to Demonstrate chr() Casting Function


1. ascii_to_char = chr(100)
2. print(f'Equivalent Character for ASCII value of 100 is {ascii_to_char}')
Output
Equivalent Character for ASCII value of 100 is d
An integer value corresponding to an ASCII code is converted ➀ to the character and printed ➁.
The complex() Function
Use complex() function to print a complex number with the value real + imag*j or convert a string or
number to a complex number.
Program to Demonstrate complex() Casting Function
1. complex_with_string = complex("1")
2. complex_with_number = complex(5, 8)
3. print(f"Result after using string in real part {complex_with_string}")
4. print(f"Result after using numbers in real and imaginary part {complex_with_ number}")
Output
Result after using string in real part (1+0j)
Result after using numbers in real and imaginary part (5+8j)
The first argument is a string ➀. Hence you are not allowed to specify the second argument. In ➁
the first argument is an integer type, so you can specify the second argument which is also an
integer. Results are printed out in ➂ and ➃.

The ord() function


It returns an integer representing Unicode code point for the given Unicode character.
Program to Demonstrate ord() Casting Function
1. unicode_for_integer = ord('4')
2. unicode_for_alphabet = ord("Z")
3. unicode_for_character = ord("#")
4. print(f"Unicode code point for integer value of 4 is {unicode_for_integer}")
5. print(f"Unicode code point for alphabet 'A' is {unicode_for_alphabet}")
6. print(f"Unicode code point for character '$' is {unicode_for_character}")
Output
Unicode code point for integer value of 4 is 52
Unicode code point for alphabet 'A' is 90

Ramachandra College of Engineering | $@MEEN@ Page 9


Python Programming 2020-
2021

Unicode code point for character '$' is 35


The ord() function converts an integer ➀, alphabet ➁ and a character ➂ to its equivalent Unicode
code point integer value and prints the result ➃–➅.
The hex() Function
Convert an integer number (of any size) to a lowercase hexadecimal string prefixed with “0x” using
hex() function.
Program to Demonstrate hex() Casting Function
1. int_to_hex = hex(255)
2. print(f"After Integer to Hex Casting the result is {int_to_hex}")
Output
After Integer to Hex Casting the result is 0xff
Integer value of 255 is converted to equivalent hex string of 0xff ➀ and result is printed as shown in
➁.
The oct() Function
Convert an integer number (of any size) to an octal string prefixed with “0o” using oct() function.
Program to Demonstrate oct() Casting Function
1. int_to_oct = oct(255)
2. print(f"After Integer to Hex Casting the result is {int_to_oct}")
Output
After Integer to Hex Casting the result is 0o377
Integer value of 255 is converted to equivalent oct string of 0o37 ➀ and result is printed as in ➁.
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.
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
Multiline Comments

Ramachandra College of Engineering | $@MEEN@ Page 10


Python Programming 2020-
2021

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'''
VARIABLES
Variable is a named placeholder 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
Follow the below-mentioned 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. Also, follow these guidelines while
naming a variable, 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

Ramachandra College of Engineering | $@MEEN@ Page 11


Python Programming 2020-
2021

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.
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'
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

STRINGS, ASSIGNMENT, AND COMMENTS


i) Data Types:
In programming, a data type consists of a set of values and a set of operations that can be
performed on those values. A literal is the way a value of a data type looks to a programmer. The
programmer can use a literal in a program to mention a data value. When the Python interpreter
evaluates a literal, the value it returns is simply that literal.
Following Table shows example literals of several Python data types.

Ramachandra College of Engineering | $@MEEN@ Page 12


Python Programming 2020-
2021

The first two data types listed in Table, int and float, are called numeric data types, because they
represent numbers. Character strings are often referred to simply as strings.

ii) String Literals:


In Python, a string literal is a sequence of characters enclosed in single or double quotation marks.
The following Python shell shows some example strings:
>>> ‘ Hello there!’
‘Hello there!’
>>>”Hello there!”
‘Hello there!’
>>>’’
‘’
>>>””
“”
The last two string literals (' ' and “ ”) represent the empty string.
Note:
The empty string is different from a string that contains a single blank space character, “ “.
Double-quoted strings are handy for composing strings that contain single quotation marks or
apostrophes.
Example:
>>>print(“I'm using a single quote!”)
I'm using a single quote!
If you want to output the string as a single line, you have to include the entire string literal in the
same line of code. Otherwise, a syntax error will occur.
To output a paragraph of text that contains several lines, you could use a separate print function call
for each line. However, it is more convenient to enclose the entire string literal, line breaks and all,
within three consecutive quotation marks (either single or double) for printing.
>>>print(“””This very long sentence extends all the way
to the next line.”””)

Ramachandra College of Engineering | $@MEEN@ Page 13


Python Programming 2020-
2021

This very long sentence extends all the way


to the next line

iii) Escape Sequences:


The newline character \n is called an escape sequence. Escape sequences are the way Python
expresses special characters, such as the tab, the newline, and the backspace (delete key), as literals.
Table lists some escape sequences in Python.

Because the backslash is used for escape sequences, it must be escaped to appear as a literal
character in a string. Thus, print(“\\”) would display a single \ character.

iv) String Concatenation:


You can join two or more strings to form a new string using the concatenation operator +.
Here is an example:

The * operator allows you to build a string by repeating another string a given number of times. The
left operand is a string, and the right operand is an integer.
For example: If you want the string “Python” to be preceded by 10 spaces, it would be easier to use
the * operator with 10 and one space.

V) Variables and the Assignment Statement:


A variable associates a name with a value, making it easy to remember and use the value later in a
program. We need to follow few rules when choosing names for your variables. For example, some

Ramachandra College of Engineering | $@MEEN@ Page 14


Python Programming 2020-
2021

names, such as if, def, and import, are reserved for other purposes and thus cannot be used for
variable names.
In general, a variable name must begin with either a letter or an underscore ( _), and can contain any
number of letters, digits, or other underscores.
Python variable names are case sensitive; thus, the variable WEIGHT is a different name from the
variable weight.
Python programmers typically use lowercase letters for variable names, but in the case of variable
names that consist of more than one word, it’s common to begin each word in the variable name
(except for the first one) with an uppercase letter. This makes the variable name easier to read.
For example, the name interestRate is slightly easier to read than the name interestrate.
Programmers use all uppercase letters for the names of variables that contain values that the
program never changes. Such variables are known as symbolic constants.
Examples of symbolic constants are TAX_RATE and STANDARD_DEDUCTION.
Variables receive their initial values and can be reset to new values with an assignment statement.
The form of an assignment statement is the following:
<variable_name>=<expression>
The Python interpreter first evaluates the expression on the right side of the assignment symbol and
then binds the variable name on the left side to this value. It is called defining or initializing the
variable.
Note that the = symbol means assignment, not equality.
After you initialize a variable, subsequent uses of the variable name in expressions are known as
variable references.
When the interpreter encounters a variable reference in any expression, it looks up the associated
value. If a name is not yet bound to a value when it is referenced, Python signals an error. The
following example shows some definitions of variables and their references:

The first two statements initialize the variables firstName and secondName to string values. The next
statement references these variables, concatenates the values referenced by the variables to build a
new string, and assigns the result to the variable fullName. The last line of code is a simple reference
to the variable fullName, which returns its value.

Ramachandra College of Engineering | $@MEEN@ Page 15


Python Programming 2020-
2021

Variables serve two important purposes in programs:


1. They help the programmer keep track of data that change over the course of time.
2. They also allow the programmer to refer to a complex piece of information with a simple
name.

Vi) Program Comments and Docstrings:


A comment is a piece of program text that the interpreter ignores but that provides useful
documentation to programmers. At the very least, the author of a program can include his or her
name and a brief statement about the purpose of the program at the beginning of the program file.
This type of comment, called a docstring, is a multi-line string.

In addition to docstrings, end-of-line comments can document a program. These comments begin
with the # symbol and extend to the end of a line. An end-of-line comment might explain the
purpose of a variable or the strategy used by a piece of code
Here is an example:

Good documentation can be as important in a program as its executable code. it’s a good idea to do
the following:
1. Begin a program with a statement of its purpose and other information that would help a
programmer to modify the program in future.
2. Accompany a variable definition with a comment that explains the variable’s purpose.
3. Precede major segments of code with brief comments that explain their purpose.
4. Include comments to explain the workings of complex or tricky sections of code.

NUMERIC DATA TYPES AND CHARACTER SETS


i) Integers:
In mathematics, the integers include 0, all of the positive whole numbers, and all of the negative
whole numbers.

Ramachandra College of Engineering | $@MEEN@ Page 16


Python Programming 2020-
2021

Integer literals in a Python program are written without commas, and a leading negative sign
indicates a negative value.
Although the range of integers is infinite, a real computer’s memory places a limit on the
magnitude of the largest positive and negative integers.
The most common implementation of the int data type in many programming languages consists
of the integers from –2,147,483,648 (–231) to 2,147,483,647 (231 – 1).
However, the magnitude of a long integer can be quite large, but is still limited by the memory of
your particular computer.

ii) Floating-Point Numbers


A real number in mathematics, such as the value of pi (3.1416…), consists of a whole number, a
decimal point, and a fractional part.
Real numbers have infinite precision, which means that the digits in the fractional part can
continue forever.
Like the integers, real numbers also have an infinite range. However, because a computer’s
memory is not infinitely large, a computer’s memory limits not only the range but also the
precision that can be represented for real numbers.
Python uses floating-point numbers to represent real numbers.
Values of the most common implementation of Python’s float type range from approximately –
10308 to 10308 and have 16 digits of precision.
A floating-point number can be written using either ordinary decimal notation or scientific
notation. Scientific notation is often useful for mentioning very large numbers.
Table shows some equivalent values in both notations.

iii) Character Sets

Ramachandra College of Engineering | $@MEEN@ Page 17


Python Programming 2020-
2021

Some programming languages use different data types for strings and individual characters. In
Python, character literals look just like string literals and are of the string type. But they also
belong to several different character sets, among them the ASCII set and the Unicode set.
(The term ASCII stands for American Standard Code for Information Interchange.)
In the 1960s, the original ASCII set encoded each keyboard character and several control
characters using the integers from 0 through 127. As new function keys and some international
characters were added to keyboards, the ASCII set doubled in size to 256 distinct values in the
mid-1980s. Then, when characters and symbols were added from languages other than English,
the Unicode set was created to support 65,536 values in the early 1990s.
The ASCII character set maps to a set of integers. Python’s ord and chr functions convert
characters to their numeric ASCII codes and back again, respectively.

Note that the ASCII code for 'B' is the next number in the sequence after the code for 'A'. These
two functions provide a handy way to shift letters by a fixed amount.
For example, if you want to shift three places to the right of the letter 'A', you can write
chr(ord('A') + 3) resulting in D.

Using Functions and Modules


Python includes many useful functions, which are organized in libraries of code called modules.
i) Calling Functions: Arguments and Return Values:
A function is a chunk of code that can be called by name to perform a task. Functions often
require arguments to perform their tasks. Arguments are also known as parameters.
When a function completes its task, the function may send a result back to the part of the
program that called that function. The process of sending a result back to another part of a
program is known as returning a value.
For example, the argument in the function call round(6.5) is 6.5, and the value returned is 7.
When an argument is an expression, it is first evaluated, and then its value is passed to the
function for further processing.

Ramachandra College of Engineering | $@MEEN@ Page 18


Python Programming 2020-
2021

For instance, the function call abs(4 – 5) first evaluates the expression 4 - 5 and then passes the
result, -1, to abs. Finally, abs returns 1.
The values returned by function calls can be used in expressions and statements.
For example, the function call print(abs(4 - 5) + 3) prints the value 4.
Some functions have only optional arguments, some have required arguments, and some have
both required and optional arguments.
For example, the round function has one required argument, the number to be rounded.
For example, round(7.563, 2) returns 7.56.
Python’s help function displays information about round, as follows:

ii) The math Module


Functions and other resources are coded in components called modules. The programmer must
explicitly import other functions from the modules where they are defined.
The math module includes several functions that perform basic mathematical operations.

To use a resource from a module, you write the name of a module as a qualifier, followed by a
dot (.) and the name of the resource. For example, to use the value of pi from the math module,
you would write the following code: math.pi.

If you are going to use only a couple of a module’s resources frequently, you can avoid the use of
the qualifier with each reference by importing the individual resources

Ramachandra College of Engineering | $@MEEN@ Page 19


Python Programming 2020-
2021

Programmers occasionally import all of a module’s resources to use without the qualifier. For
example, the statement from math import * would import all of the math module’s resources.

iii) The Main Module:


Like any module, the main module can also be imported. Instead of launching the script from a
terminal prompt or loading it into the shell from IDLE, you can start Python from the terminal
prompt and import the script as a module.

After importing a main module, you can view its documentation by running the help function:
>>>help(taxform)

iv) Program Format and Structure:


It’s a good idea to structure your programs as follows:
1. Start with an introductory comment stating the author’s name, the purpose of the
program, and other relevant information. This information should be in the form of a
docstring
2. Then, include statements that do the following:
• Import any modules needed by the program.
• Initialize important variables, suitably commented.
• Prompt the user for input data and save the input data in variables.
• Process the inputs to produce the results.
• Display the results.
Remember, programs should be easy for other programmers to read and understand.

v) Running a Script from a Terminal Command Prompt


In General, Python programs are run in IDLE. But, the program can be released to others to run on
their computers. Python must be installed on a user’s computer, but the user need not run IDLE to
run a Python script.

Ramachandra College of Engineering | $@MEEN@ Page 20


Python Programming 2020-
2021

One way to run a Python script is to open a terminal command prompt window by selecting
1. Start button-- All Programs--- Accessories---Command Prompt.
After the user has opened a terminal window, he or she must navigate or change directories until
the prompt shows to the directory that contains the Python script.
2. When the user is attached to the appropriate directory, she can run the script by entering the
command python scriptname.py at the command prompt.

Ramachandra College of Engineering | $@MEEN@ Page 21

You might also like