Python Programming: Ii B.Tech (Cse) - I Semester (R19)
Python Programming: Ii B.Tech (Cse) - I Semester (R19)
Python Programming: Ii B.Tech (Cse) - I Semester (R19)
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
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.
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
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.
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.
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.
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'
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
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.
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.
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.
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.
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.
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.
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.
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:
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
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.
After importing a main module, you can view its documentation by running the help function:
>>>help(taxform)
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.