Python project (1)
Python project (1)
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.
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.
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: -
Example: -
# A simple Python function
def fun():
print("Welcome to GFG")
Example: -
# A simple Python function
def fun():
print("Welcome to GFG")
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
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")
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)
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)
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")
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
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
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
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.
1. Arithmetic Operators
2. Comparison Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Identity Operators and Membership Operators
Multiplication: multiplies
* x*y
two operands
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
Output
False
True
False
True
False
True
Output
False
True
False
| Bitwise OR x|y
~ Bitwise NOT ~x
Output
0
14
-11
14
2
40
Divide(floor) AND:
Divide left operand with
//= right operand and then a//=b a=a//b
assign the value(floor) to
left operand
Performs Bitwise OR on
|= operands and assign value a|=b a=a|b
to left operand
Output
10
20
10
100
102400
print(a is not b)
print(a is c)
Output
True
True
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
print(min)
Output:
10
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:
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.
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.")