The document provides an overview of how to learn the basics of Python programming, including identifiers, data types, decisions, looping, functions, modules, and file handling. It begins with an introduction to the author and their background/expertise. It then covers Python identifiers and reserved words, basic data types like numbers, strings, lists, tuples and dictionaries. It discusses decision making statements like if/else and loops like for/while. It introduces functions and modules for organizing code. Finally, it covers opening, writing and closing files in Python. The document aims to provide everything needed to get started with Python programming.
This document outlines the objectives and content of the course GE3151 Problem Solving and Python Programming. The course is intended to teach students the basics of algorithmic problem solving using Python. It covers topics like computational thinking, Python data types, control flow, functions, strings, lists, tuples, dictionaries, files and modules. The course contains 5 units that will teach students how to define problems, develop algorithms, implement solutions in Python using conditionals, loops, functions and data structures, perform input/output with files and use modules and packages.
This document provides an introduction and overview of the Python programming language course CSE 120 handled by G.Gandhi Jaba Kumar. It discusses that Python is an interpreted, object-oriented, and interactive programming language used for web development, software development, mathematics, and system scripting. The document then covers Python syntax including indentation, comments, keywords, variables, data types, operators, and basic programming concepts like conditionals and loops. It provides examples to illustrate Python code and best practices.
Python is an interpreted, interactive, object-oriented programming language. It has a simple syntax and is used for rapid application development. Python supports procedural, object-oriented, and functional programming. It has a large standard library and can connect to existing components. Python is easy to read and maintain due to its clear syntax and structure. It is also portable and has broad library support.
Introduction to Python for Data Science and Machine Learning ParrotAI
This document provides an introduction and overview of Python for data science and machine learning. It covers basics of Python including what Python is, its features, why it is useful for data science. It also discusses installing Python, using the IDLE and Jupyter Notebook environments. The document then covers Python basics like variables, data types, operators, decision making and loops. Finally, it discusses collection data types like lists, tuples and dictionaries and functions in Python.
This document provides an introduction to the Python programming language. It discusses Python language elements like literals, keywords, identifiers, operators, expressions, statements, and comments. It also covers Python data types, variables, printing values, and how to write and run a simple Python program. The document aims to explain Python concepts in a step-by-step manner to help readers learn the basics of the Python language.
The document discusses Python programming concepts such as data types, variables, operators, and input/output. It provides examples of Python code and explains key features like:
- Python supports several data types including integers, floats, booleans, strings, and lists.
- Variables store and label values that can be of different data types. Variables are created using names.
- Operators like arithmetic, comparison, and logical operators are used to manipulate values.
- User input and output is handled through functions like print() and input().
- Comments, indentation, and quotation are syntax elements in Python code.
Python is a general-purpose programming language that is highly readable. It uses English keywords and has fewer syntactical constructions than other languages. Python supports object-oriented, interactive, and procedural programming. It has various data types like numbers, strings, lists, tuples and dictionaries. Python uses constructs like if/else, for loops, functions and classes to control program flow and structure code.
This presentation is a great resource for zero-based Python programmers who wants to learn Python 3. This course includes brief history of Python and familiarity of its basic syntax.
Python Course In Ghaziabad. Scode network is best training institute for Python which provides Online Python course with complete certificates at an affordable price.
The document provides an introduction to Python programming. It discusses that Python is a high-level, interpreted, object-oriented, and general purpose programming language. It can be used for web development, scientific computing, desktop applications, and more. The document then covers Python basics like data types, variables, literals, operators, control flow statements, functions, modules and packages. It also discusses installing Python on Windows and writing the first Python program.
This document provides an overview of the Python programming language. It describes what Python is, how it can be used for web development, software development, mathematics, and system scripting. It also covers Python's syntax features like indentation, variables, comments, and data types. Key reasons for using Python include its ability to run on different platforms, simple English-like syntax, and support for procedural, object-oriented, and functional programming.
After the end of lesson you will be able to learn Python basics-What Python is? Its releases. Where we can use Python? Python Features. Tokens, comments variables etc... In out next PPT you will learn how to input and get output in Python
This document provides a quick syntax guide for Python 3.x. It describes Python as a simple, powerful, and open source programming language that is dynamic, object-oriented, and interpreted. The guide covers Python's history and uses, data types, operators, conditional and loop statements, functions, modules, classes, and exceptions. It aims to give beginners an overview of Python's key features and syntax.
Excellence Technology is one of the top reputed ISO certified software development and industrial training company in Mohali. Excellence Technology is a professional company providing web education and advanced 6 months and weeks industrial training in Mohali and is also a leading software development company.
Guido van Rossum emphasized the importance of code readability in Python. He introduced significant whitespace as a core feature of the language, aiming to enforce a clean and readable code structure. This emphasis on readability is evident in the presentation's mention of Python's design philosophy that highlights code readability.Van Rossum emphasized the importance of Python in enabling developers to write clear and logical code, which is scalable for both small and large-scale projects. The presentation mentions Python's language constructs and object-oriented approach designed to assist programmers in achieving this goal.
Though not explicitly attributed to van Rossum, Python's dynamically typed nature and built-in garbage collection contribute to its ease of use and simplification of memory management, reflecting the language's user-centric design principles.
Overall, Guido van Rossum's vision and design choices for Python resonate with the attributes and philosophies outlined in the presentation. His influence is seen in Python's core principles, which prioritize readability, versatility, and ease of use for programmers.
Python is a cross-platform programming language that can run on Windows, macOS, Linux, and other platforms. It is free and open-source. While most modern operating systems come with Python pre-installed, it is generally recommended to install the latest version separately. The Thonny IDE is a simple Python IDE that bundles the latest Python version, so it can run Python programs without requiring a separate Python installation. Thonny has features like an easy-to-use debugger and code completion that make it suitable for beginners learning Python.
an insightful lecture on "Loads on Structure," where we delve into the fundamental concepts and principles of load analysis in structural engineering. This presentation covers various types of loads, including dead loads, live loads, as well as their impact on building design and safety. Whether you are a student, educator, or professional in the field, this lecture will enhance your understanding of ensuring stability. Explore real-world examples and best practices that are essential for effective engineering solutions.
A lecture by Eng. Wael Almakinachi, M.Sc.
Welcome to the May 2025 edition of WIPAC Monthly celebrating the 14th anniversary of the WIPAC Group and WIPAC monthly.
In this edition along with the usual news from around the industry we have three great articles for your contemplation
Firstly from Michael Dooley we have a feature article about ammonia ion selective electrodes and their online applications
Secondly we have an article from myself which highlights the increasing amount of wastewater monitoring and asks "what is the overall" strategy or are we installing monitoring for the sake of monitoring
Lastly we have an article on data as a service for resilient utility operations and how it can be used effectively.
Ad
More Related Content
Similar to Python Programming for problem solving.pptx (20)
The document discusses Python programming concepts such as data types, variables, operators, and input/output. It provides examples of Python code and explains key features like:
- Python supports several data types including integers, floats, booleans, strings, and lists.
- Variables store and label values that can be of different data types. Variables are created using names.
- Operators like arithmetic, comparison, and logical operators are used to manipulate values.
- User input and output is handled through functions like print() and input().
- Comments, indentation, and quotation are syntax elements in Python code.
Python is a general-purpose programming language that is highly readable. It uses English keywords and has fewer syntactical constructions than other languages. Python supports object-oriented, interactive, and procedural programming. It has various data types like numbers, strings, lists, tuples and dictionaries. Python uses constructs like if/else, for loops, functions and classes to control program flow and structure code.
This presentation is a great resource for zero-based Python programmers who wants to learn Python 3. This course includes brief history of Python and familiarity of its basic syntax.
Python Course In Ghaziabad. Scode network is best training institute for Python which provides Online Python course with complete certificates at an affordable price.
The document provides an introduction to Python programming. It discusses that Python is a high-level, interpreted, object-oriented, and general purpose programming language. It can be used for web development, scientific computing, desktop applications, and more. The document then covers Python basics like data types, variables, literals, operators, control flow statements, functions, modules and packages. It also discusses installing Python on Windows and writing the first Python program.
This document provides an overview of the Python programming language. It describes what Python is, how it can be used for web development, software development, mathematics, and system scripting. It also covers Python's syntax features like indentation, variables, comments, and data types. Key reasons for using Python include its ability to run on different platforms, simple English-like syntax, and support for procedural, object-oriented, and functional programming.
After the end of lesson you will be able to learn Python basics-What Python is? Its releases. Where we can use Python? Python Features. Tokens, comments variables etc... In out next PPT you will learn how to input and get output in Python
This document provides a quick syntax guide for Python 3.x. It describes Python as a simple, powerful, and open source programming language that is dynamic, object-oriented, and interpreted. The guide covers Python's history and uses, data types, operators, conditional and loop statements, functions, modules, classes, and exceptions. It aims to give beginners an overview of Python's key features and syntax.
Excellence Technology is one of the top reputed ISO certified software development and industrial training company in Mohali. Excellence Technology is a professional company providing web education and advanced 6 months and weeks industrial training in Mohali and is also a leading software development company.
Guido van Rossum emphasized the importance of code readability in Python. He introduced significant whitespace as a core feature of the language, aiming to enforce a clean and readable code structure. This emphasis on readability is evident in the presentation's mention of Python's design philosophy that highlights code readability.Van Rossum emphasized the importance of Python in enabling developers to write clear and logical code, which is scalable for both small and large-scale projects. The presentation mentions Python's language constructs and object-oriented approach designed to assist programmers in achieving this goal.
Though not explicitly attributed to van Rossum, Python's dynamically typed nature and built-in garbage collection contribute to its ease of use and simplification of memory management, reflecting the language's user-centric design principles.
Overall, Guido van Rossum's vision and design choices for Python resonate with the attributes and philosophies outlined in the presentation. His influence is seen in Python's core principles, which prioritize readability, versatility, and ease of use for programmers.
Python is a cross-platform programming language that can run on Windows, macOS, Linux, and other platforms. It is free and open-source. While most modern operating systems come with Python pre-installed, it is generally recommended to install the latest version separately. The Thonny IDE is a simple Python IDE that bundles the latest Python version, so it can run Python programs without requiring a separate Python installation. Thonny has features like an easy-to-use debugger and code completion that make it suitable for beginners learning Python.
an insightful lecture on "Loads on Structure," where we delve into the fundamental concepts and principles of load analysis in structural engineering. This presentation covers various types of loads, including dead loads, live loads, as well as their impact on building design and safety. Whether you are a student, educator, or professional in the field, this lecture will enhance your understanding of ensuring stability. Explore real-world examples and best practices that are essential for effective engineering solutions.
A lecture by Eng. Wael Almakinachi, M.Sc.
Welcome to the May 2025 edition of WIPAC Monthly celebrating the 14th anniversary of the WIPAC Group and WIPAC monthly.
In this edition along with the usual news from around the industry we have three great articles for your contemplation
Firstly from Michael Dooley we have a feature article about ammonia ion selective electrodes and their online applications
Secondly we have an article from myself which highlights the increasing amount of wastewater monitoring and asks "what is the overall" strategy or are we installing monitoring for the sake of monitoring
Lastly we have an article on data as a service for resilient utility operations and how it can be used effectively.
PRIZ Academy - Functional Modeling In Action with PRIZ.pdfPRIZ Guru
This PRIZ Academy deck walks you step-by-step through Functional Modeling in Action, showing how Subject-Action-Object (SAO) analysis pinpoints critical functions, ranks harmful interactions, and guides fast, focused improvements. You’ll see:
Core SAO concepts and scoring logic
A wafer-breakage case study that turns theory into practice
A live PRIZ Platform demo that builds the model in minutes
Ideal for engineers, QA managers, and innovation leads who need clearer system insight and faster root-cause fixes. Dive in, map functions, and start improving what really matters.
This slide deck presents a detailed overview of the 2025 survey paper titled “A Survey of Personalized Large Language Models” by Liu et al. It explores how foundation models like GPT and LLaMA can be personalized to better reflect user-specific needs, preferences, and behaviors.
The presentation is structured around a 3-level taxonomy introduced in the paper:
Input-Level Personalization (e.g., user-profile prompting, memory retrieval)
Model-Level Personalization (e.g., LoRA, PEFT, adapters)
Objective-Level Personalization (e.g., RLHF, preference alignment)
How to Buy Snapchat Account A Step-by-Step Guide.pdfjamedlimmk
Scaling Growth with Multiple Snapchat Accounts: Strategies That Work
Operating multiple Snapchat accounts isn’t just a matter of logging in and out—it’s about crafting a scalable content strategy. Businesses and influencers who master this can turn Snapchat into a lead generation engine.
Key strategies include:
Content Calendars for Each Account – Plan distinct content buckets and themes per account to avoid duplication and maintain variety.
Geo-Based Content Segmentation – Use location-specific filters and cultural trends to speak directly to a region's audience.
Audience Mapping – Tailor messaging for niche segments: Gen Z, urban youth, gamers, shoppers, etc.
Metrics-Driven Storytelling – Use Snapchat Insights to monitor what type of content performs best per account.
Each account should have a unique identity but tie back to a central brand voice. This balance is crucial for brand consistency while leveraging the platform’s creative freedoms.
How Agencies and Creators Handle Bulk Snapchat Accounts
Digital agencies and creator networks often manage dozens—sometimes hundreds—of Snapchat accounts. The infrastructure to support this requires:
Dedicated teams for each cluster of accounts
Cloud-based mobile device management (MDM) systems
Permission-based account access for role clarity
Workflow automation tools (Slack, Trello, Notion) for content coordination
This is especially useful in verticals such as music promotion, event marketing, lifestyle brands, and political outreach, where each campaign needs targeted messaging from different handles.
The Legality and Risk Profile of Bulk Account Operations
If your aim is to operate or acquire multiple Snapchat accounts, understand the risk thresholds:
Personal Use (Low Risk) – One or two accounts for personal and creative projects
Business Use (Medium Risk) – Accounts with aligned goals, managed ethically
Automated Bulk Use (High Risk) – Accounts created en masse or used via bots are flagged quickly
Snapchat uses advanced machine learning detection for unusual behavior, including:
Fast switching between accounts from the same IP
Identical Snap stories across accounts
Rapid follower accumulation
Use of unverified devices or outdated OS versions
To stay compliant, use manual operations, vary behavior, and avoid gray-market account providers.
Smart Monetization Through Multi-Account Snapchat Strategies
With a multi-account setup, you can open doors to diversified monetization:
Affiliate Marketing – Niche accounts promoting targeted offers
Sponsored Content – Brands paying for story placement across multiple profiles
Product Launch Funnels – Segment users by interest and lead them to specific landing pages
Influencer Takeovers – Hosting creators across multiple themed accounts for event buzz
This turns your Snapchat network into a ROI-driven asset instead of a time sink.
Conclusion: Build an Ecosystem, Not Just Accounts
When approached correctly, multiple Snapchat accounts bec
In modern aerospace engineering, uncertainty is not an inconvenience — it is a defining feature. Lightweight structures, composite materials, and tight performance margins demand a deeper understanding of how variability in material properties, geometry, and boundary conditions affects dynamic response. This keynote presentation tackles the grand challenge: how can we model, quantify, and interpret uncertainty in structural dynamics while preserving physical insight?
This talk reflects over two decades of research at the intersection of structural mechanics, stochastic modelling, and computational dynamics. Rather than adopting black-box probabilistic methods that obscure interpretation, the approaches outlined here are rooted in engineering-first thinking — anchored in modal analysis, physical realism, and practical implementation within standard finite element frameworks.
The talk is structured around three major pillars:
1. Parametric Uncertainty via Random Eigenvalue Problems
* Analytical and asymptotic methods are introduced to compute statistics of natural frequencies and mode shapes.
* Key insight: eigenvalue sensitivity depends on spectral gaps — a critical factor for systems with clustered modes (e.g., turbine blades, panels).
2. Parametric Uncertainty in Dynamic Response using Modal Projection
* Spectral function-based representations are presented as a frequency-adaptive alternative to classical stochastic expansions.
* Efficient Galerkin projection techniques handle high-dimensional random fields while retaining mode-wise physical meaning.
3. Nonparametric Uncertainty using Random Matrix Theory
* When system parameters are unknown or unmeasurable, Wishart-distributed random matrices offer a principled way to encode uncertainty.
* A reduced-order implementation connects this theory to real-world systems — including experimental validations with vibrating plates and large-scale aerospace structures.
Across all topics, the focus is on reduced computational cost, physical interpretability, and direct applicability to aerospace problems.
The final section outlines current integration with FE tools (e.g., ANSYS, NASTRAN) and ongoing research into nonlinear extensions, digital twin frameworks, and uncertainty-informed design.
Whether you're a researcher, simulation engineer, or design analyst, this presentation offers a cohesive, physics-based roadmap to quantify what we don't know — and to do so responsibly.
Key words
Stochastic Dynamics, Structural Uncertainty, Aerospace Structures, Uncertainty Quantification, Random Matrix Theory, Modal Analysis, Spectral Methods, Engineering Mechanics, Finite Element Uncertainty, Wishart Distribution, Parametric Uncertainty, Nonparametric Modelling, Eigenvalue Problems, Reduced Order Modelling, ASME SSDM2025
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)ijflsjournal087
Call for Papers..!!!
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
June 21 ~ 22, 2025, Sydney, Australia
Webpage URL : https://inwes2025.org/bmli/index
Here's where you can reach us : [email protected] (or) [email protected]
Paper Submission URL : https://inwes2025.org/submission/index.php
Jacob Murphy Australia - Excels In Optimizing Software ApplicationsJacob Murphy Australia
In the world of technology, Jacob Murphy Australia stands out as a Junior Software Engineer with a passion for innovation. Holding a Bachelor of Science in Computer Science from Columbia University, Jacob's forte lies in software engineering and object-oriented programming. As a Freelance Software Engineer, he excels in optimizing software applications to deliver exceptional user experiences and operational efficiency. Jacob thrives in collaborative environments, actively engaging in design and code reviews to ensure top-notch solutions. With a diverse skill set encompassing Java, C++, Python, and Agile methodologies, Jacob is poised to be a valuable asset to any software development team.
1. Mrs. M. Nisha
Assistant Professor
Department of CSE
Akshaya College of Engineering and
Technology
Python for Everyone
2. a general purpose, interpreted, high-level
programming
Python is
language.
It was created by Guido Van Rossum in1991.
It was designed with code readability and its syntax allows the
programmers to express the code with fewer lines of code.
Python programming relies on indentation using white space, to
define the scope of loops and functions.
Introduction
3. Introduction
Python is a popular programming language for several reasons:
1.Readability and Simplicity: Python's syntax is clear and easy to understand
2.Versatility: Used in various fields, including web development, data analysis, machine
learning, artificial intelligence, scientific computing, and automation.
3.Extensive Libraries and Frameworks: Django and Flask for web development,
NumPy and pandas for data analysis, TensorFlow and PyTorch for ML, and many more.
4.Community Support: This means extensive documentation, and numerous forums
5.Cross-Platform Compatibility: It can run on various operating systems, such as
Windows, macOS, and Linux, without requiring significant changes to the code.
6.Integration Capabilities: Python can easily integrate with other languages and
technologies
7.Rapid Development: Python allows for rapid development and prototyping due to its
high-level nature and the availability of extensive libraries.
8.Popularity in Data Science and AI: Python is the go-to language for data science, ML,
and AI due to its powerful libraries and frameworks that simplify complex tasks.
8. Python Interpreter Modes
Python Interpreter
Python is an interpreted object-oriented programming language.
Interpreter is a translator, which translates the given code line-by-line into
machine readable bytecodes. If any error occurs, it stops the translation until
the error is fixed.
Compiler is a translator, which translates the entire code as whole into
machine readable bytecode and displays all the error during compilation.
9. Python Interpreter Modes
Python Interpreter Modes
Python Interpreter consists of two modes,
* Interactive mode
* Script mode
Both are the two primary ways to run the Python code.
Both modes play essential roles in Python development
10. Python Interactive Mode
Python Interactive Mode
Python Interactive mode is used for executing single line or single block of
code, which provides immediate feedback for each statement.
Advantages
It is convenient for writing short lines of code.
It helps the beginners to understand the execution of the code.
12. Python Script Mode
Python Script Mode
Python script mode is used for executing multiple blocks of code.
Script files are stored using the extension “.py”
Advantages
It helps to provide proper and organization for complex projects.
Code reusability
14. Comments
Python comments are the non-executable piece of code that are igorned by
the interpreter at the time of program execution.
In python, comments are represented with the symbol “#”.
Comments enhance the readability of code, that helps the programmers to
understand the meaning of the code.
Types of Comments
Single-line comments
Multi-line comments
16. Comments
Multi-line Comments
Python does not really support multi-line comments.
To include it, we can either use “#’ for each line or multi-line string in the
code.
17. Identifiers and Keywords
Identifiers:-
Identifiers are the user-defined name given to a variables, functions, methods.
It can start with an alphabets (A to Z) or underscore.
It is always good to provide meaningful name to the identifiers for better
understanding about the code.
Rules for Naming Identifiers:-
Identifiers cannot be a reserved python keywords.
They are case sensitive. (Eg:- Uppercase & Lowercase identifiers are distinct)
Identifiers contain digits (0 to 9) but should not start with digit.
18. Identifiers and Keywords
Rules for Naming Identifiers:-
Identifiers does not allow punctuations like %, $, @, etc.
It does not contain any other special characters other than underscore(_).
If identifier starts with _ symbol, then it indicates that it is private.
If identifier starts with (two under score symbols) indicating that
strongly private identifier.
If an identifier starts and ends with two underscore symbols then it is called
as magic methods.
19. Identifiers and Keywords
Examples for Valid Identifiers:-
ab10c, abc_DE, _, _abc, _1_var, abc
Examples for Invalid Identifiers:-
123total, 12Name, name$, total-mark, continue, var#1, !var1
20. Identifiers and Keywords
Keywords:-
Python Keywords are the pre-defined and reserved words which have
a
special meaning.
Keywords cannot be used as identifiers and function name.
It is case sensitive.
In python there is an inbuilt keyword module, which provides kwlist attribute
to display the list of python keywords.
24. Data Types
Numeric Data Type:-
Numeric data type represents the numeric values such as integer, float and
complex data.
Integer:-
Integer can be positive or negative whole number without any fractions or
decimals.
Eg:-
10, 1000, -23
25. Data Types
Integer values can be represented in following ways
-Decimal form (Base 10) - 0 to 9
-Binary form (Base 2) - 0, 1, literals prefix starts with 0B or 0b
-Octal form (Base 8) - 0 to 7, literals prefix starts with 0o or 0O
- Hexadecimal (Base 16) - 0 to 9, A to F, literals prefix starts with 0X or 0x
Numeric Data Type:-
Integer:-
Eg:-
26. Data Types
Float values are represented by a decimal point value.
- Eg:- 2.5, -28.98, etc
The floating point values can also represented by a exponential form.
- Eg:- 1.2e3, etc
Numeric Data Type:-
Float:-
Eg:-
27. Data Types
A complex number is represented by a complex class.
It is specified as (real part) + (imaginary part)j. For example:- – 2+3j
Numeric Data Type:-
Complex Number:-
Eg:
28. Data Types
Boolean Data Type:-
Boolean data type is represented by the boolean values.
Boolean values are represented by True (1), False (0)
Eg:-
29. Data Types
Sequence Data Type:-
Sequence data type is the ordered collection of similar or different data types.
In Python, the sequence data types are as follows,
- String
- List
- Tuple
String:-
String is a sequence of characters enclosed within single quotes,
double quotes or triple quotes.
Eg:- ‘Hello’, “Hello World”, '''hai''', """hiiii"""
33. Data Types
Slicing of String:-
String slicing is a piece of string obtained from the sequence of string.
Slicing have been performed using the operator “[ : ]”.
34. Data Types
Sequence:-
List:-
List is a
mutable &
ordered
collection of
elements of
heterogeneou
s data type.
In list, the elements are separated by commas and that are enclosed within
square bracket “[ ]”
Eg:
35. Data Types
Example for List Indexing:-
In list, the elements are represented with the index value from 0 to n-1.
Eg:
37. Data Types : Sequence
Tuple:-
Tuple is immutable & ordered collection of elements of
heterogeneous /
homogeneous data type.
The elements are separated by commas and that are enclosed within square
bracket “( )”
Eg:
38. Data Types : Sequence
Example for Tuple Representation:-
39. Data Types
Example for Tuple Indexing:-
In tuple, the elements are represented with the index value from 0 to n-1.
Eg:
43. Data Types
Dictionary:-
Dictionary is an ordered collection of elements enclosed within “{ }”.
The elements in the dictionaries are mutable.
Elements are represented by key : value pair
Eg:-
45. Variables in Python
❑ Python Variable is a container that store values.
❑ The value can be immediately assigned to a variable in Python
❑ A Python variable is a name given to a memory location. It is the
basic unit of storage in a program.
Example
Var = “Sri Eshwar"
print(Var)
1
46. Rules for declaring Variables in Python
❑ A Python variable name must start with a letter or the underscore
character.
❑ A Python variable name cannot start with a number.
❑A Python variable name can only contain alpha-numeric
characters and underscores (A-z, 0-9, and _ ).
❑Variable in Python names are case-sensitive (name, Name,
and NAME are three different variables).
❑ The reserved words(keywords) in Python cannot be used to
name
the variable in Python.
2
47. Assigning a variable in Python
❑ Assigning an integer
age = 45
❑Assigning a floating
point salary = 1456.8
❑Assigning a string
name = "John"
print(age)
print(salary)
print(name)
3
48. Expression in Python
❑An expression is a combination of operators and operands that
is interpreted to produce some other value.
❑An expression is evaluated as per the precedence of its
operators.
The expression types are
⮚ Constant Expressions
⮚ Arithmetic Expressions
⮚ Integral Expressions
⮚ Floating Expressions
⮚ Relational Expressions
⮚ Logical Expressions
⮚ Bitwise Expressions
4
50. Arithmetic Expression
An arithmetic expression is a combination of numeric values,
operators, and sometimes parenthesis.The arithmetic operators are
6
51. Arithmetic Expression-Example
Program
x = 40
y = 12
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.3333333
333333335 7
52. Integral Expressions
These are the kind of expressions that produce only integer results after
all computations and type conversions.
Program
a = 13
b = 12.0
c = a +
int(b)
print(c)
Output
25
8
53. Floating Expressions
These are the kind of expressions which produce floating point numbers
as result after all computations and type conversions.
Example:
# Floating Expressions
a = 13
b = 5
c = a / b
print(c)
Output
2.6
9
54. Relational Expressions
10
❑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.
Example:
# Relational Expressions
a = 21
b = 13
c = 40
d = 37
p = (a + b) >= (c - d)
print(p)
Output
True
55. 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 and will
return
False.
11
56. Logical Expressions-Example
Example
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)
12
Output
False
True
True
57. Bitwise Expressions-Example
These are the kind of expressions in which computations
are performed at bit level.
Example
a = 12
x = a >> 2
y = a << 1
print(x, y)
Output
3 24
13
58. Operators
❑ Operator is a symbol that performs certain operations.
❑ Python provides the following set of operators
1. Arithmetic Operators
2. Relational Operators or Comparison Operators
3. Logical operators
4. Bitwise operators
5. Assignment operators
6. Special operators
1
79. Special operators
1. Identity Operators
❑ We can use identity operators for address comparison.
❑ 2 identity operators are available
2. is
3. is not
❑ r1 is r2 returns True if both r1 and r2 are pointing to the same object
❑ r1 is not r2 returns True if both r1 and r2 are not pointing to the
same object
Python defines the following 2 special
operators
1. Identity Operators
2. Membership operators
22
81. 2.Membership operators
❑ We can use Membership operators to check whether the given object
present in the given collection.(It may be String, List,Set,Tuple or
Dict)
❑ In->Returns True if the given object present in the specified
Collection
❑ not in-> Returns True if the given object not present in the specified
Collection
24
82. Operators Precedence
25
.
❑ If multiple operators present then which operator will be
evaluated
first is decided by operator precedence.
❑ The acronym PEMDAS ( Parentheses, Exponentiation,
Multiplication ,Division, Addition, Subtraction) is a useful way to
remember the rules:
84. 1
Control Flow Statements
Control Flow
Statements
Sequential
Statements
Branching
Statements
Conditional
Statements
• In a program, the control flow is the order in which the program’s
code executes. Control statements are elements in the source
code that control the flow of program execution.
• The control flow of a Python program is regulated by sequential
statements, conditional statements, loops, and function calls.
if
if-else
Nested if
If-elif-else
Un Conditional
Statements
break
continue
pass
Loop
Statements
for
while
85. Example 1: Greet a user with the Welcome Message “Welcome<<user
name>>”
IPO Chart:-
Sequence
Program:-
Username=input(“Enter your name”)
print(“Welcome”, Username)
Input Processing Output
Read username Algorithm
Step 1 : Start
Step 2 : Input username
Step 3 : Print Welcome username
Step 4 : Stop
“Welcome username”
Output:-
XYZ
Welcome XYZ
2
86. • Conditional Statements also known as selection statements, are
used to make decisions based on a given condition.
• If the condition evaluates to True, a set of statements is executed,
otherwise another set of statements is executed.
Conditional Statements
3
88. • Conditional Statements are also known as If Statement,
which executes only if the condition given in the if statement is
True.
• If the condition is False, then the If statement is not executed.
• Syntax:-
5
If Statement
if condition:
Statement
89. • Example 1: Python program to determine whether a person is eligible
to vote.
IPO Chart:-
Program
age=int(input(“Enter a number”))
if age>=18:
print(“You are Eligible to
vote”)
Conditional Statement : If Statement
Input Processing Output
Prompt the user to
enter a person age
Step 1: Start
Step 2: Read the value of age
Step 3: Check the condition age is greater
than or equal to 18. If True, goto
Step 3.1
Step 3.1: Print “You are eligible”
Step 4: Stop
You are eligible
Output
You are Eligible to Vote
6
90. • Alternative Statements are also known as If–Else Statement, in
which the “If Statement” executes the statements only if
the condition is True.
• If the condition is False, then the Else statement gets executed.
If-Else Statement
Syntax
if condition:
Statements
else:
State
ments
7
91. Example 1: To check whether the given number is odd or even number
IPO Chart:
If-Else Statement
Program: (Even_odd.py)
number = int(input("Enter a number:n"))
if (number % 2) == 0:
print(number," is Even number")
else:
print(number," is Odd number")
Input Processing Output
number
Example:
number=10
Read number
Check condition number %2==0, if
condition true, print number is even
Else print number is odd
Print number is odd or even
Example:
10%2==0 (True)
10 is even number
8
92. Example 1: To check whether the given number is odd or even number
Program:
1. number = int(input("Enter a number:n"))
2. if (number % 2) == 0:
3. print(number," is Even number")
4. else:
5. print(number," is Odd number")
Trace Table:
9
If-else Statement
Line No number number %2==0 Output
1 10
2 True
3 10 is Even number
4
5 - -
93. • Chained conditional Statements are also known as if–elif-else
Statement, in which the “if Statement” executes the
statements only if the condition is True.
• “elif Statement” provides an alternative possibility for the “if
Statement”. The execution of “Elif Statement” is same as the
“if Statement” (i.e) “elif Statement” executes the statements
only if the condition is True.
• If the condition given in the “elif Statement” is also False, then
“else Statement” gets executed.
If – elif - else Statement
10
95. Example 1: To test whether a number entered by the user is negative /
positive / zero.
IPO Chart:
If – Elif - Else Statement
Program: (pos_neg_zero.py)
num=int(input("Enter any number:n"))
if num > 0:
print(num,"is Positive number")
elif num == 0:
print(num,"is Zero")
else:
print(num,"is Negative
number")
Input Processing Output
number
Example:
a=-7
Read number
if number>0 then
print “number is Positive”
elif number<0 then
print “number is
Negative”
else
print “number is Zero”
Print number is negative /
positive / zero.
Example:
-7 is Negative Number
12
96. Selection : If – elif - else Statement
13
Program:
1. num=int(input("Enter any number:n"))
2. if num > 0:
3. print(num,"is Positive number")
4. elif num == 0:
5. print(num,"is Zero")
6. else:
7. print(num,"is Negative number")
Trace Table:
Line No num num>0 num==0 else Output
1 -7
2 False
3 -
4 False
5 -
6 True
7 -7 is Negative Number
97. • It means you can use one if or else if statement inside another if
or else if statement(s).
• It is always legal to nest if-else statements.
Nested If Statement
14
98. Example 1: To find the greatest among three numbers.
IPO Chart:
Nested If Statement
Input Processing Output
3 numbers
Example:
a=10, b=15, c=35
Read 3 numbers as a, b and c
if a>b then
if a>c then
print a is largest
else
print c is largest
elif b>c then
print b is
largest
else
print c is
largest
Print largest number
Example:
c is largest
15
99. Nested If Statement
Example 1: To find the greatest among three numbers
Program:
1. a=int(input("Enter the first number: "))
2. b=int(input("Enter the second number: "))
3. c=int(input("Enter the third number: "))
4. if a>b:
5. if a>c:
6. print(a,"is the greatest number than",b,"and",c)
7. else:
8. print(c,"is the greatest number than",a,"and",b)
9. elif b>c:
10. print(b,"is the greatest number than",a,"and",c)
11. else:
12. print(c,"is the greatest number than",a,"and",b)
16
100. 17
Nested If Statement
Example 1: To find the greatest among three numbers
Trace Table:
Line No a b c a>b a>c b>c Output
1 12
2 13
3 10
4 False
5
6
7
8
9 True
10 13 is the greatest number than 12
and 10
11
12
101. Practice Exercises : Conditionals
1. Write a program to check leap year or not.
2.Write a program to display “Hello” if a number entered
by the user is multiple of 5 otherwise print “Bye”.
3.Write a program to accept number from 1 to 7 and
display the name of day like 1 for Sunday, 2 for Monday and
so on.
4.Write a Python program to accept the cost price of a
bike and display the road tax to be paid according to the
following criteria.
18
102. • Looping Statement is a process of executing the set of statements
repeatedly until the condition is True.
•It is also known as looping statements or
repetition. Iteration (Looping)
• Example: To repeat our daily routine as a student
Looping Statements
19
103. • While loop statement is a set of statements that are repeatedly
executed only if the condition is True. When the
condition becomes False, the loop gets terminated.
• While loop statement is also known as Entry-Controlled loop.
• Syntax:-
while condition:
statement
Iteration : While Loop Statement
20
104. Example 1: Print first N natural numbers.
IPO Chart:
21
Iteration : While Loop Statement
Input Processing Output
N Value
Example:
N=3
READ N value
INITIALIZE i as 1
WHILE i<=N
PRINT i
i=i+1
END WHILE
Print N Natural numbers
Example:
N=3
The first 3 Natural
Numbers are:
1, 2, 3
Program:
1. N=int(input('Enter the value of N: '))
2. i=1 # initialization
3. while i<=N: # Condition
4. print(i)
5. i=i+1 # Increment
105. 22
Iteration : While Loop Statement
Example 1: Print first N natural numbers
Trace Table
Line No N i i<=N Output
1 3
2 1
3 True
4 1
2 2
3 True
4 2
2 3
3 True
4 3
2 4
3 False
106. • For loop statement is a set of statements that are repeatedly or
iteratively executed over a sequence.
When
becomes False, then the loop gets terminated.
• Syntax:-
the condition
Iteration : For Loop Statement
Syntax
for variable in sequence:
statement
23
107. Example 1: Calculate the factorial of a given number
Note: In mathematics, the factorial of a positive integer n, denoted by
n!, is the product of all positive integers less than or equal to n.
Example: 5!= 5*4*3*2*1=120.
IPO Chart:
Iteration : For Loop Statement
Input Processing Output
N Value
Example:
N=5
READ N
SET fact=1
IF n==0 THEN
PRINT fact
ELSE
FOR i
←
1 to n
C
OMP
UTE
Print factorial of N
Example:
N=5
The factorial of 5 is 120
24
108. Iteration : For Loop Statement
Example 1: Calculate the factorial of a given number
Program:
1. N = int(input("Enter a number: ")) # To take input from the user
2. factorial = 1
3. if N < 0: # check if the number is negative, positive or
zero
4. print("Sorry, factorial does not exist for negative numbers")
5. elif N == 0:
6. print("The factorial of 0 is 1")
7. else:
8. for i in range(1,N + 1):
9. factorial = factorial*i
10. print("The factorial of",N,"is",factorial)
25
109. Iteration : For Loop Statement
Line
No
N factorial N<0 N==0 i range(1,N + 1) Output
1 5
2 1
3 False
5 False
8 1 True
9 1
8 2 True
9 2
8 3 True
9 6
Example 1: Calculate the factorial of a given number
Trace Table
26
110. Iteration : For Loop Statement
Line
No
N factorial N<0 N==0 i range(1,N + 1) Output
8 4 True
9 24
8 5 True
9 120
8 6 False
10 120
Example 1: Calculate the factorial of a given number
Trace Table
27
111. • It is used to transfers the control from one part of the program to
another without any condition.
• Python supports three types of unconditional control statements:
– break
– continue
– pass
Unconditional Control Statements
28
112. • It is used to transfers the control from one part of the program to
another without any condition.
• Python supports three types of unconditional control statements:
– break
– continue
– pass
Unconditional Control Statements
29
113. • Break statement is used to terminate the execution of the nearest
enclosing loop in which it appears.
• When compiler encounters a break statement, the control passes to
the statement immediately after the body of the loop.
• Syntax:-
break
Unconditional Statement : Break
30
114. Unconditional Control Statement : Break
Example 1: To print the numbers from 1 to 10. If the number is 3 then stop
the process.
IPO Chart:
Input Processing Output
Range of numbers
Example:
Range: 1 to 10
INITIALIZE i=1
WHILE i<=10
PRINT i
IF i==3
THEN
break
i=i+1
PRINT
“Done”
Print numbers from 1 to 10
Example:
1
2
3
Done
31
115. 32
Unconditional Control Statement : Break
Program:
1. i=1
2. while i<=10:
3. print(i)
4. if i==3:
5. break
6. i=i+1
7. print(“Done”)
Example 1: To print the numbers from 1 to 10. If the number is 3 then stop
the process.
Line
No
i i<10 Output i==5
1 1
2 True
3 1
4 False
6 2
2 True
3 2
4 False
6 3
2 True
3 3
4 True
7 Done
Trace Table
116. Unconditional Control Statement : Break
Example 2: To get N inputs from the user and calculate the sum of the
same. If user enters -1 then stop adding.
IPO Chart:
Input Processing Output
N value
N integer value from
user
Example:
N: 5
User input
5
4
3
8
9
READ N value
INITIALIZE i as 1, sum as 0
WHILE i<=N
READ num
IF num==-1 THEN
break
ELSE
su
m=su
m+n
um
END
IF
i=i+1
END WHILE
PRINT
sum
Print sum of N inputs
Example:
N: 5
User Input
5
4
3
8
9
Sum of
input
value is:
29
33
117. Unconditional Control Statement : Break
Example 2: To get N inputs from the user and calculate the sum of the
same. If user enters -1 then stop adding.
Program:
1. N=int(input("Enter the value of N"))
2. i=1
3. sum=0
4. while i<=N:
5. num=int(input("Enter the user inputs"))
6. if num==-1:
7. break
8. else:
9. sum=sum+num
10. i=i+1
11. print('The sum of user input is: ',sum)
34
118. 35
Unconditional Control Statement : Break
Example 2: To get N inputs from the user and calculate the sum of the
same. If user enters -1 then stop adding.
Trace Table
Line No N i sum i<=N num num==-1 Output
1 5
2 1
3 0
4 True
5 5
6 False
7 5
8 2
4 True
5 8
6 False
7 13
119. Unconditional Control Statement : Break
Example 2: To get N inputs from the user and calculate the sum of the
same. If user enters -1 then stop adding.
Trace Table
Line No N i sum i<=N num num==-1 Output
8 3
4 True
5 7
6 False
7 20
8 4
4 True
5 -1
6 True
11 20
36
120. • Continue statement can only appear in the body of a loop.
• When compiler encounters a continue statement, then the rest of
the statements in the loop are skipped and the control
is unconditionally transferred to the loop.
• Syntax:-
continue
Unconditional Statement : Continue
37
121. Unconditional Control Statements: continue
Example 1: To get N inputs from the user and skip if user inputs negative
number else calculate the sum of the user inputs
IPO Chart:
Input Processing Output
N value
N integer value from
user
Example:
N: 5
User input
5
4
-3
8
-9
READ N value
INITIALIZE i as 1, sum as 0
WHILE i<=N
READ num
i=i+1
IF num<0
THEN
continue
ELSE
sum=sum+num
END IF
END WHILE
PRINT sum
Print sum of N inputs
Example:
N: 5
User Input
5
4
-3 (skip)
8
-9 (skip)
Sum of
input
value is:
17
38
122. Unconditional Control Statements: continue
Example 1: To get N inputs from the user and skip if user inputs negative
number then calculate the sum of the user inputs
Program:
1. N=int(input("Enter the value of N: "))
2. i=1
3. sum=0
4. while i<=N:
5. num=int(input("Enter the user inputs: "))
6. i=i+1
7. if num<0:
8. continue
9. else:
10. sum=sum+num
11. print('The sum of user input is: ',sum)
39
123. 40
Unconditional Control Statements: continue
Example 1: To get N inputs from the user and skip if user inputs negative
number then calculate the sum of the user inputs
Trace Table
Line No N i sum i<=N num Num<0 Output
1 5
2 1
3 0
4 True
5 5
6 2
7 False
10 5
4 True
5 4
6 3
7 False
124. Unconditional Control Statements: continue
Example 1: To get N inputs from the user and skip if user inputs negative
number then calculate the sum of the user inputs
Trace Table
Line No N i sum i<=N num Num<0 Output
10 9
4 True
5 -3
6 4
7 True
10 -
4 True
5 8
6 5
7 False
10 17
41
125. Unconditional Control Statements: continue
Example 1: To get N inputs from the user and skip if user inputs negative
number then calculate the sum of the user inputs
Trace Table
Line No N i sum i<=N num Num<0 Output
4 True
5 -9
6 6
7 True
10 -
4 False
11 17
42
126. Example 2: Write a Python program to print the numbers from 1 to
10.
Program:-
for i in range(1,11):
if i==5:
continue
print(i)
print(“Done”)
Unconditional Statement : Continue
Output
1
2
3
4
6
7
8
9
10
Done
43
127. Unconditional Statement : Continue
i i==5 Output Output
1 False 1
2 False 2
3 False 3
4 False 4
5 True
6 False 6
7 False 7
8 False 8
9 False 9
10 False 10
11 Done
Example 2: Write a Python program to print the numbers from 1 to
10.
44
128. • Pass statement is the statement that are syntactically used to not
execute the code. The pass statement does noting.
• Syntax:-
pass
Unconditional Statement : Pass
45
129. Example 1: Write a Python program to print the numbers from 1 to
10.
Program:-
for i in range(1,11):
if i==5:
pass
print(i)
print(“Done”)
Unconditional Statement : Pass
Output
1
2
3
4
5
6
7
8
9
10
Done
46
130. Unconditional Statement : Pass
i i==5 Output Output
1 False 1
2 False 2
3 False 3
4 False 4
5 True 5
6 False 6
7 False 7
8 False 8
9 False 9
10 False 10
11 Done
Example 1: Write a Python program to print the numbers from 1 to
10.
47
131. • A function is block of code which is used to perform a particular
task when it is called.
• Functions are used to perform certain actions, and they are
important for reusing code: Define the code once, and use it
many times.
Function: Introduction
48
132. Need for Function:
• Function simplifies the process of program development.
• Functions provide better modularity and have a high degree
of
code reuse.
Advantages of Function:
• Reducing duplication of code
• Decomposing complex problems into simpler pieces
• Improving clarity of the code
• Reuse of code
Function: Introduction
49
133. • Depending on whether a function is predefined or created by
programmer; there are two types of function:
• Build-in Function or Library function:
– Programmer can use library function by invoking function
directly; they don't need to write it themselves.
Python has several functions that are readily available for
use.
– Example: print(), range(), format(), abs(), round(), and etc.,
• User-defined Function : The function created by the user
according to the need.
Function: Introduction
50
134. Build-in Function
Example: The round() function returns a
floating-point number rounded to the specified number of
decimals.
Syntax: round(number, ndigits)
The round() function takes two parameters:
– number - the number to be rounded
– ndigits (optional) - number up to which the given number is rounded;
defaults to 0
Program:
1. # for integers
2. print(round(10)) #10
3. # for floating point
4. print(round(10.7)) #11
5. print(round(5.5)) #6
6. print(round(2.67)) #3
7. print(round(2.678,2)) #2.68
51
135. Function Definition:
• It is a part where we define the operation of a function.
It consists of the declarator followed by the function body.
• Defining a function means, specifying its name, parameters that
are expected, and the set of instructions.
• In Python a function is defined using the def keyword
Function: Elements
52
136. Function Definition:-
Function : Defining a Function
Example:-
# Function Definition
1. def add(a,b):
2. sum=a+b
3. return sum
53
137. Function : Calling a Function
Function Call:-
• Defining a function means, specifying its name, parameters
that are expected, and the set of instructions.
• Once the basic structure of a function is finalized, it can be executed by
calling it.
• The function call statement invokes the function.
Syntax:-
function_name(variable1, variable2,…. )
Example:-
# Function Call in the Main Function
1. a=int(input(‘Enter the value of a:’))
2. b=int(input(‘Enter the value of b:’))
3. res=add(a,b) #The function
with the name add is called
4. print(res) 54
139. Function Call:-
• When a function is invoked, the program control jumps to the
called
function to execute the statements that are in the part of that function.
• Once the called function is executed the program control passes back to
the calling function. The function that returns the value back to the
calling function is known as Fruitful function.
Function : Calling a Function
# Function Call or Calling Function
1. a=int(input(‘Enter the value of a:’))
2. b=int(input(‘Enter the value of b:’))
3. res=add(a,b)
4. print(res)
Example:-
# Function Definition or Called
Function
1. def add(a,b):
2. sum=a+b
3. return sum
56
140. Parameters:-
• Parameters are the variables which is used to store the values.
Types of Parameters:-
• Actual Parameter – Parameters used in the function call or calling
function.
• Formal Parameter – Parameters used in the function definition or
called function.
During program execution, the values in the actual parameter
is assigned to the formal parameter.
Function : Parameters
57
141. Example 1: Python program to find cube
of a given numberusing function
Program: (cube.py)
Function
# Sub Function or Called
Function
1. def cube(x):
2. return x*x*x
# Calling Function
1. n=int(input(‘Enter the value of n:’))
2. result=cube(n)
3. print(“The Cube is:”, result)
Output
Enter the value of n: 10
The Cube is: 1000
58
142. Fruitful Functions:-
• A fruitful function is one in which there is a return statement
with an expression. This means that a fruitful function returns
a value that can be utilized by the calling function for
further processing.
The return Statement:-
• The return statement is used to return value from the called
function to the calling function.
• A return statement with no argument returns none to the calling
function.
• Syntax:
59
Fruitful Functions
return expression
143. Example: Python program to check whether a given number is odd or
even using functions.
Fruitful Functions
Input Processing Output
Prompt the
user to enter
a number
Main Function:-
READ a
CALL the function evenodd(a) and pass the value of ‘a’
from the calling function to the called function.
SET the value obtained from the called function to res
IF res==1 THEN
PRINT “Number is Even”
IF res==-1 THEN
PRINT “Number is Odd”
Sub Function:- evenodd(a)
GET the value from calling function as a
IF a%2==0 THEN
RETURN the value as 1 to the calling function
ELSE
RETURN the value as -1 to the calling function
Print the entered
number as odd or
even
60
144. Example: Python program to check whether a given number is odd or
even using functions.
Program:-
def evenodd(a):
if(a%2==0):
return 1
else:
return -1
a=int(input(“Enter the number”))
res=evenodd(a)
if(res==1):
print(“Number is even”)
if(res==-1):
print(“Number
is odd”)
Fruitful Functions
Output:-
Enter the number
10
Number is even
61
145. • Arguments are the values which are assigned to the parameter.
Types of Arguments:-
Required argument
Keyword argument
Default argument
Variable – length argument
Required Argument:-
• In Required argument, the arguments are passed to a function in
correct positional order.
• The number of arguments in the function call should exactly match
with the number arguments specified in the function definition. 62
Fruitful Functions : Parameters
146. Example: Python program to return the average of its arguments.
Program:-
def avg(n1,n2):
res=(n1+n2)/2
return(res)
n1=int(input(“Enter the first no:”))
n2=int(input(“Enter the second
no:”)) print(“AVERAGE = ”,
avg(n1,n2))
63
Fruitful Functions : Parameters
Output:-
Enter the first no:
6
Enter the second no:
4
AVERAGE = 5
147. Keyword Argument:-
• In Keyword Argument, the order (or the position) of the arguments can be
changed. The values are not assigned to arguments according to
their position but based on their name (or keyword).
Example 1: Python program to print the employee details using function.
Program:-
def display(name, age, salary):
print(“Name: ”, name)
print(“Age: ”, age)
print(“Salary: ”, salary)
return
n=“XYZ”
a=35
s=20000
display(sa 64
Fruitful Functions : Parameters
Output:-
Name: XYZ
Age: 35
Salary:
20000
148. Example 2: Python program to print the person information using function.
Program:-
def printinfo(name, age):
print(“This prints a passed info into this function”)
print ("Name: ", name)
print ("Age: ", age)
return
printinfo(age=50, name=“miki”)
Fruitful Functions : Parameters
Output:-
This prints a passed info into this function
Name: miki
Age: 50
65
149. Default Argument:-
• Python allows users to specify function arguments that can have default
values. Default value to an argument is provided using the assignment
operator (=).
• Default argument assumes a default value, if a value is not provided in the
function call for the argument.
Example 1: Python program to print the student details using function.
Program:-
def display(name, course=“BTech”):
print(“Name: ”, name)
print(“Course: ”, course)
return
display(course=“BCA”, name=“Arav”)
display(name=“Reyansh”)
Fruitful Functions : Parameters
Output:-
Name: Arav
Course: BCA
Name: Reyansh
Course: BTech
66
150. Variable-length Arguments
• In some situations, it is not known in advance that how may arguments
will be passed to a function. In such cases, Python allows programmers to
make function calls with arbitrary number of arguments.
• When we use arbitrary arguments or variable length arguments, then the
function definition uses an asterisk(*) before the parameter name.
Syntax:-
def functionname([arg1, arg2,….],*var_arg_tuple):
function statements
return [expression]
Fruitful Functions : Parameters
67
151. Fruitful Functions : Parameters
Example 2: Python program to print the sum of two numbers from the
entered input.
Program:-
def sum(a,b,*var):
sum=a+b
for i in var:
print(i)
return(sum)
print(sum(10,
20,30,40,50))
Output:-
30
40
50
30
68
152. Fruitful Functions : Parameters
Example : Python program to print the arbitrary key word arguments
and positional argument by the entered input.
Program:-
def sum(*var,**res):
for i in var:
print(i)
for key,value in res.items():
print(key,":",value)
return
print(sum(10,20,30,40,50,greeting="HI",a=10))
Output:-
10
20
30
40
50
greeting : HI
a : 10
None
69
153. map()
• map() returns a map object(which is an iterator) as a result after
applying the given function to each item of a given iterable (list,
tuple, etc).
Example:-
def square(x):
return x * x
Syntax:-
map(function_name, iterables)
Output:-
[1,4,9,16,25]
numbers = [1, 2, 3, 4, 5]
squared_numbers = map(square, numbers)
print(list(squared_numbers)) 70
154. map()
• map() returns a map object(which is an iterator) as a result after
applying the given function to each item of a given iterable (list,
tuple, etc).
Example:-
def square(x):
return x * x
Syntax:-
map(function_name, iterables)
Output:-
[1,4,9,16,25]
numbers = [1, 2, 3, 4, 5]
squared_numbers = map(square, numbers)
print(list(squared_numbers)) 71
155. 72
filter()
• The filter() method filters the given sequence with the help
of a
function.
Example:-
def is_even(x):
return x % 2 == 0
numbers = [1, 2, 3,
4, 5, 6, 7, 8, 9, 10]
print(list(filter(is_e
ven, numbers)))
Syntax:-
filter(function_name, iterables)
Output:-
[2,4,6,8,10]
156. 73
reduce()
• reduce() is used to apply a function to an iterable and reduce it to a
single cumulative value. It is a part of functools module.
Example:-
import functools
def add(x, y):
return x + y
numbers = [1, 2,
3, 4, 5]
sum_of_numbers = functools.reduce(add, numbers)
Syntax:-
functools.reduce(function, iterables)
Output:-
15
157. Lambda()
• Lambda() are the anonymous function, which means the
function
without a name.
• Lambda function takes any number of arguments but can have only
one expression.
Example:-
add=lambda x,y:x+y
print(add(2,3))
Syntax:-
lambda parameters : expression
Output:-
5
74
160. • Recursive function is defined as a function that calls itself to solve a smaller
version of its task until a final call is made which does not require a call to itself.
• Every recursive function has major two cases.,
Base case – The problem is simple enough to be solved directly without making
any further calls to the same function.
Recursive case – First the problem is divided into simpler sub-parts. Second, the
function calls itself with the sub-parts of the problem obtained in the first
step. Third, the result is obtained by combining the solutions of simpler sub-
parts.
• Recursion is based on divide and conquer technique for problem solving.
Function : Recursion
77
161. Example 1:Python program to find
exponentiation of given number using recursion
Program: (exp.py)
Function : Recursion
# Sub Function or Called Function
1. def exp(base, pow):
2. if(pow==0):
3. return 1
4. else:
5. return (base*exp(base, pow-1))
# Main Function or Calling Function
1. base=int(input(‘Enter the base No:’))
2. power=int(input(‘Enter the power:’))
3. print(“Result=”, exp(base, pow))
Output
Enter the base No: 2
Enter the power: 3
8
78
162. Example 2:Python program to find fibonacci series using recursion
Program: (fibo.py)
Function : Recursion
# Sub Function or Called Function
1. def fibonacci(n):
2. if(n<=1):
3. return n
4. else:
5. return (fibonacci(n-1)+fibonacci(n-2))
# Main Function or Calling Function
1. num=int(input(‘Enter the term:’))
2. if num<=0:
3. print(“Please enter the positive integer”)
4. else:
5. for i in range(0, num):
6. print(fibonacci(i))
Output
Enter the term: 5
0 1 1 2 3
79
163. Illustrative Programs
Financial Application:- (Example 1)
Develop Python Code for the Financial Application
Enter the Product name: Pen
Enter the quantity of an item sold: 5
Enter the value of an item: 2
Enter the discount percentage: 2
Enter the tax: 2
*******************BILL****
*************
Quantity sold: 5
Price per item: 2
Amount: 10.0
Discount: -0.2
Total: 9.8
Tax: +0.196
Amount to be
80
167. Illustrative Programs
Sandwich Vowel:-
def updateSandwichedVowels(a):
n = len(a)
updatedString = "" for i
in range(0, n, 1):
if (i == 0 or i == n - 1):
updatedString += a[i]
continue
if (isVowel(a[i]) == True
and isVowel(a[i - 1]) ==
False and
isVowel(a[i + 1]) == False):
continue
updatedString += a[i]
return updatedString 84
169. Illustrative Programs
Chocolate Distribution Algorithm:-
Given an array of n integers where each value represents the number of chocolates in a packet.
Each
packet can have a variable number of chocolates. There are m students, the task is to distribute
chocolate packets such that:
1. Each student gets one packet.
2.The difference between the number of chocolates in the packet with maximum chocolates
and packet
with minimum chocolates given to the students is minimum.
Examples:
Input : arr[] = {7, 3, 2, 4, 9, 12, 56} , m = 3
Output: Minimum Difference is 2
Explanation:
We have seven packets of chocolates and we need to pick three packets for 3 students
If we pick 2, 3 and 4, we get the minimum difference between maximum and minimum
packet sizes.
Input : arr[] = {3, 4, 1, 9, 56, 7, 9, 12} , m = 5
Output: Minimum Difference is 6
Explanation:
The set goes like 3,4,7,9,9 and the output is 9-3 = 6 86
171. 88
Illustrative Programs
Chocolate Distribution Algorithm:-
def findMinDiff(arr, n, m):
if (m==0 or n==0):
return 0
arr.sort()
if (n < m):
retur
n -1
min_dif
f = arr[n-
1] - arr[0]
for i in
range(len(
arr) - m +
1):
arr = [12,4,7,9,2,23,25]
m = 4
n = len(arr)
print("Minimum difference is", findMinDiff(arr, n, m))
Output:-
Minimum difference is 7
172. Al Sweigart, "Automate the Boring Stuff with Python: Practical Programming for
Total Beginners," 2nd Edition, No Starch Press, 2019
Liang Y. Daniel, “Introduction to Programming Using Python”, Pearson Education,
2017
Jake VanderPla, “Python Data Science Handbook,” O’Reilly
(https://jakevdp.github.io/PythonDataScienceHandbook)
William S Vincent, “Django for Beginners: Build Websites with Python and Django,”
Welcome to code Publishers, 2020.
Reference Books
173. Reference Books
Robert Sedgewick, Kevin Wayne, Robert Dondero, "Introduction to Programming in
Python: An Inter-Disciplinary Approach," Pearson India Education Services Pvt. Ltd., 2016
Allen B. Downey, "Think Python: How to Think Like a Computer Scientist," Second edition,
Updated for Python 3, Shroff O'Reilly Publishers, 2016
Timothy A. Budd," Exploring Python," Mc-Graw Hill Education (India) Private Ltd., 2015