UNIT-1
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.
b=int(input('Enter b'))
c=a+b
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:
>>> 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
str.format() method
f-strings
dataoutput.py Output
#more about data output Enter your country india
dataout1.py
Output:
Using f-string
Dataout2.py
Output
Comments
Variables
Variable is the name given to the value that is stored in the memory
of the computer.
Assignment Operator
Syntax
<variable> = <expr>
Examples
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'
print('Variable value is :',var1)
def fun2():
#main function
fun1()
fun2()
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
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
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
Exp2.py Output
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
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.
Type conversions
Expressions
There are several ways to present the output of a program, data can
be printed to the console.
Parameters:
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
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
Using f-string
Dataout2.py
Output
Escape Sequence
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
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
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
if Boolean_ Expression:
Statement 1
Statement 2
:
Statement N
#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
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
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
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
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
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.
Output:
• 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)
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.
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)
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)
Output:
f=True
while f:
pass
print('This line will be printed')
f=False
print('End of the program')
Output: