Python Programming (R19) - UNIT-1
Python Programming (R19) - UNIT-1
Unit-1
Topics to be covered
Introduction: 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.
I. Introduction
Introduction to Python
Python was created by Guido Van Rossum, who was a Dutch person from
Netherlands in the Year 1991. Guido Van Rossum created it when he was
working in National Research Institute of Mathematics and Computer
Science in Netherlands. He thought to create a scripting language as a
“Hobby” in Christmas break in 1980. He studied all the languages like ABC
(All Basic Code), C, C++, Modula-3, Smalltalk, Algol-68 and Unix Shell and
collected best features. He stared implementing it from 1989 and released
first working version of Python in 1991. He named it as “Python”, being a
big fan of “Monty Python’s Flying Circus” comedy show broadcasted in
BBC from 1969 to 1974.
Python is a high-level, general-purpose programming language for
solving problems on modern computer systems. The language and many
supporting tools are free, and Python programs can run on any operating
system. You can download Python, its documentation, and related
materials from www.python.org.
www.Jntufastupdates.com 1
all the related factors such as input, output, processing
requirements, and memory requirements etc.
b. Program Design: Once the problem and its requirements have been
identified, then the design of the program will be carried out with
tolls like algorithms and flowcharts. An Algorithm is a step-by-step
process to be followed to solve the problem. It is formally written
using the English language. The flowchart is a visual
representation of the steps mentioned in the algorithm. This
flowchart has some set of symbols that are connected to perform the
intended task. The symbols such as Square, Dimond, Lines, and
Circles etc. are used.
b=int(input('Enter b'))
c=a+b
www.Jntufastupdates.com 2
d. Debugging: At this stage the errors such as syntax errors in the
programs are detected and corrected. This stage of program
development is an important process. Debugging is also known as
program validation.
e. Testing: The program is tested on a number of suitable test cases.
The most insignificant and the most special cases should be
identified and tested.
f. Documentation: Documentation is a very essential step in the
program development. Documentation helps the users and the who
actually maintain the software.
g. Maintenance: Even after the software is completed, it needs to be
maintained and evaluated regularly. In software maintenance, the
programming team fixes program errors and updates the software
when new features are introduced.
Input, Processing, and Output
The data that is given to the programs is called input. This input is
accepted from some source, and it is processed inside the program, and
interactive programs, the input source is the keyboard, and the output
The programmer can also force the output of a value by using the
print function. The simplest form for using this function looks like the
following:
www.Jntufastupdates.com 3
Parameters:
>>> print(12*3/4)
9.0
>>> print(1,2,3,4,sep='-',end='$')
1-2-3-4$
When we are really working with python programs, they often require
input from the user. The input can be received from the user using the
input function. When you are working with input () function it causes
the program to stop until the user enters the input and presses the
enter button. The program later uses the input given by the user and
console or saves it to the specified file with file parameter. The syntax
www.Jntufastupdates.com 4
Displays a prompt for the input. In this example, the prompt is
“Enter value for the variable”.
Receives a string of keystrokes, called characters, entered at the
keyboard and returns the string to the shell.
str.format() method
f-strings
dataoutput.py Output
#more about data output Enter your country india
www.Jntufastupdates.com 5
dataout.py Output
branch=input('Enter branch name') Enter branch name CSE
dataout1.py
Output:
Using f-string
www.Jntufastupdates.com 6
curly braces { }. The expressions are replaced with their values. An f
at the beginning of the string tells Python to allow any valid variable
names within the string.
Dataout2.py
Output
Comments
www.Jntufastupdates.com 7
Triple double quotes Triple single quotes
“”” python supports multiple ‘‘‘python supports multiple
comment using Triple double comment using Triple double
quotes””” quotes’’’
Variables
Variable is the name given to the value that is stored in the memory
of the computer.
Assignment Operator
Syntax
<variable> = <expr>
Examples
www.Jntufastupdates.com 8
x=5
Y=10.25
C=3+4J
Multiple Assignment
Syntax
var1=var2=var3...varn= <expr>
Example :
x=y=z=1
Example:
x, y, z = 1, 2, "abcd"
var1=‘Python'
#function definition
def fun1():
var1='Pyt'
www.Jntufastupdates.com 9
print('Variable value is :',var1)
def fun2():
#main function
fun1()
fun2()
www.Jntufastupdates.com 10
Write a python program to read your name and display it to
console.
readinput.py Output
name=input('Enter your name:') Enter your name: guido vas
rossum
print('My name is:',name)
My name is: guido vas rossum
Performing Calculations
>>> 3.14*3*3
28.259999999999998
>>> 9*5.0
45.0
Here, 9 is integer, and 5.0 is float, then the less general type that is
int will be converted into more general type that is float and the
entire expression will result in float value.
>>> eval('45/9*2')
10.0
www.Jntufastupdates.com 11
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.
>>> 4 + 6
1. Arithmetic Operators
2. Bitwise Operators
3. Comparison Operators
4. Logical Operators
5. Assignment Operators
6. Membership Operators
7. Identity Operators
Arithmetic Operators
www.Jntufastupdates.com 12
Write a program that asks the user for a weight in kilograms and
converts it to pounds. There are 2.2 pounds in a kilogram.
Prg1.py Output
k=float (input ('Enter kilograms')) Enter kilograms100
#Display result
Write a program that asks the user to enter three numbers (use
three separate input statements). Create variables called total
and average that hold the sum and average of the three numbers
and print out the values of total and average.
Prg2.py Output
Bitwise Operators
www.Jntufastupdates.com 13
number ten has a binary representation of 1010. Bitwise operators
perform their operations on such binary representations, but they
return standard Python numerical values. The Following table lists
all the Bitwise operators:
www.Jntufastupdates.com 14
Comparison Operators
Exp2.py Output
www.Jntufastupdates.com 15
logical operators
The logical operators are used for comparing 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. There are three logical operators: and, or, and
not.
Assignment Operator
x=4
x+=5
print (“The value of x is:”, x)
Output:
The value of x 9
www.Jntufastupdates.com 16
Membership Operators
Write a program that asks the user to enter a word and prints
out whether that word contains any vowels. (Lab prg 8)
Prg8.py Output
word=input ('Enter any word:') Enter any word: python
vowels=['a','e','i','o','u']
o is present
for i in vowels:
if i in word:
print (i,'is present')
Identity Operators
These are used to check if two values (variable) are located on the
same part of the memory. If the x is a variable contain some value,
it is assigned to variable y. Now both variables are pointing
(referring) to the same location on the memory as shown in the
example program.
www.Jntufastupdates.com 17
is not True if the operands are not X=5 #int
identical (refer to the same Y=5.0 # float
memory) X is not Y, returns True
Type conversions
www.Jntufastupdates.com 18
Convert an integer number (of any size) to an octal string
prefixed with “0o” using oct() function. For example, o=oct(8),
where o contains ‘0o10’ and o=oct(16), where o contains ‘0o20’
The type() function returns the data type of the given object.
If we pass 20 to the type() function as follow type(20) then its
type will be displayed as <class 'int'>
Expressions
www.Jntufastupdates.com 19
Multiplication and Division have the same precedence, which
is higher than Addition and Subtraction, which also have the
same precedence. So 2 *3-1 yields 5 rather than 4, and 2/3-1 is -1,
not 1 (re-member that in integer division, 2/3=0).
There are several ways to present the output of a program, data can
be printed to the console.
Parameters:
www.Jntufastupdates.com 20
end=’end’: (Optional) Specify what to print at the end. Default : ‘\n’
Example:
>>>print(10,20,30,40,sep='-',end='&’)
Output:
10-20-30-40&
>>>print('apple',1,'mango',2,'orange',3,sep='@',end='#’)
Output:
apple@1@mango@2@orange@3#
str.format() method
f-strings
www.Jntufastupdates.com 21
Using str.format() with positional arguments
dataoutput.py Output
#more about data output Enter your country india
dataout.py Output
branch=input('Enter branch name') Enter branch name CSE
dataout1.py
www.Jntufastupdates.com 22
Output:
Using f-string
Dataout2.py
Output
www.Jntufastupdates.com 23
Double-quoted strings are suitable for composing strings that contain
single quotation marks or apostrophes. Here is a self-justifying
example:
Escape Sequence
www.Jntufastupdates.com 24
String Concatenation
We can join two or more strings to form a new string using the
concatenation operator +. Here is an example:
Assignment Statement
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 in
the tax calculator case study 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>
When this happens to the variable name for the first time, 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.
Comment
www.Jntufastupdates.com 25
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. This can be written inside Triple double quotes or
Triple single quotes. 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.
End-of-line
Docstring
# read word from keyboard
"""
Program: VowelTest.py
Author : KSR
Purpose: Testing whether a
given word contains
any vowels or not
"""
Numeric Data
types
Under the numeric data types python has three different types:
integers, floating-point, complex numbers. These are defined as int,
float, complex in python. Integers can be of any length; it is only
limited by the memory available. Python uses floating-point
www.Jntufastupdates.com 26
numbers to represent real numbers. 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. A floating-point number can be written using either
ordinary decimal notation or scientific notation. Example, 37.8 can
be represented in scientific notation as 3.78e1. Complex numbers
are written in the form, x + yj, where x is the real part and y is the
imaginary part. Example, (3+4j).
Character Sets
www.Jntufastupdates.com 27
parameters. When a function completes its task, the function may
send a result back to the part of the program that called that
function, which is also known as caller. The process of sending a
result back to another part of a program is known as returning a
value.
www.Jntufastupdates.com 28
'nan', 'pi', 'pow', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh',
'tau', 'trunc']
if Boolean_ Expression:
Statement 1
Statement 2
:
Statement N
www.Jntufastupdates.com 29
executed, otherwise the first statement after the if block will be
executed. The statements inside the if block must be properly
indented with spaces or tab.
Write python program to test whether a given number is Even
or not using if decision statement.
#Even or Odd
n=int(input("Enter the number"))
if n%2==0:
print(n,'is even number')
print('End of if block')
print('End of the program')
print('Execution is completed')
if Boolean_Expression:
statements 1
else:
statements 2
www.Jntufastupdates.com 30
if n%2==0:
print(n,'is even number')
print('End of if block')
else:
print(n,'is odd')
print('else block')
print('End of the program')
print('Execution is completed')
Note: if you observe above if and else blocks. The else block
indentation is single space, whereas the if bloc has used tab for
indentation. Hence both Block can use different indentation, but all
the statements within the block should have same indentation.
Generate a random number between 1 and 10. Ask the user to
guess the number and print a message based on whether they
get it right or not. (Lab prg 6)
import random
while True:
n=int(input('Enter any number between 1 and 10'))
print(f' You are trying to guess number {n}')
rn=random.randint(1,10)
print('The random number generated is:',rn)
if rn==n:
print('Your guessing is right')
else:
print('Badluck your guessing is wrong')
Output:
Enter any number between 1 and 108
You are trying to guess number 8
The random number generated is: 1
Bad luck your guessing is wrong
Enter any number between 1 and 105
www.Jntufastupdates.com 31
You are trying to guess number 5
The random number generated is: 5
Your guessing is right
If Boolean_expression1:
Statements
elif Boolean_expression2:
Statements
elif Boolean_exxpression3:
Statements
else:
Statements
Write a Program to Prompt for a Score between 0.0 and 1.0. If the Score Is Out
of Range, Print an Error. If the Score Is between 0.0 and 1.0, Print a Grade Using
the Following Table.
Score >=0.9 >=0.8 >=0.7 >=0.6 <0.6
Grade A B C D F
www.Jntufastupdates.com 32
elif score>=0.7:
Output:
print('Your Grade is C')
Enter your score 0.75
elif score>=0.6:
print('Your Grade is D') Your Grade is C
else:
print('Your Grade is F')
Nested if statements
Sometimes it may be need to write an if statement inside another if
block then such if statements are called nested if statements. The
syntax would be as follow:
if Boolean_expression1:
if Boolean_expression2:
if Boolean_expression3:
Statements
else:
Statements
else:
print(f'{year} is a leap year')
else:
print(f'{year} is not a leap year')
Comparing Strings
www.Jntufastupdates.com 33
We can use comparison operators such as >, <, <=, >=, ==, and != to compare two
strings. This expression can return a Boolean value either True or False. Python
compares strings using ASCII value of the characters. For example,
Boolean Variables
The variables that store Boolean value either True or False called Boolean variables.
If the expression is returning a Boolean value then it is called Boolean expression.
Example:
>>>X=True
>>>Y=False
>>> a>5 and a<10 #Boolean expression
www.Jntufastupdates.com 34
as loops, which repeat an action. Each repetition of the action is
known as a pass or an iteration. There are two types of loops—
those that repeat an action a predefined number of times (definite
iteration) and those that perform the action until the program
determines that it needs to stop (indefinite iteration). There are
two loop statements in Python, for and while.
The first line is called loop header which contains a keyword while,
and condition which return a Boolean value and colon at the end.
The body of the loop contains statement1, statements2 , and so on.
Thus is repeated until the condition is evaluated to True otherwise
loop will be terminated.
www.Jntufastupdates.com 35
data=input('Enter any number')
sum=0
while data!=" ":
sum=sum+int(data)
data=input('Enter any number or space to quit')
print('The sum is :',sum)
The count control with while loop
We can also use while loop for count-controlled loops. The body of the while is
repeatedly executed until the condition which returns a Boolean value True.
Otherwise body of the loop is terminated and the first statement after the while loop
will be executed.
Write a program that asks the user for their name and how many times to
print it. The program should print out the user’s name the specified number
of times. (Lab Prg 4)
n=int(input('Enter the number that you want to display your name:'))
name=input('Enter name:')
while n>=0:
print(name)
n=n-1
print('End of the program')
Output:
www.Jntufastupdates.com 36
for variable in [value1, value2, etc.]: # Loop Header
statement1
statement2
…………
Statement N
Here variable is the name of the variable. And for and in are the
keywords. Inside the square brackets a sequence of values is
separated by comma. In Python, a comma-separated sequence of
data items that are enclosed in a set of square brackets is called a
list. The list is created with help of [] square brackets. The list also
can be created with help of tuple. We can also use range() function
to create the list. The general form of the range() function will be as
follow:
• range(number) –ex: range (10) –It takes all the values from 0 to 9
Write a Python Program to find the sum of all the items in the list using for
loop.
fortest.py Output
#sum of all items in the list The sum of all items in the list is:
s=0 15
for x in [1,2,3,4,5]: # list
s=s+x
print ("The sum of all items in the list is:",s )
Write a program that uses a for loop to print the numbers 8, 11, 14, 17, 20, . . . ,
83, 86, 89. (Lab Prg 3)
for i in range(8,90,3):
print(i)
www.Jntufastupdates.com 37
Use a for loop to print a triangle like the one below. Allow the user to specify
how high the triangle should be. (lab Prg 5)
for i in range(0,4):
for j in range(0,i+1):
print('*',end=" ")
print("\r")
n=int(input('Enter n:'))
sum=0
for i in range(n):
data=float(input('Enter value'))
sum=sum+data
#display sum
print('Sum is:',sum)
Output:
Enter n:4
Enter value12
Enter value13
Enter value21
Enter value22
Sum is: 68.0
Input Validation Loops
Loops can be used to validate user input. For instance, a program may
require the user to enter a positive integer. Many of us have seen a
“yes/no” prompt at some point, although probably in the form of a
dialog box with buttons rather than text.
www.Jntufastupdates.com 38
import random
action = "Y"
while action == "Y":
Nested loops
Writing a loop statement inside another is called Nested
loops. The "inner loop" will be executed one time for each iteration
of the "outer loop". We can put any type of loop inside any other type
of loop. For example, a for loop can be inside a while loop or vice
versa.
Syntax of nested loops:
#Nested for loops
Use a for loop to print a triangle like the one below. Allow the
user to specify how high the triangle should be. (Lab Prg 5)
www.Jntufastupdates.com 39
Using for nested loops Using for and while nested loops
for i in range(4): for i in range(4):
for j in range(0,i+1): j=0
print('*',end=' ') while j < (i+1):
print('\r') print('*',end=' ')
j=j+1
print('\r')
*
**
***
****
print('2')
for i in range(3,101,2):
for j in range(2,i):
if i%j==0:
break
else:
print(i)
www.Jntufastupdates.com 40
Jump Statements
we have three jump statements: break, continue and pass.
Break statement:
It terminates the current loop and resumes execution
at the next statement, just like the traditional break
statement in C.
The break statement can be used in both while and for
loops.
Output:
www.Jntufastupdates.com 41
The pass statement
The pass statement does nothing
It can be used when a statement is required syntactically but the
program requires no action
Example: creating an infinite loop that does nothing
while True:
pass
f=True
while f:
pass
print('This line will be printed')
f=False
print('End of the program')
Output:
www.Jntufastupdates.com 42