0% found this document useful (0 votes)
7 views25 pages

PSPP UNIT-2

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 25

UNIT II

DATA, EXPRESSIONS, STATEMENTS

Python interpreter and interactive mode, debugging; values and types: int, float, boolean, string, and
list; variables, expressions, statements, tuple assignment, precedence of operators, comments;
Illustrative programs: exchange the values of two variables, circulate the values of n variables, distance
between two points.

Introduction to Python

 Python is an open source, Object Oriented and high level programming language
 It was developed by Guido van Rossum in early 1990s
 It is a general purpose language
 It offers strong support for integration with other language and tools, as it comes with extensive
standard libraries
 Its easiest language to learn and use

Python Interpreter mode and Interactive mode

Python Interpreter

 Interpreter: To execute a program in a high-level language by translating it one line at a time.


 Compiler: To translate a program written in a high-level language into a low-level language all at
once, in preparation for later execution.

Difference between Compiler and Interpreter

Compiler Interpreter

 Compiler Takes Entire program as input  Interpreter Takes Single instruction as


input

 Intermediate Object Code is Generated  No Intermediate Object Code is


Generated

 Memory Requirement is More(Since Object  Memory Requirement is Less


Code is Generated)
 Errors are displayed after entire program is  Errors are displayed for every instruction
checked interpreted (if any)

 Example : C Compiler  Example : PYTHON

Python being a interpreter language works on two modes namely:

 Interactive mode
 Script mode

Interactive mode

 It is a command line shell which gives immediate feedback for each statement
 Working in interactive mode is convenient for beginners and for testing small pieces of code
1
Example

Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Intel)] on win32

Type "copyright", "credits" or "license()" for more information.

>>>

 The first three lines are the information about python version number and operating system
 The last line >>> is a prompt (chevron) that indicates that the interpreter is ready to enter code. If the
user types a line of code and hits enter the interpreter displays the result

Drawback:

 We cannot save the statements and have to retype all the statements once again to re-run them

Script mode

 In script mode, we type python program in a file and then use interpreter to execute the content of the
file.
 Scripts are saved to disk for future use.
 Python scripts have the extension .py, meaning that the filename ends with .py

Steps for executing a python program under script mode

 Select Filename from the shell window


 Enter python expressions or statements on separate lines
 Save the file using File->save->Filename.py
 Run the code by pressing F5

Example Output

print(1)

x=2

print(x)

2
Interactive mode Script mode
 A way of using the Python interpreter  A way of using the Python interpreter
by typing commands and expressions to read and execute statements in a
at the prompt script
 Can’t save and edit the code  Can save and edit the code
 We can see the results immediately  We cannot see the results immediately

Values and types


Values
• Values are the basic units of data like a number or string
• Eg: 2, 42.0, “Hello, World”. (These values belongs to different data types)

Data types
• Every value in python has a data type
• It is a set of values, and the allowable operations on those values

Integer Type
 An integer type (int) represents signed whole numbers
 It consists of positive and negative numbers including zero
 To write an integer in octal (base 8), precede it with “0o”
Example
>>0o100
64
 To write an integer in hexadecimal(base 16), precede it with “0x” or “0X”
 Example: 0x77
 To write an integer in binary(base 2), precede it with “0b” or “0B”
 Example: 0b101

Floating Type

 Floating point (float) type represents number with fractional part


 It has decimal point and a fractional part
 Example: 3.0 or 3.17 or -28.72
 It can also be written using decimal notation and scientific notation

Decimal Notation Scientific Notation Meaning

2.34 2.34e0 2.34*100

23.4 2.34e1 2.34*101

234.0 2.34e2 2.34*102

Complex Type

• Complex numbers are of form, x+yj, where x is the real part and y is the imaginary part.
3
Example

String Type

 A string represents sequence of characters

 It can be created using Single Quotes, Double Quotes and triple quotes

Example

– Using Single Quotes: ‘HELLO’

– Using Double Quotes: “HELLO”

– Using Triple Quotes : ‘‘‘ Hello Every One

Welcome to Python Programming’’’

Indexing

 Positive indexing helps in accessing the string from the beginning

 Negative subscript helps in accessing the string from end

 A[0] or A[-5] will display ‘H’

 A[1] or A[-4] will display “E”

String Operations

– Indexing
– Slicing
– Concatenation
– Repetitions
4
Example

str="Python Program!"
>>> print(str[0]) // Indexing
P
>>> print(str[7:10]) // Slicing
Pro
>>> print(str[7:])
Program!
>>> print(str*2) // Repetition
Python Program!Python Program!
>>> print(str+"Ver 3.4") // Concatenation
Python Program!Ver 3.4

Boolean Type

 A Boolean type represents special values ‘True’ and ‘False’


 They are represented as 1 and 0
 The most common way to produce a Boolean value is with a relational operator

Example: 2<3 is True

List Type

 List is an ordered sequence of items

 Values in the list are called elements/items


 Lists are created by placing all items inside a square bracket separated by commas
 Items in a list can be of different data type
 Lists are mutable

Operations on List

 Indexing
 Slicing
 Concatenation
 Repetitions
 Updation, Insertion and Deletion

Creating a List List1=["python",7.79,101,"hello"]


List2=["god",6.78,9]
Indexing print(List1[0])
python
print(List1[2])
101
Slicing (ending position-1) print(List1[1:3])
[7.79, 101]
print(List1[1:])
[7.79, 101, 'hello']
Repetition print(List2*3)

5
['god', 6.78, 9, 'god', 6.78, 9, 'god', 6.78, 9]
Concatenation print(List1+List2)
['python', 7.79, 101, 'hello', 'god', 6.78, 9]
Updating the List List1[2]=45
print(List1)
['python', 7.79, 45, 'hello']
Inserting an element List1.insert(2,"program")
print(List1)
['python', 7.79, 'program', 45, 'hello']
Removing an element List1.remove(45)
print(List1)
['python', 7.79, 'program', 'hello']

Tuple

• A tuple is a container which holds a series of comma- separated values (items or elements) between
parentheses
• Tuples are immutable
• It can hold a mix of data types ( int , float, string, list)
• Tuples are faster than lists
• Example:
tuple1 = (element1, element2, element 3…….element n)
tuple1 = (1, 2, 3, 4, 5)
tuple2 = (‘a’, ‘b’, ‘c’, ‘d’)

Creating a tuple t=("python",7.79,101,"hello")


Indexing print(t[0])
python
Slicing print(t[1:3])
(7.79, 101)
Concatenation t+("ram",67)
('python', 7.79, 101, 'hello', 'ram', 67)
Repetition print(t*2)
('python', 7.79, 101, 'hello', 'python', 7.79, 101, 'hello')

Altering the tuple data type leads to error. Following error occurs when user tries to do.

>>> t[1]=2

Traceback (most recent call last):

File "<pyshell#8>", line 1, in <module>

t[1]=2

TypeError: 'tuple' object does not support item assignment

Tuple Assignment

6
 An assignment to all of the elements in a tuple using single assignment statement
 The left side is a tuple of variables; the right side is a tuple of values.
 Naturally, the number of variables on the left and the number of variables on the right have to be the
same

Example:

>>> T1 = (10, 20, 30)

>>> T2 = (100,200,300,400)

>>> print (T1)

(10, 20, 30)

>>> print (T2)

(100, 200, 300, 400)

>>> T1, T2=T2, T1

>>> print (T1)

(100, 200, 300, 400)

>>> print (T2)

(10, 20, 30)

Comments

 Comments make the program easily understandable by the programmer and non-programmer who
are seeing the code
 Comment statements are non-executable statements so they are ignored while program execution
 They have no effect on the program results

Example:

# swap.py

# Swapping the values of two variable program

 Another way of doing comments is to user triple quotes “”” or ‘’’

Example

‘’’ This is a

perfect example for

multi-line comments’’’

7
Python Literals

 A literal is a notation that represents a fixed value


 Numeric Literals
o They Consist of digits (0-9) with an optional (+ or -) possibly a decimal point
o Examples of integer literals
10 2500 -4500 +200

o Floating point Literals

o Range of the numeric literal 10 -308 to 10308

Arithmetic Overflow error

a=1.4e200
b=2.1e200
c=a*b
print(c)

String Literals

 String Literals represent sequence of characters


 Example: “Hello”
 It can be single quote (‘’) or double quotes (“ ”)

Variables

 A variable is a memory location where a programmer can store a value.


 Example: roll_no, amount, name etc.
 No prior declaration is required.
 The interpreter allocates the memory on the basis of the data type of a variable.

Rules of naming variables

 Variable name must begin with only letter (a-z, A-Z) or underscore (_)
 Keywords cannot be a variable
 No special symbols allowed
 No blank spaces are allowed between variable names
 Variable names are case sensitive

Creating Variables
8
 The assignment statement (=) assigns value to a variable
 Syntax : Variable=expr

 Examples:
>>> n=10
>>> name="Jaya"
>>> 7wonders="taj mahal"
Syntax Error: invalid syntax
>>> student_name="bala"
>>> a=b=c=10

Keywords

 Keywords are reserved words they have a predefined meanings in Python


 Python has 33 keywords

Example

import keyword

print(keyword.kwlist)

Statements

 Statement is a unit of code that has an effect, like creating a variable or displaying a value

>>> n=7

>>> print(n)

 Here the first line is an assignment statement the gives a value to n


 The second line is a print statement that displays the value of n

9
Expressions

 An expression is a combination of values, variables and operators


 Example

>>> 42

>>>42
>>>a=2

>>>a+3+2

>>>7
>>>z=("hi"+"friend")

>>>print(z)

>>>hifriend

INPUT AND OUTPUT

 Input is the data entered by user in the program


 In python, input function is available for input

Output

 Output can be displayed to the user using Print statement

Operators in Python

 Operators are the constructs which can manipulate the value of operands
 Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called operator
 Types of operators
o Arithmetic Operators

10
o Comparison Operators
o Logical Operators
o Assignment Operator
o Membership Operator
o Identity Operator
o Bitwise Operator

Arithmetic Operators

They are used to perform mathematical operations like addition, subtraction, multiplication etc.

Operator Name Expression Example Output


+ Addition x+y 15+4 19
- Subtraction x-y 15-4 11
* Multiplication x*y 15*4 60
/ Division x/y 15/4 3.75
% Modulus x%y 15%4 3
** Exponentiation x**y 15**4 50625
// Floor Division x//y 40//20 3

Example Program

a=int(input("Enter the value of a:\n"))


b=int(input("Enter the value of b:\n"))
c=a+b
print("Result of addition", c)
c=a-b
print("Result of subtraction", c)
c=a*b
print("Result of Multiplication", c)
c=a/b
print("Result of Division", c)
c=a%b
print("Result of Modulus", c)
c=a**b
print("Result of Exponent", c)
c=a//b
print("Result of Floor Division", c)
Output

11
Comparison Operators

 Comparison operators are also called as Relational Operators


 They are used to compare values and return True or False condition

Operator Name Expression Example Output


> Greater than x>y 54>18 True
< Less than x<y 54<18 False
== Equal to x==y 54==18 False
!= Not equal to x!=y 54!=18 True
>= Greater than or x>=y 54>=18 True
equal to
<= Less than or x <=y 54<=18 False
equal to

Example Program
x=54
y=18
print('x>y is',x>y)
print('x<y is',x<y)
print('x==y is',x==y)
print('x!=y is',x!=y)
print('x>=y is',x>=y)
print('x<=y is',x<=y)

Output

Logical Operators

 Logical operators supported in python are and, or and not

12
Operator Name Example Explanation

and Logical AND x and y True if both the operands are true

or Logical OR x or y True if either of the operand is true

not Logical NOT x not y True if Operand is false

Example Program
x='true'
y='false'
print(' x and y is', x and y)
print('x or y is', x or y)
print('not x is', not x)

Output

Assignment Operators

 Assignment operators are used in Python to assign values to variables. a = 5 is a simple assignment
operator that assigns the value 5 on the right to the variable a on the left.

Operator Name Example Equivalent to

== Equal to X=10 X=10


+= Plus Equal to X+=10 X=X+10
-= Minus Equal to X-=10 X=X-10
/= Division Equal to X/=10 X=X/10
%= Modulus Equal to X%=10 X=X%10
//= Floor equal to X//=10 X=X//10
**= Exponent Equal to X**=10 X=X**10
= Equal to X=10 X=10

Example Program

x=12
y=15
x+=y
print("x+=y:",x)
x-=y

13
print("x-=y:",x)
x*=y
print("x*=y:",x)
x/=y
print("x/=y:",x)
x%=y
print("x%=y:",x)
x**=y
print("x**=y",x)
x//=y
print("x//=y",x)

Output
x+=y: 27
x-=y: 12
x*=y: 180
x/=y: 12.0
x%=y: 12.0
x**=y 1.5407021574586368e+16
x//=y 1027134771639091.0

Membership Operators

 Membership Operators are used to test whether a value or variable is found in a sequence (list, sting,
tuple, dictionary and set)
 in and not in are two membership operators

Operator Example Explanation


in x in y True if the value or variable found in sequence
not in x not in y True if the value or variable not found in sequence

Example Program
x="Python Program"
print('y' in x)
print('p' in x)
print('hello' not in x)
print('n' not in x)

Output

Identity Operators
 Identity Operators compare the memory location of two objects
 The two identity operators are is and is not

14
Example Program

x1 = 5
y 1= 5
x2 = 'Hello'
y2 = 'Hello'
print(x1 is not y1)
print(x2 is y2)

Output:

Bitwise Operators

 Bitwise operations manipulate on bits


 Here numbers are represented with bits, a series of zeros and ones

Operator Name Example Explanation

& Bitwise AND X&Y Both operands are true result is true

| Bitwise OR X|Y True if either of the operand is true

` Bitwise NOT `x It complements the bits

^ Bitwise XOR X^Y Result is true if either of the operands are


true
>> Bitwise right shift X>>2 Operands are shifted right by number of
times specified
<< Bitwise left shift X<<2 Operands are shifted left by number of times
specified

15
Operator Precedence

Operator Description

** Exponentiation (raise to the power)

Complement, unary plus and minus (method


~+-
names for the last two are +@ and -@)

* / % // Multiply, divide, modulo and floor division

+- Addition and subtraction

>><< Right and left bitwise shift

& Bitwise 'AND'

^| Bitwise exclusive `OR' and regular `OR'

<= <>>= Comparison operators

16
<> == != Equality operators

= %= /= //= -=
Assignment operators
+= *= **=

is is not Identity operators

in not in Membership operators

not or and Logical operators

 The acronym PEMDAS ( Parentheses, Exponentiation, Multiplication ,Division, Addition


,Subtraction) is a useful way to remember the rules:
o Parentheses have the highest precedence and can be used to force an expression to evaluate in
the order you want. Since expressions in parentheses are evaluated first, 2 * (3-1) is 4, and
(1+1)**(5-2) is 8.
o Exponentiation has the next highest precedence, so 1 + 2**3 is 9, not 27, and 2*3**2 is 18, not
36.
o Multiplication and Division have higher precedence than Addition and Subtraction. So 2*3-1
is 5, not 4, and 6+4/2 is 8, not 5
o Operators with the same precedence are evaluated from left to right (except exponentiation)

Modules

 Module
 Creating a Module [user defined]
 Built-in modules
o Calendar
o Math
o Random
 Randint
 Using choice
 Way to access the module
o Through import statement
o from…import
o import all names

Module

 Modules refer to a file containing python statements and definitions


 We use modules to break down large programs into small manageable and organized files
 Modules provide reusability of code

Creating a Module: [User define]

17
Example.py

def add(a,b):

result=a+b

return result

How to access user defined module:

Syntax: from python_filename import function_name

from example import add

print(add(5,6))

Output:

11

Built-in Modules

 Random
 Math
 Calendar and date-time
1. Random
Usage/Need:
 If we want a computer to pick a random number in a given range we use random function

Random Functions

 Randint
o If we want a random integer, we use the randint function
o randint accepts two parameters : lowest and highest number
 Example
import random
print(random.randint(0,5))
The output will be either 1,2,3,4 or 5
 Using Choice
o Helps to generate a random value from the sequence
o The choice function can often be used for choosing a random element from a list
 Example

import random

mylist=[2,101,False]

print(random.choice(mylist))

2. Math
 The math module provides access to mathematical constants and functions
18
 Example
import math
print(math.pi)
print(math.e)
print(math.factorial(5))
print(math.sin(2))
print(math.cos(0.5))
print(math.sqrt(49))
Output

3. Calendar & date-time


 Python’s time and calendar modules keep track of date & times
Example
import calendar
cal=calendar.month(2017,5)
print (cal)
Output
May 2017
Mo Tu We Th Fr Sa Su
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
 Date-time
Example
import datetime
print (datetime.date.today())
Output
2018-10-02
import datetime
print (datetime.datetime.now())
Output
2018-10-02 10:14:53.508789

Way to Access the Modules


 Through python import statement
 from…..import statement
 import all names

Through python import statement


Syntax: import function_name

19
We can import a module using import statement and access the definitions inside it using dot operator

Example
import math
print(“the value of pi is”,math.pi)

Output: the value of pi is 3.141592653589793

from…..import statement
Syntax: from python_filename import function_name 1, function_name 2

Example
>>> from math import pi,e
>>> print(pi)
3.141592653589793
>>> print(e)
2.718281828459045

import all names

Syntax: from python file import*

>>> from math import*


>>> print(pi)
3.141592653589793

Functions
Functions are “ self-contained” modules of code that accomplish a specific task

Need for function


 When the program is too complex and large they are divided into parts. Each part is separately coded and
combined into single program. Each subprogram is called as function
 Debugging, Testing and maintenance becomes easy when the program is divided into subprograms.
 Functions are used to avoid rewriting same code again and again in a program.
 Function provides code re-usability
 The length of the program is reduced.

STEPS
 Function definition
 Function Call

Defining Function
Syntax

Function Call
Syntax: function_name(arg1, arg2)

Flow of execution
20
 The order in which statements are executed is called the flow of execution
 Execution always begins at the first statement of the program
 Statements are executed one at a time, in order, from top to bottom.
 Function definitions do not alter the flow of execution of the program, but remember that statements inside
the function are not executed until the function is called.

Function Prototypes
Function with no arguments and no return values
 In this type no argument is passed through the function call and no output is return to main function
 The sub function will read the input values perform the operation and print the result in the same block
def sum():
x=int(input("Enter a value:"))
y=int(input("Enter b value:"))
z=x+y
print(z)
sum()

Function with arguments and no return


 Arguments are passed through the function call but output is not return to the main function
def sum(x,y):
z=x+y
print("Sum of two values:",z)
sum(9,2)

Function with no arguments and with return values


 In this type no argument is passed through the function call but output is return to the main function.
def sum():
x=int(input("Enter A Value:"))
y=int(input("Enter B Value:"))
z=x+y
return z
x=sum()
print(x)

Function with arguments and with return values


 In this type arguments are passed through the function call and output is return to the main function
def sum(a,b):
z=a+b
return z
x=int(input())
y=int(input())
z=sum(x,y)
print(z)

Parameters and Arguments


Parameters
• Parameters are the value(s) provided in the parenthesis when we write function header.
• Example: def my_add(a,b):

Arguments
• Arguments are the value(s) provided in function call/invoke statement
• List of arguments should be supplied in same way as parameters are listed.
• Example: my_add(x,y)
21
Argument Types
1. Required Arguments
o The number of arguments in the function call should match exactly with the function definition
def my_details(name,age):
print("Name:",name)
print("Age:",age)
return
my_details("george",45)

2. Keyword Arguments
o Arguments preceded with a variable name followed by a = sign
def my_details(name,age):
print("Name:",name)
print("Age:",age)
return
my_details(name="george",age=45)

3. Default arguments
o Assumes a default value if a value is not provided in the function call for that argument.
def my_details(name,age=40):
print("Name:",name)
print("Age:",age)
return
my_details(name="George")

4. Variable length arguments


If we want to specify more arguments than specified while defining the function,variable length arguments
are used. It is denoted by * symbol before parameter.
def my_details(*name):
print(*name)
my_details("rajan","rahul","micheal","arjun")

Illustrative Problems

Circulate the value of the Variables Output


def rotate(a,n): [1, 2, 3, 4, 5]
new_list=a[n:]+a[:n] List rotated clockwise by 1= [2, 3, 4, 5, 1]
return new_list List rotated clockwise by 2= [3, 4, 5, 1, 2]
example_list=[1,2,3,4,5] List rotated anti-clockwise by 2= [4, 5, 1, 2, 3]
print(example_list)
my_list=rotate(example_list,1)
print("List rotated clockwise by 1=",my_list)
my_list=rotate(example_list,2)
print("List rotated clockwise by 2=",my_list)
my_list=rotate(example_list,-2)
print("List rotated anti-clockwise by 2=",my_list)
Distance between two points Output
x1=int(input("Enter X1:")) Enter X1:4
y1=int(input("Enter y1:")) Enter y1:6
x2=int(input("Enter X2:")) Enter X2:8
y2=int(input("Enter Y2:")) Enter Y2:10
p=(x2-x1)*(x2-x1)+(y2-y1)*(y2-y1) d=p**0.5 5.656854249492381

22
print(d)
Exchange the values of two variables without using Output
third variable
x=int(input("Enter the first number\n")) Enter the first number
y=int(input("Enter the second number\n")) 50
print("Values before swap are %d and %d ."%(x,y)) Enter the second number
x,y = y,x 10
print("Values after swap are %d and %d ."%(x,y)) Values before swap are 50 and 10.
Values after swap are 10 and 50.
Swap two numbers using third variable Output
x=int(input("Enter the first number\n")) Enter the first number
y=int(input("Enter the second number\n")) 50
print("Values before swap are %d and %d ."%(x,y)) Enter the second number
temp=x 10
x=y Values before swap are 50 and 10.
y=temp Values after swap are 10 and 50.
print("Values after swap are %d and %d ."%(x,y))
Sum of first ‘n’ even numbers using function Output
def sum(n): Enter the limit:10
i=0 10
sum=0 Sum of even numbers= 20
while i<n:
sum=sum+i
i=i+2
return sum
n=int(input("Enter the limit:"))
print(n)
result=sum(n)
print("Sum of even numbers=",result)
Leap Year Program Output
year=int(input("Enter a given year:")) Enter a given year:1994
if(((year%4==0)and(year%100!=0)) or (year%400==0)): The given year 1994 is not a Leap
print("The given year",year,"is a Leap Year") Year
else:
print("The given year",year,"is not a Leap Year")
Simple Interest Output
x=float(input("Enter the principal amount\n")) Enter the principal amount
y=float(input("Enter the rate of interest\n")) 10000
z=float(input("Enter the time period (in years)\n")) Enter the rate of interest
si=(x*y*z)/100 7
print("Simple Interest is %.2f"%si) Enter the time period (in years)
10
Simple Interest is 7000.00
Converting Fahrenheit to Centigrade Output
fh=float(input("Enter temperature in Fahrenheit:\n")) Enter temperature in Fahrenheit:
cl=(fh-32)/1.8 45
print("Temperature in Celsius: %.2f"%cl) Temperature in Celsius: 7.22
Employee Payroll Output
name=input("Enter name: ") Enter name: Ram
basic=float(input("\nEnter Basic Salary: ")) Enter Basic Salary: 23000
hra=float(input("\nEnter HRA: ")) Enter HRA: 9500
da=float(input("\nEnter D.A.: ")) Enter D.A.: 9500
pf=(12/100)*basic PAYROLL DETAILS:
23
gs=basic+hra+da+pf Name: Mr.Ram
print("\nPAYROLL DETAILS:") BASIC PAY: Rs.23000.00/-
print("Name: Mr.%s"%name) HRA: Rs.9500.00/-
print("BASIC PAY: Rs.%.2f"%basic,end="/-") DA: Rs.9500.00/-
print("\nHRA: Rs.%.2f"%hra,end="/-") PF: Rs.2760.00/-
print("\nDA: Rs.%.2f"%da,end="/-") ***GROSS SALARY: Rs.44760.00/-
print("\nPF: Rs.%.2f"%pf,end="/-") ***
print("\n***GROSS SALARY: Rs.%.2f/-***"%gs)
Menu Driven Calculator Using Functions Output
def addition(a,b): 3
return a+b 5
def subtraction(a,b): 1
return a-b 8
def multiplication(a,b):
return a*b
def division(a,b):
return a/b
def modulo(a,b):
return a%b
def average(a,b):
return (a+b)/2
def power(a,b):
return a**b
a=int(input())
b=int(input())
select=int(input())
if select==1:
print("%d"%addition(a,b))
if select==2:
print("%d"%subtraction(a,b))
if select==3:
print("%d"%multiplication(a,b))
if select==4:
print("%.2f"%division(a,b))
if select==5:
print("%d"%modulo(a,b))
if select==6:
print("%.2f"%average(a,b))
if select==7:
print("%d"%power(a,b))
Square root of a number Output
def squareroot(f): Enter a number
return f**0.5 12
f=int(input("Enter a number\n")) The square root of 12 is 3.46
print("The square root of",f,"is %.2f"%squareroot(f))
Checking Vowels Output
ch=input("Enter a Character : \n") Enter a Character :
if(ch=='a' or ch=='A' or ch=='e' or ch=='E' or ch=='i' or a
ch=='I' or ch=='o' or ch=='O' or ch=='u' or ch=='U'): a is vowel.
print(ch, "is vowel.")
else:
print(ch, "is consonant.")
Area of Circle using Functions Output

24
def calcarea(x): 2
area=3.14*x*x The area of the circle is 12.56
return area
a=float(input())
area=calcarea(a)
print("The area of the circle is %.2f"%area)
Prime Number using Functions Output
def findprime(n): 7
if (n==1): 1
return 0
elif(n==2):
return 1  The program returns 1 if the number is
else: prime else it returns zero.
for x in range(2,n):  7 is prime number it is returning 1.
if(n%x==0):
return 0
return 1
n=int(input())
print(findprime(n))

25

You might also like