1st Unit Python Programming
1st Unit Python Programming
INTRODUCTION
Python is a general-purpose, dynamically typed, high-level, compiled and interpreted,
garbage-collected, and purely object-oriented programming language that supports procedural, object-oriented,
and functional programming.
Python is a widely used high-level, interpreted programming language. It was created by Guido van Rossum in
1991 and further developed by the Python Software Foundation. It was designed with an emphasis on code
readability, and its syntax allows programmers to express their concepts in fewer lines of code. python is a
programming language that lets you work quickly and integrate systems more efficiently.
Why Learn Python?
• Easy Syntax: Python syntax is like plain English, which allows you to focus on logic instead of
worrying about complex rules.
• Easy Career Transition: If you know any other programming language, moving to Python is super
easy.
• Project Oriented Learning: You can start making simple project while learning the python basics.
Python Syntax
To print a statement- print(“Hello World”)
Output: Hello World
• Advantages of Python:
Python Features
Python is easy to learn as compared to other programming languages. Its syntax is straightforward and
much the same as the English language. There is no use of the semicolon or curly-bracket, the indentation
defines the code block. It is the recommended programming language for beginners.
2.Object-Oriented Language
Python supports object-oriented language and concepts of classes and objects come into existence. It
supports inheritance, polymorphism, and encapsulation, etc. The object-oriented procedure helps to
programmer to write reusable code and develop applications in less code.
3.Interpreted Language
Python is an interpreted language; it means the Python program is executed one line at a time. The
advantage of being interpreted language, it makes debugging easy and portable.
4.Cross-platform Language
Python can run equally on different platforms such as Windows, Linux, UNIX, and Macintosh, etc. So, we
can say that Python is a portable language. It enables programmers to develop the software for several
competing platforms by writing a program only once.
Python is freely available for everyone. It is freely available on its official. It has a large community across
the world that is dedicatedly working towards make new python modules and functions. Anyone can
contribute to the Python community. The open-source means, "Anyone can download its source code
without paying any penny."
It provides a vast range of libraries for the various fields such as machine learning, web developer, and also
for the scripting. There are various machine learning libraries, such as Tensor flow, Pandas, Numpy, Keras,
and Pytorch, etc. Django, flask, pyramids are the popular framework for Python web development.
Expressive Language
Python can perform complex tasks using a few lines of code. A simple example, the hello world program
you simply type print("Hello World"). It will take only one line to execute, while Java or C takes multiple
lines.
application
Web development
• Python is used to create web applications quickly using frameworks and libraries.
• The Django web framework is used to build Instagram.
Desktop GUI
• Python is used to create graphical user interfaces (GUIs) using built-in tools like PyQT, wxWidgets,
and kivy.
Audio and video applications
• Python is used to create audio and video applications using libraries like PyDub and OpenCV.
• Spotify is an example of an app built using Python.
Version of python
Python has multiple versions, including Python 2.0, Python 3.0, Python 3.7, Python 3.10, and Python
3.12. The most recent version is Python 3.12.6.
Python 2.0
• Released in 2000, this version is still the basis for many Python programs
• Added new functionality to the original language
Python 3.0
• Released in late 2008, this version addressed design flaws in previous versions
• Considered the future of Python.
Python 3.7
• A major release with new features and improvements
• Provides developers with a more powerful and flexible programming environment.
Python 3.10
• Python 3.10.11 is the eleventh maintenance release of Python 3.10
• Python 3.10.10 is the newest major release of the Python programming language
• Python 3.12.6
• The latest Python version, which improves efficiency, developer experience, and performance
Other Python versions:
• Python 3.8.10 was the final regular maintenance release of the 3.8 branch
What is IDE?
Python IDEs (Integrated Development Platforms) are dedicated platforms to code, compile, run, test, and
debug python code. It is said that Python IDEs understand the code better than any text editors. They possess
an integrated build process.
• List of IDEs
• PyCharm
• IDLE
• Visual studio code
• Atom
• Sublime text
• Spyder
• PyDev
• Jupyter
• Thonny
• PyScripter
Script mode
• Script mode runs commands sequentially from a file
• It's useful for running a series of commands on a file or group of files.
Command-line tools
• Developers can create tools that execute actions with precision and speed by writing scripts that accept
command-line arguments and options.
• This automation saves time and reduces the likelihood of human error.
Simple python program example.
num1 = 15
num2 = 12
# printing values
output
Sum of 15 and 12 is 27
PYTHON BASICS
Identifiers in Python
Identifier is a user-defined name given to a variable, function, class, module, etc. The identifier is a
combination of character digits and an underscore. They are case-sensitive i.e., ‘num’ and ‘Num’ and ‘NUM’
are three different identifiers in python. It is a good programming practice to give meaningful names to
identifiers to make the code understandable.
We can also use the Python string is identifier() to check whether a string is a valid identifier or not.
keyword
• Python keywords are unique words reserved with defined meanings and functions that we can only
apply for those functions. You'll never need to import any keyword into your program because they're
permanently present.
• Python has a set of keywords that are reserved words that cannot be used as variable names, function
names, or any other identifiers
• Rules
• Keyword cant be used as identifier.
• It should be in lower case except True and False.
We can also get all the keyword names using the below code.
import keyword
print(keyword.kwlist)
Output:
Statement is an instruction for the computer to do something. Based on the instruction given system will
execute.
Types
1.simple statement
In Python, the statements are usually written in a single line and the last character of these lines is newline. To
extend the statement to one or more lines we can use braces {}, parentheses (), square [], semi-colon “;”, and
continuation character slash “\”. we can use any of these according to our requirement in the code. With the line
continuation character, we can explicitly divide a long statement into numerous lines (\).
g = "welcome\
to\
college"
print(g)
Output:
Welcome to college
a.python if statement
An expression is a combination of operators and operands that is interpreted to produce some other value. In
any programming language, an expression is evaluated as per the precedence of its operators. So that if there is
more than one operator in an expression, their precedence decides which operation will be performed first.
Types
1. Constant Expressions: These are the expressions that have constant values only.
Example:
x = 15 + 1.3
print(x)
Output
16.3
add = x + y
sub = x - y
pro = x * y
div = x / y
print(add)
print(sub)
print(pro)
print(div)
Output
52
28
480
3.3333333333333335
3. Integral Expressions: These are the kind of expressions that produce only integer results
after all computations and type conversions.
Example:
Python3
# Integral Expressions
a = 13
b = 12.0
c = a + int(b)
print(c)
Output 25
4. Floating Expressions: These are the kind of expressions which produce floating point
numbers as result after all computations and type conversions.
Example:
a=15
b=4
c=a/b
Output
3.75
5. Relational Expressions: In these types of expressions, arithmetic expressions are written on
both sides of relational operator (> , < , >= , <=). Those arithmetic expressions are evaluated
first, and then compared as per relational operator and produce a boolean output in the end.
These expressions are also called Boolean expressions.
Example:
a = 21
b = 13
c = 40
d = 37
p = (a + b) >= (c - d)
print(p)
Output
True
6.Logical Expressions: These are kinds of expressions that result in either True or False. It
basically specifies one or more conditions. For example, (10 == 9) is a condition if 10 is equal
to 9. As we know it is not correct, so it will return False. Studying logical expressions, we also
come across some logical operators which can be seen in logical expressions most often.
P = (10 == 9)
Q = (7 > 5)
# Logical Expressions
R = P and Q
S = P or Q
T = not P
print(R)
print(S)
print(T)
Output
False
True
True
7.Bitwise Expressions: These are the kind of expressions in which computations are performed
at bit level.
Example:
# Bitwise Expressions
a = 12
x = a >> 2
y = a << 1
print(x, y)
Output
3 24
c = a + (b >> 1)
print(c)
Output
22
1 Parenthesis ()[]{}
2 Exponentiation **
Multiply, Divide,
4 / * // %
Modulo
8 Bitwise XOR ^
9 Bitwise OR |
11 Equality Operators == !=
= += -
12 Assignment Operators
= /= *=
a = 10 + 3 * 4
print(a)
b = (10 + 3) * 4
print(b)
c = 10 + (3 * 4)
print(c)
Output
22
52
22
result = 3 + 5 * (2 ** 3) - 8 / 4 + (6 - 2) * 3
Exponentiation (**) has the highest precedence:
2 ** 3 evaluates to 8
Now, the expression looks like this:
result = 3 + 5 * 8 - 8 / 4 + (6 - 2) * 3
Parentheses are evaluated next (they have higher precedence than addition, subtraction,
multiplication, and division):
(6 - 2) evaluates to 4
result = 3 + 5 * 8 - 8 / 4 + 4 * 3
Multiplication (*) and division (/) come next, evaluated from left to right:
5 * 8 evaluates to 40.
8 / 4 evaluates to 2.0 (since division results in a float in Python)
4 * 3 evaluates to 12.
result = 3 + 40 - 2.0 + 12
Finally, addition (+) and subtraction (-) are evaluated from left to right:
• 3 + 40 evaluates to 43.
• 43 - 2.0 evaluates to 41.0.
• 41.0 + 12 evaluates to 53.0.
Final result:
result = 53.0
Python Variables
In python , variables are used to store data that can be referenced and manipulated during program execution. A
variable is essentially a name that is assigned to a value. Unlike many other programming languages, Python
variables do not require explicit declaration of type. The type of the variable is inferred based on the value
assigned.
Variables act as placeholders for data. They allow us to store and reuse values in our program.
Example:
x=5
print(x)
print(name)
Output
Samantha
• Variable names can only contain letters, digits and underscores (_).
2.Multiple Assignments
Python allows multiple variables to be assigned values in a single line.
Assigning the Same Value
Python allows assigning the same value to multiple variables in a single line, which can be useful for
initializing variables with the same value.
a = b = c = 100
print(a, b, c)
• Output
100 100 100
Assigning Different Values
We can assign different values to multiple variables simultaneously, making the code concise and easier to
read.
x, y, z = 1, 2.5, "Python"
print(x, y, z)
Output
1 2.5 Python
Type Casting a Variable
Type casting refers to the process of converting the value of one data type into another. Python provides
several built-in functions to facilitate casting, including int(), float() and str() among others.
Examples of Casting:
# Casting variables
s = "10" # Initially a string
n = int(s) # Cast string to integer
cnt = 5
f = float(cnt) # Cast integer to float
age = 25
s2 = str(age) # Cast integer to string
# Display results
print(n)
print(f)
print(s2)
Output
10
5.0
25
Getting the Type of Variable
In Python, we can determine the type of a variable using the type() function. This built-in function returns the
type of the object passed to it.
# Define variables with different data types
n = 42
f = 3.14
s = "Hello, World!"
li = [1, 2, 3]
d = {'key': 'value'}
bool = True
Output
• <class 'int'>
• <class 'float'>
• <class 'str'>
• <class 'list'>
• <class 'dict'>
• <class 'bool'>
Python Operators
Operators are used to perform operations on variables and values.
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators
Multiplication: 60
Division: 3.75
Floor Division: 3
Modulus: 3
Exponentiation: 50625
In Python comparison or relational operator compares the values. It either returns True or False according to
the condition.
Example
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
Python logical operator perform Logical AND, Logical OR and Logical NOT operations. It is used to
combine conditional statements.
2. logical and
3. logical or
Output
<class 'int'>
<class 'float'>
<class 'str'>
<class 'list'>
<class 'dict'>
<class 'bool'>
Python bitwise operator act on bits and perform bit-by-bit operations. These are used to operate on binary
numbers.
1. Bitwise NOT
2. Bitwise Shift
3. Bitwise AND
4. Bitwise XOR
5. Bitwise OR
print(a & b)
print(a | b)
print(~a)
print(a ^ b)
print(a >> 2)
print(a << 2)
Output
0
14
-11
14
2
40
Python assignment operator are used to assign values to the variables. This operator is used to assign the
value of the right side of the expression to the left side operand.
Example of Assignment Operators in 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
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 .
a = 10
b = 20
c=a
print(a is not b)
print(a is c)
Output
True
True
In Python, in and not in are the membership operator 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
x = 24
y = 20
if (x not in list):
print("x is NOT present in given list")
else:
if (y in list):
else:
Output
Python Data types are the classification or categorization of data items. It represents the kind of value
that tells what operations can be performed on a particular data. Since everything is an object in Python
programming, Python data types are classes and variables are instances (objects) of these classes. The
following are the standard or built-in data types in Python:
The numeric data type in Python represents the data that has a numeric value. A numeric value can be an
integer, a floating number, or even a complex number. These values are defined as python int ,python
float, python complex classes in python .
• Integers – This value is represented by int class. It contains positive or negative whole numbers
(without fractions or decimals). In Python, there is no limit to how long an integer value can be.
• Float – This value is represented by the float class. It is a real number with a floating-point
representation. It is specified by a decimal point. Optionally, the character e or E followed by a
positive or negative integer may be appended to specify scientific notation.
a=5
print(type(a))
b = 5.0
print(type(b))
c = 2 + 4j
print(type(c))
Output
<class 'int'>
<class 'float'>
<class 'complex'>
2. Sequence Data Types in Python
The sequence Data Type in Python is the ordered collection of similar or different Python data types. Sequences
allow storing of multiple values in an organized and efficient fashion. There are several sequence data types of
Python:
• Python string
• Python list
• Python tuple
# Empty list
a = []
a = [1, 2, 3]
print(a)
print(b)
Output
[1, 2, 3]
In order to access the list items refer to the index number. In Python, negative sequence indexes represent
positions from the end of the array. Instead of having to compute the offset as in List[len(List)-3], it is
enough to just write List[-3]. Negative indexing means beginning from the end, -1 refers to the last item, -2
refers to the second-last item, etc.
a = ["abc", "xyz", "lmn"]
print(a[0])
print(a[2])
print(a[-1])
print(a[-3])
Output
abc
lmn
abc
lmn
Just like a list,a tuple is also an ordered collection of Python objects. The only difference between a tuple
and a list is that tuples are immutable. Tuples cannot be modified after it is created.
In Python Data Types, tuples are created by placing a sequence of values separated by a ‘comma’ with or
without the use of parentheses for grouping the data sequence. Tuples can contain any number of elements
and of any datatype (like strings, integers, lists, etc.).
t1 = ()
t2 = ('Geeks', 'For')
Output
In order to access the tuple items refer to the index number. Use the index operator [ ] to access an item in a
tuple.
t1 = tuple([1, 2, 3, 4, 5])
print(t1[0])
print(t1[-1])
print(t1[-3])
Output
Python Data type with one of the two built-in values, True or False. Boolean objects that are equal to True
are truthy (true), and those equal to False are falsy (false). However non-Boolean objects can be evaluated in
a Boolean context as well and determined to be true or false. It is denoted by the class bool.
Example: The first two lines will print the type of the boolean values True and False, which is <class
‘bool’>. The third line will cause an error, because true is not a valid keyword in Python. Python is case-
sensitive, which means it distinguishes between uppercase and lowercase letters.
print(type(True))
print(type(False))
print(type(true))
Output:
<class 'bool'>
<class 'bool'>
In Python Data Types, set is an unordered collection of data types that is iterable, mutable, and has no
duplicate elements. The order of elements in a set is undefined though it may consist of various elements.
Sets can be created by using the built-in set() function with an iterable object or a sequence by placing the
sequence inside curly braces, separated by a ‘comma’. The type of elements in a set need not be the same,
various mixed-up data type values can also be passed to the set.
Example: The code is an example of how to create sets using different types of values, such
as strings , lists , and mixed values
s1 = set()
s1 = set("python")
Output
A dictionary in Python is a collection of data values, used to store data values like a map, unlike other Python
Data Types that hold only a single value as an element, a Dictionary holds a key: value pair. Key-value is
provided in the dictionary to make it more optimized. Each key-value pair in a Dictionary is separated by a
colon : , whereas each key is separated by a ‘comma’.
Values in a dictionary can be of any datatype and can be duplicated, whereas keys can’t be repeated and must
be immutable. The dictionary can also be created by the built-in function dict().
d = {}
print(d)
print(d1)
Output
In order to access the items of a dictionary refer to its key name. Key can be used inside square brackets.
Using get() method we can access the dictionary elements.
print(d['name'])
print(d.get(3))
Output
For
Geeks
Indentation in Python
In Python, indentation is used to define blocks of code. It tells the python interpreter that a group of
statements belongs to a specific block. All statements with the same level of indentation are considered part
of the same block. this is achieved using whitespace (spaces or tabs) at the beginning of each line.
For Example:
if 10 > 5:
print("This is true!")
Output
This is true!
I am tab indentation
I have no indentation
Comments
#This is a comment
print("Hello, World!")
Multi-Line Comments
Python does not provide the facility for multi-line comments. However, there are indeed many ways to create
multi-line comments.
In Python, we may use hashtags (#) multiple times to construct multiple lines of comments. Every line with a
(#) before it will be regarded as a single-line comment.
Code
1. # it is a
2. # comment
3. # extending to multiple lines
In this case, each line is considered a comment, and they are all omitted.
Console input() and output()
In Python, the input() function allows you to capture user input from the keyboard, while you can use the
print() function to display output to the console. These built-in functions allow for basic user interaction in
Python scripts, enabling you to gather data and provide feedback.
Example:
Rahul
My Name is Rahul
In Implicit type conversion of data types in Python, the Python interpreter automatically converts one data
type to another without any user involvement.
x = 10
print("x is of type:",type(x))
y = 10.6
print("y is of type:",type(y))
z=x+y
print(z)
print("z is of type:",type(z))
o/p
In Explicit Type Conversion, users convert the data type of an object to required data type.
We use the built-in functions like int(),float(),str() etc to perform explicit type conversion.
This type of conversion is also called typecasting because the user casts (changes) the data type of the
objects.
num_string = '12'
num_integer = 23
num_string = int(num_string)
print("Sum:",num_sum)
o/p
Sum: 35
Libraries in Python
A Python library is a collection of related modules. It contains bundles of code that can be used repeatedly in
different programs. It makes Python Programming simpler and convenient for the programmer. As we don’t
need to write the same code again and again for different programs.
1. TensorFlow: This library was developed by Google in collaboration with the Brain Team. It is an
open-source library used for high-level computations. It is also used in machine learning and deep
learning algorithms. It contains a large number of tensor operations. Researchers also use this Python
library to solve complex computations in Mathematics and Physics.
2. Matplotlib: This library is responsible for plotting numerical data. And that’s why it is used in data
analysis. It is also an open-source library and plots high-defined figures like pie charts, histograms,
scatterplots, graphs, etc.
3. Pandas: Pandas are an important library for data scientists. It is an open-source machine learning
library that provides flexible high-level data structures and a variety of analysis tools. It eases data
analysis, data manipulation, and cleaning of data. Pandas support operations like Sorting, Re-
indexing, Iteration, Concatenation, Conversion of data, Visualizations, Aggregations, etc.
4. Numpy: The name “Numpy” stands for “Numerical Python”. It is the commonly used library. It is a
popular machine learning library that supports large matrices and multi-dimensional data. It consists
of in-built mathematical functions for easy computations. Even libraries like TensorFlow use Numpy
internally to perform several operations on tensors. Array Interface is one of the key features of this
library.
5. SciPy: The name “SciPy” stands for “Scientific Python”. It is an open-source library used for high-
level scientific computations. This library is built over an extension of Numpy. It works with Numpy
to handle complex computations. While Numpy allows sorting and indexing of array data, the
numerical data code is stored in SciPy. It is also widely used by application developers and engineers.
6. Scrapy: It is an open-source library that is used for extracting data from websites. It provides very
fast web crawling and high-level screen scraping. It can also be used for data mining and automated
testing of data.
7. Scikit-learn: It is a famous Python library to work with complex data. Scikit-learn is an open-source
library that supports machine learning. It supports variously supervised and unsupervised algorithms
like linear regression, classification, clustering, etc. This library works in association with Numpy
and SciPy.
8. PyGame: This library provides an easy interface to the Standard Directmedia Library (SDL)
platform-independent graphics, audio, and input libraries. It is used for developing video games u
9.PyTorch: PyTorch is the largest machine learning library that optimizes tensor computations. It has
rich APIs to perform tensor computations with strong GPU acceleration. It also helps to solve application
issues related to neural networks.
10. PyBrain: The name “PyBrain” stands for Python Based Reinforcement Learning, Artificial
Intelligence, and Neural Networks library. It is an open-source library built for beginners in the
field of Machine Learning. It provides fast and easy-to-use algorithms for machine learning tasks.
It is so flexible and easily understandable and that’s why is really helpful for developers that are
new in research fields.
A = 16
B = 3.14
print(sqrt(A))
print(sin(B))
Output
4.0
0.0015926529164868282
Python control flow. Control flow is the order in which individual statements, instructions, or
function calls are executed or evaluated.
Types
1.sequential:By default line by line will execute.
2.selection:used for making decision and branching.
Ex: conditional statement
3.repetation:used to perform repeated piece of code multiple times. Ex: looping statement
is the simplest form of a conditional statement. It executes a block of code if the given condition is true.
Example:
age = 20
print("Eligible to vote.")
It allows us to specify a block of code that will execute if the condition(s) associated with an if or elif
statement evaluates to False. Else block provides a way to handle all other cases that don't meet the specified
conditions.
Example:
age = 10
else:
Output
elif Statement
elif statement in Python stands for "else if." It allows us to check multiple conditions , providing a way to
execute different blocks of code based on which condition is true. Using elif statements makes our code more
readable and efficient by eliminating the need for multiple nested if statements.
Example:
age = 25
print("Child.")
print("Teenager.")
print("Young adult.")
else:
print("Adult.")
Output
Young adult.
Nested if..else Conditional Statements in Python
age = 70
is_member = True
if is_member:
else:
else:
Output
Loops in Python
It is used to execute a block of statements repeatedly until a given condition is satisfied. When the condition
becomes false, the line immediately after the loop in the program is executed.
while expression:
statement(s)
cnt = 0
cnt = cnt + 1
print("Hello world")
Output
Hello Geek
Hello Geek
Hello Geek
used for sequential traversalFor example: traversing a list or string or array etc.
For Loop Syntax:
n=4
print(i)
Output
Python programming language allows to use one loop inside another loop which is called nested loop.
x = [1, 2]
y = [4, 5]
for i in x:
for j in y:
print(i, j)
Output:
14
15
24
25
Control statements modify the loop’s execution flow. Python provides three primary control
statements: continue, break, and pass.
break Statement
The is used to exit the loop prematurely when a certain condition is met.
for i in range(10):
if i == 5:
break
print(i)
Output
continue Statement
for i in range(10):
if i % 2 == 0:
continue
print(i)
Output
pass Statement
for i in range(5):
if i == 3:
pass
print(i)
Output
The range() function returns a sequence of numbers, starting from 0 by default, and increments
by 1 (by default), and stops before a specified number.
Syntax
Parameter Description
Example
Create a sequence of numbers from 3 to 5, and print each item in the sequence:
x = range(3, 6)
for n in x:
print(n)
o/p
3
4
5
x = range(3, 20, 2)
for n in x:
print(n)
o/p
3
5
7
9
11
13
15
19
exit() Function
Ex:
1. for x in range(3,10)
print(x+20)
exit()
o/p 23
2. print(“python programming”)
exit()
print(“basic version ”)
Python function
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.
• Built-in library function: These are standard function in Python that are available to use.
• 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.
def fun():
print("Welcome to GFG")
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.
def fun():
print("Welcome to GFG")
fun()
Output:
Welcome to GFG
Parameter: In Python, a parameter is a variable that receives data passed into a function.
Arguments: In Python, an argument is a value that's passed to a function when it's called.
Syntax
Ex:
abc()
Arguments are the values passed inside the parenthesis of the function call. A function can have any number of
arguments separated by a comma.
def evenOdd(x):
if (x % 2 == 0):
print("even")
else:
print("odd")
evenOdd(2)
evenOdd(3)
Output:
even
odd
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
o/p:
I am from Sweden
I am from India
I am from Norway
I am from Brazil
• Default argument
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.
# Python program to demonstrate
# default arguments
def myFun(x, y=50):
print("x: ", x)
print("y: ", y)
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.
print(firstname, lastname)
# Keyword arguments
student(firstname='Geeks', lastname='Practice')
student(lastname='Practice', firstname='Geeks')
Output:
Geeks Practice
Geeks Practice
Recursion function.
Recursive functions are functions that calls itself. It is always made up of 2 portions, the base case and the
recursive case.
Example:
def fibonacci(n):
# Base cases
if n == 0:
return 0
elif n == 1:
return 1
# Recursive case
else:
# Example usage
print(fibonacci(10))
Output
55
A return statement is used to end the execution of the function call and it “returns” the value of the expression
following the return keyword to the caller. The statements after the return statements are not executed
Example:
return a + b
def is_true(a):
# returning boolean of a
return bool(a)
# calling function
res = add(2, 3)
print(res)
res = is_true(2<5)
print(res)
Output
True
Errors are problems in a program that causes the program to stop its execution. On the other hand, exceptions
are raised when some internal events change the program’s normal flow.
Types of error
When the proper syntax of the language is not followed then a syntax error is thrown.
amount = 10000
# check that You are eligible to
if(amount>2999)
Output:
if(a<3):
print("gfg")
Output
A logical error in Python, or in any programming language, is a type of bug that occurs when a program runs
without crashing but produces incorrect or unintended results. Logical errors are mistakes in the program’s logic
that lead to incorrect behavior or output, despite the syntax being correct.
1. No Syntax Error: The code runs successfully without any syntax errors.
2. Unexpected Output: The program produces output that is different from what is expected.
3. Difficult to Detect: Logical errors can be subtle and are often harder to identify and fix compared to
syntax errors because the program appears to run correctly.
4. Varied Causes: They can arise from incorrect assumptions, faulty logic, improper use of operators, or
incorrect sequence of instructions.
total = 0
Analysis
• Expected Output: The average of the numbers [10, 20, 30, 40, 50] should be 30.
• Actual Output: The program will output The average is: 29.0.
TypeError It occurs when a function and operation are applied in an incorrect type.
Python Exception Handling handles errors that occur during the execution of a program. Exception handling
allows to respond to the error, instead of crashing the running program.
try:
# Code that might raise an exception
except SomeException:
# Code to handle the exception
else:
# Code to run if no exception occurs
finally:
• try Block: try block lets us test a block of code for errors. Python will “try” to execute the code in this
block. If an exception occurs, execution will immediately jump to the except block.
• except Block: except block enables us to handle the error or exception. If the code inside the try block
throws an error, Python jumps to the except block and executes it. We can handle specific exceptions or
use a general except to catch all exceptions.
• else Block: else block is optional and if included, must follow all except blocks. The else block runs
only if no exceptions are raised in the try block. This is useful for code that should execute if the try
block succeeds.
• finally Block: finally block always runs, regardless of whether an exception occurred or not. It is
typically used for cleanup operations (closing files, releasing resources).
Example:
try:
n=0
res = 100 / n
except ZeroDivisionError:
except ValueError:
else:
finally:
print("Execution complete.")
Output
Execution complete.
Explanation:
try block asks for user input and tries to divide 100 by the input number.
finally block runs regardless of the outcome, indicating the completion of execution.
Example:
try:
x = int("str") # This will cause ValueError
#inverse
inv = 1 / x
except ValueError:
print("Not Valid!")
except ZeroDivisionError:
print("Zero has no inverse!")
Output
Not Valid!