0% found this document useful (0 votes)
7 views

Python project (1)

This document is a project file on Python for a Computer Science Engineering course, detailing various topics such as functions, operators, and a calculator project. It includes acknowledgments, explanations of Python functions, their types, syntax, and examples, as well as an overview of Python operators. The project reflects the author's learning journey and gratitude towards their mentor and supporters.

Uploaded by

naitiksingh8470
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Python project (1)

This document is a project file on Python for a Computer Science Engineering course, detailing various topics such as functions, operators, and a calculator project. It includes acknowledgments, explanations of Python functions, their types, syntax, and examples, as well as an overview of Python operators. The project reflects the author's learning journey and gratitude towards their mentor and supporters.

Uploaded by

naitiksingh8470
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 34

Project File of Python

Computer Science Engineering (4th Semester)


RAJA JAIT SINGH COLLEGE OF DIPLOMA AND ENGINEERING
(Govt. of India)

Prepared By: -Naitik singh Submitted To: - Shweta


Mam
Roll No. 222590800139
INDEX

S.NO TOPIC DATE SIGNATURE


1. Functions in python with
syntax and example in detail.
2. Operators in python
with syntax and
example in detail.
3. Project on Calculator
Acknowledgement

In this vast world of coding, where every line of code holds the promise of
innovation and progress, I find myself deeply indebted to my Python teacher,
Mrs. Shweta. Their unwavering guidance has been the compass steering me
through the complexities of Python, culminating in the successful completion
of my ambitious project. To them, I owe a debt of gratitude beyond words.

But my journey doesn't end there. It's paved with the unwavering support of
my parents and friends, who stood by me with unyielding encouragement and
cooperation. Their belief in me was the fuel that propelled me forward, even
when the challenges seemed insurmountable.

Entitled "Calculator," my project represents not just lines of code, but a


culmination of countless hours of dedication and passion. It stands as a
testament to the relentless pursuit of excellence and the thirst for knowledge
that drives me.

Amidst this journey, one figure stands out – our mentor, Mrs. Shweta. Their
presence has been more than that of a guide; they've been a beacon of
wisdom and inspiration. Their invaluable advice and insightful suggestions have
been the guiding light illuminating the path to success. For their time, effort,
and unwavering support throughout this journey, I extend my deepest
gratitude.

In this acknowledgment, I seek not just to express gratitude but to immortalize


the profound impact each of these individuals has had on my journey. Their
contributions have shaped not just my project but my entire worldview,
instilling in me the values of perseverance, collaboration, and the relentless
pursuit of knowledge.
With heartfelt appreciation,
Mayank

Python Functions: -
Python Functions is a block of statements that return the specific task. The idea
is to put some commonly or repeatedly done tasks together and make a
function so that instead of writing the same code again and again for different
inputs, we can do the function calls to reuse code contained in it over and over
again.
Some Benefits of Using Functions: -
 Increase Code Readability
 Increase Code Reusability
 Python Function Declaration
The syntax to declare a function is: -

Types of Functions in Python


Below are the different types of functions in Python: -
1. Built-in library function: These are Standard functions in
Python that are available to use.
2. User-defined function: We can create our own functions
based on our requirements.
Creating a Function in Python
We can define a function in Python, using the def keyword. We
can add any type of functionalities and properties to it as we
require. By the following example, we can understand how to
write a function in Python. In this way we can create Python
function definition by using def keyword.

Example: -
# A simple Python function
def fun():
print("Welcome to GFG")

Calling a Function in Python


After creating a function in Python we can call it by using the
name of the functions Python followed by parenthesis
containing parameters of that particular function. Below is the
example for calling def function Python.

Example: -
# A simple Python function
def fun():
print("Welcome to GFG")

# Driver code to call a function


fun()

Output - Welcome to GFG


Python Function with Parameters
If you have experience in C/C++ or Java then you must be
thinking about the return type of the function and data type of
arguments. That is possible in Python as well (specifically for
Python 3.5 and above).
Python Function Syntax with Parameters
def function_name(parameter: data_type) ->
return_type:
"""Docstring"""
# body of the function
return expression
The following example uses arguments and parameters that
you will learn later in this article so you can come back to it
again if not understood.

Python3
def add(num1: int, num2: int) -> int:
"""Add two numbers"""
num3 = num1 + num2

return num3

# Driver code
num1, num2 = 5, 15
ans = add(num1, num2)
print(f"The addition of {num1} and {num2} results
{ans}.")
Output:
The addition of 5 and 15 results 20.
Python3
# some more functions
def is_prime(n):
if n in [2, 3]:
return True
if (n == 1) or (n % 2 == 0):
return False
r = 3
while r * r <= n:
if n % r == 0:
return False
r += 2
return True
print(is_prime(78), is_prime(79))
Output:
False True

Python Function Arguments


Arguments are the values passed inside the parenthesis of the
function. A function can have any number of arguments
separated by a comma.
In this example, we will create a simple function in Python to
check whether the number passed as an argument to the
function is even or odd.

Python3
# A simple Python function to check
# whether x is even or odd
def evenOdd(x):
if (x % 2 == 0):
print("even")
else:
print("odd")

# Driver code to call the function


evenOdd(2)
evenOdd(3)
Output – even
odd

Types of Python Function Arguments


Python supports various types of arguments that can be passed
at the time of the function call. In Python, we have the following
function argument types in Python:
 Default argument
 Keyword arguments (named arguments)
 Positional arguments
 Arbitrary arguments (variable-length arguments *args and
**kwargs)
Let’s discuss each type in detail.

Default Arguments
A default argument is a parameter that assumes a default
value if a value is not provided in the function call for that
argument. The following example illustrates Default arguments
to write functions in Python.
Python3
# Python program to demonstrate
# default arguments
def myFun(x, y=50):
print("x: ", x)
print("y: ", y)

# Driver code (We call myFun() with only


# argument)
myFun(10)
Output - x: 10
y: 50

Like C++ default arguments, any number of arguments in a


function can have a default value. But once we have a default
argument, all the arguments to its right must also have default
values.

Keyword Arguments
The idea is to allow the caller to specify the argument name
with values so that the caller does not need to remember the
order of parameters.
Python3
# Python program to demonstrate Keyword Arguments
def student(firstname, lastname):
print(firstname, lastname)
# Keyword arguments
student(firstname='Geeks', lastname='Practice')
student(lastname='Practice', firstname='Geeks')
Output:
Geeks Practice
Geeks Practice

Positional Arguments
We used the Position argument during the function call so that
the first argument (or value) is assigned to name and the
second argument (or value) is assigned to age. By changing the
position, or if you forget the order of the positions, the values
can be used in the wrong places, as shown in the Case-2
example below, where 27 is assigned to the name and Suraj is
assigned to the age.
Python3
def nameAge(name, age):
print("Hi, I am", name)
print("My age is ", age)

# You will get correct output because


# argument is given in order
print("Case-1:")
nameAge("Suraj", 27)
# You will get incorrect output because
# argument is not in order
print("\nCase-2:")
nameAge(27, "Suraj")
Output:
Case-1:
Hi, I am Suraj
My age is 27
Case-2:
Hi, I am 27
My age is Suraj

Arbitrary Keyword Arguments


In Python Arbitrary Keyword Arguments, *args, and
**kwargs can pass a variable number of arguments to a
function using special symbols. There are two special symbols:
*args in Python (Non-Keyword Arguments)
**kwargs in Python (Keyword Arguments)
Example 1: Variable length non-keywords argument
Python3
# Python program to illustrate
# *args for variable number of arguments
def myFun(*argv):
for arg in argv:
print(arg)

myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks')


Output:
Hello
Welcome
to
GeeksforGeeks
Example 2: Variable length keyword arguments
Python3
# Python program to illustrate
# *kwargs for variable number of keyword arguments

def myFun(**kwargs):
for key, value in kwargs.items():
print("%s == %s" % (key, value))

# Driver code
myFun(first='Geeks', mid='for', last='Geeks')
Output:
first == Geeks
mid == for
last == Geeks

Docstring
The first string after the function is called the Document string
or Docstring in short. This is used to describe the functionality
of the function. The use of docstring in functions is optional but
it is considered a good practice.
The below syntax can be used to print out the docstring of a
function.
Syntax: print(function_name.__doc__)
Example: Adding Docstring to the function
Python3
# A simple Python function to check
# whether x is even or odd

def evenOdd(x):
"""Function to check if the number is even or
odd"""

if (x % 2 == 0):
print("even")
else:
print("odd")

# Driver code to call the function


print(evenOdd.__doc__)
Output:
Function to check if the number is even or odd

Python Function within Functions


A function that is defined inside another function is known as
the inner function or nested function. Nested functions can
access variables of the enclosing scope. Inner functions are
used so that they can be protected from everything happening
outside the function.
Python3
# Python program to
# demonstrate accessing of
# variables of nested functions
def f1():
s = 'I love GeeksforGeeks'
def f2():
print(s)

f2()

# Driver's code
f1()
Output:
I love GeeksforGeeks
Anonymous Functions in Python
In Python, an anonymous function means that a function is
without a name. As we already know the def keyword is used to
define the normal functions and the lambda keyword is used to
create anonymous functions.
Python3
# Python code to illustrate the cube of a number
# using lambda function
def cube(x): return x*x*x

cube_v2 = lambda x : x*x*x

print(cube(7))
print(cube_v2(7))
Output:
343
343
Recursive Functions in Python
Recursion in Python refers to when a function calls itself. There
are many instances when you have to build a recursive function
to solve Mathematical and Recursive Problems.
Using a recursive function should be done with caution, as a
recursive function can become like a non-terminating loop. It is
better to check your exit statement while creating a recursive
function.
Python3
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)

print(factorial(4))
Output
24

Here we have created a recursive function to calculate the


factorial of the number. You can see the end statement for this
function is when n is equal to 0.
Return Statement in Python Function
The function return statement is used to exit from a function
and go back to the function caller and return the specified
value or data item to the caller. The syntax for the return
statement is:
return [expression_list]
The return statement can consist of a variable, an expression,
or a constant which is returned at the end of the function
execution. If none of the above is present with the return
statement a None object is returned.
Example: Python Function Return Statement
Python3
def square_value(num):
"""This function returns the square
value of the entered number"""
return num**2

print(square_value(2))
print(square_value(-4))
Output:
4
16
Pass by Reference and Pass by Value
One important thing to note is, in Python every variable name
is a reference. When we pass a variable to a function Python, a
new reference to the object is created. Parameter passing in
Python is the same as reference passing in Java.
Python3
# Here x is a new reference to same list lst
def myFun(x):
x[0] = 20

# Driver Code (Note that lst is modified


# after function call.
lst = [10, 11, 12, 13, 14, 15]
myFun(lst)
print(lst)
Output:
[20, 11, 12, 13, 14, 15]

When we pass a reference and change the received reference


to something else, the connection between the passed and
received parameters is broken. For example, consider the
below program as follows:
Python3
def myFun(x):

# After below line link of x with previous


# object gets broken. A new object is assigned
# to x.
x = [20, 30, 40]

# Driver Code (Note that lst is not modified


# after function call.
lst = [10, 11, 12, 13, 14, 15]
myFun(lst)
print(lst)
Output:
[10, 11, 12, 13, 14, 15]

Another example demonstrates that the reference link is


broken if we assign a new value (inside the function).
Python3
def myFun(x):

# After below line link of x with previous


# object gets broken. A new object is assigned
# to x.
x = 20

# Driver Code (Note that x is not modified


# after function call.
x = 10
myFun(x)
print(x)
Output:
10

Python Operators



In Python programming, Operators in general are used to perform
operations on values and variables. These are standard symbols
used for logical and arithmetic operations. In this article, we will
look into different types of Python operators.

 OPERATORS: These are the special symbols. E.g. - +, *, /,


etc.
 OPERAND: It is the value on which the operator is applied.

Types of Operators in Python

1. Arithmetic Operators
2. Comparison Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Identity Operators and Membership Operators

Arithmetic Operators in Python


Python Arithmetic operators are used to perform basic
mathematical operations like addition, subtraction,
multiplication, and division.
In Python 3.x the result of division is a floating-point while in
Python 2.x division of 2 integers was an integer. To obtain an
integer result in Python 3.x floored (// integer) is used.
Operator Description Syntax

+ Addition: adds two operands x+y

Subtraction: subtracts two


– x–y
operands

Multiplication: multiplies
* x*y
two operands

Division (float): divides the


/ x/y
first operand by the second

Division (floor): divides the


// x // y
first operand by the second

Modulus: returns the


remainder when the first
% x%y
operand is divided by the
second

Power: Returns first raised to


** x ** y
power second

Example of Arithmetic Operators in Python


Division Operators
In Python programming language Division Operators allow you
to divide two numbers and return a quotient, i.e., the first number
or number at the left is divided by the second number or number
at the right and returns the quotient.
There are two types of division operators:
1. Float division
2. Floor division
Float division
The quotient returned by this operator is always a float number,
no matter if two numbers are integers. For example:
Example: The code performs division operations and prints the
results. It demonstrates that both integer and floating-point
divisions return accurate results. For example, ’10/2′ results
in ‘5.0’, and ‘-10/2’ results in ‘-5.0’.
Python
print(5/5)
print(10/2)
print(-10/2)
print(20.0/2)
Output:
1.0
5.0
-5.0
10.0

Integer division( Floor division)


The quotient returned by this operator is dependent on the
argument being passed. If any of the numbers is float, it returns
output in float. It is also known as Floor division because, if any
number is negative, then the output will be floored. For example:
Example: The code demonstrates integer (floor) division
operations using the // in Python operators. It provides results
as follows: ’10//3′ equals ‘3’, ‘-5//2’ equals ‘-3’,
‘5.0//2′ equals ‘2.0’, and ‘-5.0//2’ equals ‘-3.0’. Integer division
returns the largest integer less than or equal to the division
result.
Pythons
print(10//3)
print (-5//2)
print (5.0//2)
print (-5.0//2)
Output:
3
-3
2.0
-3.0

Precedence of Arithmetic Operators in Python


The precedence of Arithmetic Operators in Python is as follows:
1. P – Parentheses
2. E – Exponentiation
3. M – Multiplication (Multiplication and division have the
same precedence)
4. D – Division
5. A – Addition (Addition and subtraction have the same
precedence)
6. S – Subtraction
The modulus of Python operators helps us extract the last digit/s
of a number. For example:
 x % 10 -> yields the last digit
 x % 100 -> yield last two digits
Arithmetic Operators With Addition, Subtraction,
Multiplication, Modulo and Power
Here is an example showing how different Arithmetic Operators in
Python work:
Example: The code performs basic arithmetic operations with the
values of ‘a’ and ‘b’. It adds (‘+’), subtracts (‘-‘), multiplies (‘*’),
computes the remainder (‘%’), and raises a to the power of ‘b
(**)’. The results of these operations are printed.
Python
a = 9
b = 4
add = a + b

sub = a - b

mul = a * b

mod = a % b

p = a ** b
print(add)
print(sub)
print(mul)
print(mod)
print(p)
Output:
13
5
36
1
6561

Note: Refer to Differences between / and // for some interesting


facts about these two Python operators.
Comparison of Python Operators
In Python Comparison of Relational operators compares the
values. It either returns True or False according to the condition.
Operator Description Syntax

Greater than: True if the


> left operand is greater than x>y
the right

Less than: True if the left


< operand is less than the x<y
right

Equal to: True if both


== x == y
operands are equal

Not equal to – True if


!= x != y
operands are not equal

Greater than or equal to


True if the left operand is
>= x >= y
greater than or equal to the
right

Less than or equal to True


<= if the left operand is less x <= y
than or equal to the right

= is an assignment operator and == comparison operator.


Precedence of Comparison Operators in Python
In Python, the comparison operators have lower precedence than
the arithmetic operators. All the operators within comparison
operators have the same precedence order.
Example of Comparison Operators in Python
Let’s see an example of Comparison Operators in Python.
Example: The code compares the values of ‘a’ and ‘b’ using
various comparison Python operators and prints the results. It
checks if ‘a’ is greater than, less than, equal to, not equal to,
greater than, or equal to, and less than or equal to ‘b’.
Python
a = 13
b = 33
print(a > b)
print(a < b)
print(a == b)
print(a != b)
print(a >= b)
print(a <= b)

Output
False
True
False
True
False
True

Logical Operators in Python


Python Logical operators perform Logical AND, Logical OR,
and Logical NOT operations. It is used to combine conditional
statements.
Operator Description Syntax

Logical AND: True if both


and x and y
the operands are true

Logical OR: True if either


or x or y
of the operands is true

Logical NOT: True if the


not not x
operand is false

Precedence of Logical Operators in Python


The precedence of Logical Operators in Python is as follows:
1. Logical not
2. logical and
3. logical or
Example of Logical Operators in Python
The following code shows how to implement Logical Operators in
Python:
Example: The code performs logical operations with Boolean
values. It checks if both ‘a’ and ‘b’ are true (‘and’), if at least one
of them is true (‘or’), and negates the value of ‘a’ using ‘not’.
The results are printed accordingly.
Python
a = True
b = False
print(a and b)
print(a or b)
print(not a)

Output
False
True
False

Bitwise Operators in Python


Python Bitwise operators act on bits and perform bit-by-bit
operations. These are used to operate on binary numbers.
Operator Description Syntax

& Bitwise AND x&y

| Bitwise OR x|y

~ Bitwise NOT ~x

^ Bitwise XOR x^y

>> Bitwise right shift x>>

<< Bitwise left shift x<<

Precedence of Bitwise Operators in Python


The precedence of Bitwise Operators in Python is as follows:
1. Bitwise NOT
2. Bitwise Shift
3. Bitwise AND
4. Bitwise XOR
5. Bitwise OR

Bitwise Operators in Python


Here is an example showing how Bitwise Operators in Python
work:
Example: The code demonstrates various bitwise operations with
the values of ‘a’ and ‘b’. It performs bitwise AND (&), OR
(|), NOT (~), XOR (^), right shift (>>), and left shift
(<<) operations and prints the results. These operations
manipulate the binary representations of the numbers.
Python
a = 10
b = 4
print(a & b)
print(a | b)
print(~a)
print(a ^ b)
print(a >> 2)
print(a << 2)

Output
0
14
-11
14
2
40

Assignment Operators in Python


Python Assignment operators are used to assign values to the
variables.
Operator Description Syntax

Assign the value of the


= right side of the expression x=y+z
to the left side operand

+= Add AND: Add right-side a+=b a=a+b


Operator Description Syntax

operand with left-side


operand and then assign to
left operand

Subtract AND: Subtract


right operand from left
-= a-=b a=a-b
operand and then assign to
left operand

Multiply AND: Multiply


right operand with left
*= a*=b a=a*b
operand and then assign to
left operand

Divide AND: Divide left


operand with right operand
/= a/=b a=a/b
and then assign to left
operand

Modulus AND: Takes


modulus using left and
%= a%=b a=a%b
right operands and assign
the result to left operand

Divide(floor) AND:
Divide left operand with
//= right operand and then a//=b a=a//b
assign the value(floor) to
left operand

Exponent AND: Calculate


exponent(raise power)
**= value using operands and a**=b a=a**b
assign value to left
operand

Performs Bitwise AND on


&= operands and assign value a&=b a=a&b
to left operand
Operator Description Syntax

Performs Bitwise OR on
|= operands and assign value a|=b a=a|b
to left operand

Performs Bitwise xOR on


^= operands and assign value a^=b a=a^b
to left operand

Performs Bitwise right


shift on operands and
>>= a>>=b a=a>>b
assign value to left
operand

Performs Bitwise left shift


<<= on operands and assign a <<= b a= a << b
value to left operand

Assignment Operators in Python


Let’s see an example of Assignment Operators in Python.
Example: The code starts with ‘a’ and ‘b’ both having the value
10. It then performs a series of operations: addition, subtraction,
multiplication, and a left shift operation on ‘b’. The results of each
operation are printed, showing the impact of these operations on
the value of ‘b’.
Python
a = 10
b = a
print(b)
b += a
print(b)
b -= a
print(b)
b *= a
print(b)
b <<= a
print(b)

Output
10
20
10
100
102400

Identity Operators in Python


In Python, is and is not are the identity operators both are used
to check if two values are located on the same part of the
memory. Two variables that are equal do not imply that they are
identical.
is True if the operands are identical
is not True if the operands are not identical

Example Identity Operators in Python


Let’s see an example of Identity Operators in Python.
Example: The code uses identity operators to compare variables
in Python. It checks if ‘a’ is not the same object as ‘b’ (which is
true because they have different values) and if ‘a’ is the same
object as ‘c’ (which is true because ‘c’ was assigned the value
of ‘a’).
Python
a = 10
b = 20
c = a

print(a is not b)
print(a is c)

Output
True
True

Membership Operators in Python


In Python, in and not in are the membership operators that are
used to test whether a value or variable is in a sequence.
in True if value is found in the sequence
not in True if value is not found in the sequence

Examples of Membership Operators in Python


The following code shows how to implement Membership
Operators in Python:
Example: The code checks for the presence of
values ‘x’ and ‘y’ in the list. It prints whether or not each value is
present in the list. ‘x’ is not in the list, and ‘y’ is present, as
indicated by the printed messages. The code uses
the ‘in’ and ‘not in’ Python operators to perform these checks.
Python
x = 24
y = 20
list = [10, 20, 30, 40, 50]

if (x not in list):
print("x is NOT present in given list")
else:
print("x is present in given list")

if (y in list):
print("y is present in given list")
else:
print("y is NOT present in given list")

Output
x is NOT present in given list
y is present in given list

Ternary Operator in Python


in Python, Ternary operators also known as conditional
expressions are operators that evaluate something based on a
condition being true or false. It was added to Python in version
2.5.
It simply allows testing a condition in a single line replacing the
multiline if-else making the code compact.
Syntax : [on_true] if [expression] else [on_false]
Examples of Ternary Operator in Python
The code assigns values to variables ‘a’ and ‘b’ (10 and 20,
respectively). It then uses a conditional assignment to determine
the smaller of the two values and assigns it to the variable ‘min’.
Finally, it prints the value of ‘min’, which is 10 in this case.
Python
a, b = 10, 20
min = a if a < b else b

print(min)
Output:
10

Precedence and Associativity of Operators


in Python
In Python, Operator precedence and associativity determine the
priorities of the operator.

Operator Precedence in Python


This is used in an expression with more than one operator with
different precedence to determine which operation to perform
first.
Let’s see an example of how Operator Precedence in Python
works:
Example: The code first calculates and prints the value of the
expression 10 + 20 * 30, which is 610. Then, it checks a
condition based on the values of the ‘name’ and ‘age’ variables.
Since the name is “Alex” and the condition is satisfied using the
or operator, it prints “Hello! Welcome.”
Python
expr = 10 + 20 * 30
print(expr)
name = "Alex"
age = 0

if name == "Alex" or name == "John" and age >= 2:


print("Hello! Welcome.")
else:
print("Good Bye!!")

Output
610
Hello! Welcome.
Operator Associativity in Python
If an expression contains two or more operators with the same
precedence then Operator Associativity is used to determine. It
can either be Left to Right or from Right to Left.
The following code shows how Operator Associativity in Python
works:

Example: The code showcases various mathematical operations.


It calculates and prints the results of division and multiplication,
addition and subtraction, subtraction within parentheses, and
exponentiation. The code illustrates different mathematical
calculations and their outcomes.
Python
print(100 / 10 * 10)
print(5 - 2 + 3)
print(5 - (2 + 3))
print(2 ** 3 ** 2)

Output
100.0
6
0
512

Project on Calculator
This is one of the simplest python projects for beginners. In this, we will create
a basic calculator that can perform 4 operations addition, subtraction,
multiplication, and division. We will use the concepts of functions and function
calling and returning values from functions.

Code for the simple calculator:

def addition():
print("Addition")
n = float(input("Enter the first number: "))
b = float(input("Enter the second number: "))
return n + b

def subtraction():
print("Subtraction")
n = float(input("Enter the first number: "))
b = float(input("Enter the second number: "))
return n - b

def multiplication():
print("Multiplication")
n = float(input("Enter the first number: "))
b = float(input("Enter the second number: "))
return n * b
3
def division():
print("Division")
n = float(input("Enter the first number: "))
b = float(input("Enter the second number: "))
if b != 0:
return n / b
else:
return "Error! Division by zero."

# main...
while True:
print("My calculator")
print(" Enter 'a' for addition")
print(" Enter 's' for subtraction")
print(" Enter 'm' for multiplication")
print(" Enter 'd' for division")
print(" Enter 'q' to quit")
c = input(" ")

if c == 'q':
print("Quitting...")
break
elif c == 'a':
res = addition()
print("Ans =", res)
elif c == 's':
res = subtraction()
print("Ans =", res)
elif c == 'm':
res = multiplication()
print("Ans =", res)
elif c == 'd':
res = division()
print("Ans =", res)
else:
print("Invalid input, please try again.")

You might also like