This document discusses control flow and control structures in programming, including conditional structures like if/else statements and repetition structures like while and for loops.
It provides examples of simple if statements, if/else statements, if/elif/else statements, and nested if statements. It also discusses indefinite loops with while and definite loops with for, and how to break and continue loops.
Finally, it covers pass and return statements, local and global scopes, function composition, lambda functions, string slicing, string methods, and that strings are immutable in Python.
This document provides an overview of key concepts in programming and Python. It defines terms like code, syntax, output, console, compiling, interpreting, and variables. It explains Python as an interpreted language and shows examples of printing output, taking user input, performing calculations with numbers and math commands, using variables, and basic control structures like if/else and loops. It also covers data types like integers, floats, strings, lists, and how to modify and format them.
This document provides an overview of imperative programming and nested loops in Python. It discusses strategies for writing nested loops, including using for loops with if conditions. It also covers the range() function for iterating over sequences of numbers, user-defined functions, parameters, return statements versus print statements, multiline comments, and docstrings. The document concludes with assigning practice problems to help reinforce these concepts.
This document discusses arrays and functions in C++. It explains that arrays allow storing multiple values in a single variable to avoid declaring many individual variables. Arrays can store values of different data types like integers, floats, characters. Functions are blocks of code that perform a specific task and can optionally return a value. Functions make code reusable and avoid repetition. The document provides examples of one-dimensional and two-dimensional arrays, and functions with and without parameters. It also assigns practice problems of writing functions to calculate the summation of numbers from 1 to 1000, find the factorial of a given number, and calculate a number to the power of a given exponent.
This document provides an overview of the basics of Python. It discusses code or source code, syntax, output, the console, compiling vs interpreting, the Python interpreter, expressions, operators, integer and real numbers, math commands, variables, print statements, input, the for loop, range, if/else statements, while loops, logic, and loop control statements. It also covers data types like numbers, strings, lists, sets, and dictionaries.
Principles of functional progrmming in scalaehsoon
a short outline on necessity of functional programming and principles of functional programming in Scala.
In the article some keyword are used but not explained (to keep the article short and simple), the interested reader can look them up in internet.
This document summarizes the contents of the second day of a hands-on workshop on the Python programming language. It discusses indentation, the range function, for and while loops, conditional statements like if/elif, and modules for math, time, and random variables. Example code is provided to demonstrate various Python concepts like loops, logical operators, and comparisons between Python and C/C++ programming.
This document provides a quick tour of the Python programming language. It introduces basic Python concepts like data types, variables, operators, conditional statements, loops, and functions. It explains how to get user input, perform type conversions, and work with common data types like integers, floats, strings, and booleans. It also demonstrates how to define functions, use default arguments and keyword arguments, and handle global variables. The document uses examples to illustrate concepts like arithmetic operations, string slicing, indexing, concatenation, and repetition.
This document provides an introduction to Python programming concepts including basic arithmetic operations, variables, data types, functions, strings, lists, conditional statements, while loops, and for loops. It explains key Python syntax such as operators, comments, functions, indexing lists, conditional checks, and loop structures. Examples are given for basic math calculations, string manipulation, list indexing/modification, conditional logic, and while/for loops. Key terms like integers, floats, booleans, strings, lists, tuples, dictionaries, if/else statements, comparison operators, and loop types are defined.
Python programming language provides the following types of loops to handle looping requirements:
1. While
2. Do While
3. For loop
Python provides three ways for executing the loops. While all the ways provide similar basic functionality, they differ in their syntax and condition-checking time.
The document provides an introduction to programming with Python. It discusses key concepts like code, syntax, output, and consoles. It also covers compiling vs interpreting languages, with Python being an interpreted language. The document explains expressions, variables, basic math operations, and functions in Python like print and input. It introduces control structures like if/else statements, for loops, and while loops. It also covers different data types in Python including numbers, strings, lists, and dictionaries.
Python is an interpreted programming language that can be used to perform calculations, handle text, and control program flow. It allows variables to store values that can later be used in expressions. Common operations include arithmetic, printing output, accepting user input, and repeating tasks using for loops and conditional statements like if/else. The interpreter executes Python code directly without a separate compilation step required by other languages.
The document provides an introduction to programming with Python. It discusses key concepts like code, syntax, output, and consoles. It also covers compiling vs interpreting languages, with Python being an interpreted language. The document explains expressions, variables, basic math operations, and functions in Python like print and input. It introduces control structures like if/else statements and for/while loops. It also covers different data types in Python including numbers, strings, lists, and dictionaries.
This document provides instructions on installing Python 3 on Ubuntu and Windows operating systems. It discusses installing Python 3.8 on Ubuntu using the apt install command and verifying the installation with the python --version command. It also outlines downloading the Python installer, running the executable, adding Python to environment variables, and verifying the installation on Windows. The document further explains installing iPython using pip and provides examples of using boolean values, conditionals, loops, functions, and strings in Python programs.
This document provides an introduction to the C programming language. It discusses key concepts like functions, variables, data types, memory, scopes, expressions, operators, control flow with if/else statements and loops. It also explains how passing arguments by value means functions cannot directly modify their parameters, but passing addresses allows modifying variables in the calling scope. Overall it serves as a helpful primer on basic C syntax and programming concepts for newcomers to the language.
Functions allow programmers to organize and reuse code. There are three types of functions: built-in functions, modules, and user-defined functions. User-defined functions are created using the def keyword and can take parameters and arguments. Functions can return values and have different scopes depending on if a variable is local or global. Recursion is when a function calls itself, and is useful for breaking down complex problems into simpler sub-problems. Common recursive functions calculate factorials, Fibonacci numbers, and generate the Pascal's triangle.
This document provides an overview of key concepts in Java including Eclipse IDE, creating classes, the main method, printing output, variables, data types, user input, arithmetic operators, and typecasting. It explains how to create a Java class in Eclipse, use print statements, declare and initialize variables, take user input, and perform basic math operations and conversions between data types in Java.
OS | Functions of OS | Operations of OS | Operations of a process | Scheduling algorithms | FCFS scheduling | SJF scheduling | RR scheduling | Paging | File system implementation | Cryptography as a security tool
Problem | Problem v/s Algorithm v/s Program | Types of Problems | Computational complexity | P class v/s NP class Problems | Polynomial time v/s Exponential time | Deterministic v/s non-deterministic Algorithms | Functions of non-deterministic Algorithms | Non-deterministic searching Algorithm | Non-deterministic sorting Algorithm | NP - Hard and NP - Complete Problems | Reduction | properties of reduction | Satisfiability problem and Algorithm
More Related Content
Similar to Introduction to python programming ( part-2 ) (20)
This document provides an overview of the basics of Python. It discusses code or source code, syntax, output, the console, compiling vs interpreting, the Python interpreter, expressions, operators, integer and real numbers, math commands, variables, print statements, input, the for loop, range, if/else statements, while loops, logic, and loop control statements. It also covers data types like numbers, strings, lists, sets, and dictionaries.
Principles of functional progrmming in scalaehsoon
a short outline on necessity of functional programming and principles of functional programming in Scala.
In the article some keyword are used but not explained (to keep the article short and simple), the interested reader can look them up in internet.
This document summarizes the contents of the second day of a hands-on workshop on the Python programming language. It discusses indentation, the range function, for and while loops, conditional statements like if/elif, and modules for math, time, and random variables. Example code is provided to demonstrate various Python concepts like loops, logical operators, and comparisons between Python and C/C++ programming.
This document provides a quick tour of the Python programming language. It introduces basic Python concepts like data types, variables, operators, conditional statements, loops, and functions. It explains how to get user input, perform type conversions, and work with common data types like integers, floats, strings, and booleans. It also demonstrates how to define functions, use default arguments and keyword arguments, and handle global variables. The document uses examples to illustrate concepts like arithmetic operations, string slicing, indexing, concatenation, and repetition.
This document provides an introduction to Python programming concepts including basic arithmetic operations, variables, data types, functions, strings, lists, conditional statements, while loops, and for loops. It explains key Python syntax such as operators, comments, functions, indexing lists, conditional checks, and loop structures. Examples are given for basic math calculations, string manipulation, list indexing/modification, conditional logic, and while/for loops. Key terms like integers, floats, booleans, strings, lists, tuples, dictionaries, if/else statements, comparison operators, and loop types are defined.
Python programming language provides the following types of loops to handle looping requirements:
1. While
2. Do While
3. For loop
Python provides three ways for executing the loops. While all the ways provide similar basic functionality, they differ in their syntax and condition-checking time.
The document provides an introduction to programming with Python. It discusses key concepts like code, syntax, output, and consoles. It also covers compiling vs interpreting languages, with Python being an interpreted language. The document explains expressions, variables, basic math operations, and functions in Python like print and input. It introduces control structures like if/else statements, for loops, and while loops. It also covers different data types in Python including numbers, strings, lists, and dictionaries.
Python is an interpreted programming language that can be used to perform calculations, handle text, and control program flow. It allows variables to store values that can later be used in expressions. Common operations include arithmetic, printing output, accepting user input, and repeating tasks using for loops and conditional statements like if/else. The interpreter executes Python code directly without a separate compilation step required by other languages.
The document provides an introduction to programming with Python. It discusses key concepts like code, syntax, output, and consoles. It also covers compiling vs interpreting languages, with Python being an interpreted language. The document explains expressions, variables, basic math operations, and functions in Python like print and input. It introduces control structures like if/else statements and for/while loops. It also covers different data types in Python including numbers, strings, lists, and dictionaries.
This document provides instructions on installing Python 3 on Ubuntu and Windows operating systems. It discusses installing Python 3.8 on Ubuntu using the apt install command and verifying the installation with the python --version command. It also outlines downloading the Python installer, running the executable, adding Python to environment variables, and verifying the installation on Windows. The document further explains installing iPython using pip and provides examples of using boolean values, conditionals, loops, functions, and strings in Python programs.
This document provides an introduction to the C programming language. It discusses key concepts like functions, variables, data types, memory, scopes, expressions, operators, control flow with if/else statements and loops. It also explains how passing arguments by value means functions cannot directly modify their parameters, but passing addresses allows modifying variables in the calling scope. Overall it serves as a helpful primer on basic C syntax and programming concepts for newcomers to the language.
Functions allow programmers to organize and reuse code. There are three types of functions: built-in functions, modules, and user-defined functions. User-defined functions are created using the def keyword and can take parameters and arguments. Functions can return values and have different scopes depending on if a variable is local or global. Recursion is when a function calls itself, and is useful for breaking down complex problems into simpler sub-problems. Common recursive functions calculate factorials, Fibonacci numbers, and generate the Pascal's triangle.
This document provides an overview of key concepts in Java including Eclipse IDE, creating classes, the main method, printing output, variables, data types, user input, arithmetic operators, and typecasting. It explains how to create a Java class in Eclipse, use print statements, declare and initialize variables, take user input, and perform basic math operations and conversions between data types in Java.
OS | Functions of OS | Operations of OS | Operations of a process | Scheduling algorithms | FCFS scheduling | SJF scheduling | RR scheduling | Paging | File system implementation | Cryptography as a security tool
Problem | Problem v/s Algorithm v/s Program | Types of Problems | Computational complexity | P class v/s NP class Problems | Polynomial time v/s Exponential time | Deterministic v/s non-deterministic Algorithms | Functions of non-deterministic Algorithms | Non-deterministic searching Algorithm | Non-deterministic sorting Algorithm | NP - Hard and NP - Complete Problems | Reduction | properties of reduction | Satisfiability problem and Algorithm
What is Python? | Uses, features & flavours of Python | Running Python | Identifiers | key words | values & types | Type casting | Operators | Functions | Types of arguments
What is Endoscopy?
What are the complications of Endoscopy?
How Capsule endoscopy overcomes those problems?
What are the components of the capsule?
How does it works ?
Wondershare PDFelement Pro 11.4.20.3548 Crack Free DownloadPuppy jhon
➡ 🌍📱👉COPY & PASTE LINK👉👉👉 ➤ ➤➤ https://drfiles.net/
Wondershare PDFelement Professional is professional software that can edit PDF files. This digital tool can manipulate elements in PDF documents.
Integrating Survey123 and R&H Data Using FMESafe Software
West Virginia Department of Transportation (WVDOT) actively engages in several field data collection initiatives using Collector and Survey 123. A critical component for effective asset management and enhanced analytical capabilities is the integration of Geographic Information System (GIS) data with Linear Referencing System (LRS) data. Currently, RouteID and Measures are not captured in Survey 123. However, we can bridge this gap through FME Flow automation. When a survey is submitted through Survey 123 for ArcGIS Portal (10.8.1), it triggers FME Flow automation. This process uses a customized workbench that interacts with a modified version of Esri's Geometry to Measure API. The result is a JSON response that includes RouteID and Measures, which are then applied to the feature service record.
14 Years of Developing nCine - An Open Source 2D Game FrameworkAngelo Theodorou
A 14-year journey developing nCine, an open-source 2D game framework.
This talk covers its origins, the challenges of staying motivated over the long term, and the hurdles of open-sourcing a personal project while working in the game industry.
Along the way, it’s packed with juicy technical pills to whet the appetite of the most curious developers.
Providing Better Biodiversity Through Better DataSafe Software
This session explores how FME is transforming data workflows at Ireland’s National Biodiversity Data Centre (NBDC) by eliminating manual data manipulation, incorporating machine learning, and enhancing overall efficiency. Attendees will gain insight into how NBDC is using FME to document and understand internal processes, make decision-making fully transparent, and shine a light on underlying code to improve clarity and reduce silent failures.
The presentation will also outline NBDC’s future plans for FME, including empowering staff to access and query data independently, without relying on external consultants. It will also showcase ambitions to connect to new data sources, unlock the full potential of its valuable datasets, create living atlases, and place its valuable data directly into the hands of decision-makers across Ireland—ensuring that biodiversity is not only protected but actively enhanced.
Artificial Intelligence Applications Across IndustriesSandeepKS52
Artificial Intelligence is a rapidly growing field that influences many aspects of modern life, including transportation, healthcare, and finance. Understanding the basics of AI provides insight into how machines can learn and make decisions, which is essential for grasping its applications in various industries. In the automotive sector, AI enhances vehicle safety and efficiency through advanced technologies like self-driving systems and predictive maintenance. Similarly, in healthcare, AI plays a crucial role in diagnosing diseases and personalizing treatment plans, while in financial services, it helps in fraud detection and risk management. By exploring these themes, a clearer picture of AI's transformative impact on society emerges, highlighting both its potential benefits and challenges.
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdfVarsha Nayak
In recent years, organizations have increasingly sought robust open source alternative to Jasper Reports as the landscape of open-source reporting tools rapidly evolves. While Jaspersoft has been a longstanding choice for generating complex business intelligence and analytics reports, factors such as licensing changes and growing demands for flexibility have prompted many businesses to explore other options. Among the most notable alternatives to Jaspersoft, Helical Insight stands out for its powerful open-source architecture, intuitive analytics, and dynamic dashboard capabilities. Designed to be both flexible and budget-friendly, Helical Insight empowers users with advanced features—such as in-memory reporting, extensive data source integration, and customizable visualizations—making it an ideal solution for organizations seeking a modern, scalable reporting platform. This article explores the future of open-source reporting and highlights why Helical Insight and other emerging tools are redefining the standards for business intelligence solutions.
FME for Climate Data: Turning Big Data into Actionable InsightsSafe Software
Regional and local governments aim to provide essential services for stormwater management systems. However, rapid urbanization and the increasing impacts of climate change are putting growing pressure on these governments to identify stormwater needs and develop effective plans. To address these challenges, GHD developed an FME solution to process over 20 years of rainfall data from rain gauges and USGS radar datasets. This solution extracts, organizes, and analyzes Next Generation Weather Radar (NEXRAD) big data, validates it with other data sources, and produces Intensity Duration Frequency (IDF) curves and future climate projections tailored to local needs. This presentation will showcase how FME can be leveraged to manage big data and prioritize infrastructure investments.
Join the Denver Marketo User Group, Captello and Integrate as we dive into the best practices, tools, and strategies for maintaining robust, high-performing databases. From managing vendors and automating orchestrations to enriching data for better insights, this session will unpack the key elements that keep your data ecosystem running smoothly—and smartly.
We will hear from Steve Armenti, Twelfth, and Aaron Karpaty, Captello, and Frannie Danzinger, Integrate.
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentricNatan Silnitsky
At Wix, we revolutionized our platform by making integration events the backbone of our 4,000-microservice ecosystem. By abandoning traditional domain events for standardized Protobuf events through Kafka, we created a universal language powering our entire architecture.
We'll share how our "single-aggregate services" approach—where every CUD operation triggers semantic events—transformed scalability and extensibility, driving efficient event choreography, data lake ingestion, and search indexing.
We'll address our challenges: balancing consistency with modularity, managing event overhead, and solving consumer lag issues. Learn how event-based data prefetches dramatically improved performance while preserving the decoupling that makes our platform infinitely extensible.
Key Takeaways:
- How integration events enabled unprecedented scale and extensibility
- Practical strategies for event-based data prefetching that supercharge performance
- Solutions to common event-driven architecture challenges
- When to break conventional architectural rules for specific contexts
Insurance policy management software transforms complex, manual insurance operations into streamlined, efficient digital workflows, enhancing productivity, accuracy, customer service, and profitability for insurers. Visit https://www.damcogroup.com/insurance/policy-management-software for more details!
A brief introduction to OpenTelemetry, with a practical example of auto-instrumenting a Java web application with the Grafana stack (Loki, Grafana, Tempo, and Mimir).
Have you upgraded your application from Qt 5 to Qt 6? If so, your QML modules might still be stuck in the old Qt 5 style—technically compatible, but far from optimal. Qt 6 introduces a modernized approach to QML modules that offers better integration with CMake, enhanced maintainability, and significant productivity gains.
In this webinar, we’ll walk you through the benefits of adopting Qt 6 style QML modules and show you how to make the transition. You'll learn how to leverage the new module system to reduce boilerplate, simplify builds, and modernize your application architecture. Whether you're planning a full migration or just exploring what's new, this session will help you get the most out of your move to Qt 6.
AI and Deep Learning with NVIDIA TechnologiesSandeepKS52
Artificial intelligence and deep learning are transforming various fields by enabling machines to learn from data and make decisions. Understanding how to prepare data effectively is crucial, as it lays the foundation for training models that can recognize patterns and improve over time. Once models are trained, the focus shifts to deployment, where these intelligent systems are integrated into real-world applications, allowing them to perform tasks and provide insights based on new information. This exploration of AI encompasses the entire process from initial concepts to practical implementation, highlighting the importance of each stage in creating effective and reliable AI solutions.
In today's world, artificial intelligence (AI) is transforming the way we learn.
This talk will explore how we can use AI tools to enhance our learning experiences, by looking at some (recent) research that has been done on the matter.
But as we embrace these new technologies, we must also ask ourselves:
Are we becoming less capable of thinking for ourselves?
Do these tools make us smarter, or do they risk dulling our critical thinking skills?
This talk will encourage us to think critically about the role of AI in our education. Together, we will discover how to use AI to support our learning journey while still developing our ability to think critically.
3. CONTROLFLOW STATEMENTS ( if, if-else,if-elif-else) :
Decision making is the most important aspect of almost all the programming languages.
As the name implies, decision making allows us to run a particular block of code for a particular
decision.
Here, the decisions are made on the validity of the particular conditions. Condition checking is
the backbone of decision making.
Decision making statements in programming languages decides the direction of flow of program
execution.
decision making statements are: 1.if or simple if statement
2. if-else statement
3. elif statement
4. Nested if statement
4. 1. if or simple if statement:
The if statement is used to test a particular condition and if the condition is true, it
executes a block of code known as if-block.
The condition of if statement can be any valid logical expression which can be either
evaluated to true or false.
syntax :
if expression:
statement
Example 1
num = int(input("enter
the number:"))
if num%2 == 0:
print("Number is
even")
Output:
enter the number:10
Number is even
5. 2. if-else statement :
The if-else statement provides an else block combined with the if
statement which is executed in the false case of the condition.
If the condition is true, then the if-block is executed. Otherwise, the
else-block is executed.
Syntax:
if expression:
True block statements
else:
False block
statements
Example :
age = int (input("Enter your age: "))
if age>=18:
print("You are eligible to vote !!")
else:
print("Sorry! you have to wait !!")
Output:
Enter your age: 90
You are eligible to vote !!
6. 3. elif statement
The elif statement works like an if-else-if ladder statement in C. It must
be succeeded by an if statement.
Syntax:
if expression 1:
# block of statements
elif expression 2:
# block of statements
elif expression 3:
# block of statements
else:
# block of statements
Example 1:
number = int(input("Enter the number:"))
if number==10:
print("number is equals to 10")
elif number==50:
print("number is equal to 50");
elif number==100:
print("number is equal to 100");
else:
print("number is not equal to 10, 50 or 100");
Output:
Enter the number:15
number is not equal to 10, 50 or 100
7. 4. Nested if statements :
Nested if statements means an if statement inside another if statement.
Syntax:
if (condition1):
# condition1 is true
if (condition2):
# condition2 is true
# if Block is end here
# if Block is end here
Program:
i = 10
if (i == 10):
if (i < 15):
print ("i is smaller than 15")
if (i < 12):
print ("i is smaller than 12 too")
else:
print ("i is greater than 15")
Output:
i is smaller than 15
i is smaller than 12 too
8. Recursion:
A Function call itself again and
again is called recursion.
Ex:
def add():
……
add()
add()
Example
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
num = 3
print("The factorial
of",num,"is",factorial(num))
Output:
The factorial of 3 is 6
9. Infinite Recursion
Every recursive function must
have a base condition that stops
the recursion or else the function
calls itself infinitely.
The Python interpreter limits the
depths of recursion to help avoid
infinite recursions, resulting in
stack overflows.
By default, the maximum depth of
recursion is 1000. If the limit is
crossed, it results
in RecursionError.
EX:
def recursor():
recursor()
recursor()
Output
Traceback (most recent call last):
File "<string>", line 3, in <module>
File "<string>", line 2, in a
File "<string>", line 2, in a
File "<string>", line 2, in a
[Previous line repeated 996 more times]
RecursionError: maximum recursion depth
exceeded
10. Advantages of Recursion
1.Recursive functions make the code look clean and elegant.
2.A complex task can be broken down into simpler sub-problems using
recursion.
3.Sequence generation is easier with recursion than using some nested
iteration.
Disadvantages of Recursion
1.Sometimes the logic behind recursion is hard to follow through.
2.Recursive calls are expensive (inefficient) as they take up a lot of memory
and time.
3.Recursive functions are hard to debug.
11. Keyboard input
Input :
Python input() function is used to get input from the user.
It prompts for the user input and reads a line.
After reading data, it converts it into a string and returns that.
It throws an error EOFError if EOF(End Of File) is read.
Syntax:
Input([prompt])
prompt: It is a string message which prompts for the user input.
It returns user input after converting into a string
12. Example :
a = input("Enter a value: ")
print("You entered:",a)
Output:
Enter a value: 45
You entered: 45
here you should enter a
value through keyboard
Example :
a = input("Enter an integer: ")
val = int(a)
b = (val*val)
print("Multiplication of the value:",b)
Output:
Enter an integer: 12
Multiplication of the value: 144
13. Output function :
Print():
Python print () function prints the given output on the screen.
Syntax: print (object(s), sep=separator, end=end, file=file, flush=flush)
Example :
print(“Hi Selena ”)
Output:
Hi Selena
Example :
a=5
print(“The value of a is:”,a)
Output:
The value of a is:5
Example :
a,b=10,20
print(“The sum of a ,b is:”,a+b)
Output:
The sum of a , b is:30
14. We can also Use ‘+’ and ‘,’ operators in print():
+ adding two strings
, provide space between two strings
Example :
print(“Hi”+”Selena”)
Output
Hi Selena
Example :
print(“Hi”,”Selena”)
Output
Hi Selena
15. Output formatting
Sometimes we would like to format our output to make it look attractive.
This can be done by using the str.format() method.
This method is visible to any string object.
Ex: x = 5; y = 10
print(“The value of x is {} and y is {}”. format(x,y))
OUTPUT: The value of x is 5 and y is 10
Here the curly braces {} are used as placeholders. We can specify the order
in which it is printed by using numbers (tuple index).
16. Example 1 : 0 1
print(' Selena is {0} and {1}'.format('cute','pretty'))
Output:
Selena is cute and pretty
Example 2 : 0 1
print(' Selena is {1} and {0}'.format('cute','pretty'))
Output:
Selena is pretty and cute
17. Fruitful Functions:
These are the functions that return a value after their completion.
A fruitful function must always return a value to where it is called from.
A fruitful function can return any type of value may it be string, integer, boolean, etc.
It is not necessary for a fruitful function to return the value of one variable, the value
to be returned can be an array or a vector.
A fruitful function can also return multiple values.
Ex:
function add_f(a, b);
c = a + b;
return c;
d = add_f(3, 4);
print(d)
Output :
7
18. Incremental development
As you write larger functions, you might find yourself spending more time
debugging.
To deal with increasingly complex programs, you might want to try a process
called incremental development.
The goal of incremental development is to avoid long debugging sessions by
adding and testing only a small amount of code at a time.
Ex : suppose you want to find the distance between two points, given by the
coordinates (x1, y1) and (x2, y2). By the Pythagorean theorem, the distance is:
distance = (x2 − x1)2 + (y2 − y1) 2
The first step is to consider what a distance function should look like in Python.
In other words, what are the inputs (parameters) and what is the output (return
value)?
19. In this case, the two points are the inputs, which we can represent using four
parameters. The return value is the distance, which Is a floating-point value.
Immediately you can write an outline of the function:
def distance(x1, y1, x2, y2):
return 0.0
Obviously, this version doesn’t compute distances; it always returns zero. But it is
syntactically correct, and it runs which means that we can test it before we make it
more complicated.
To test the new function, we call it with sample values:
>>> distance(1, 2, 4, 6)
OUTPUT:0.0
We chose these values so that the horizontal distance equals 3 and the vertical
distance equals 4; that way, the result is 5 (the hypotenuse of a 3-4-5 triangle).
When testing a function, it is useful to know the right answer.
20. At this point we have confirmed that the function is syntactically correct, and
we can start adding lines of code. After each incremental change, we test the
function again.
If an error occurs at any point, we know where it must be in the last line we
added.
A logical first step in the computation is to find the differences x2- x1 and y2-
y1. We will refer to those values using temporary variables named dx and dy.
1.def distance(x1, y1, x2, y2):
2. dx = x2 - x1
3. dy = y2 - y1
4. return 0.0
If we call the function with the arguments shown above, when the flow of
execution gets to the return statement, dx should be 3 and dy should be
Next we compute the sum of squares of dx and dy:
21. 1.def distance(x1, y1, x2, y2):
2. dx = x2 - x1
3. dy = y2 - y1
4. dsquared = dx*dx + dy*dy
5. return 0.0
Again, we could run the program at this stage and check the value of dsquared (which
should be 25).
Finally, using the fractional exponent 0.5 to find the square root, we compute and
return the result:
1.def distance(x1, y1, x2, y2):
2. dx = x2 - x1
3. dy = y2 - y1
4. dsquared = dx*dx + dy*dy
5. result = dsquared**0.5
6. return result
If that works correctly, you are done.
22. Composition
you can call one function from within another. This ability is
called composition.
Example: we’ll write a function that takes two points, the center of the circle
and a point on the perimeter, and computes the area of the circle.
Assume that the center point is stored in the variables xc and yc, and the
perimeter point is in xp and yp.
The first step is to find the radius of the circle, which is the distance between
the two points.
Fortunately, we’ve just written a function, distance, that does just that, so now
all we have to do is use it:
1. radius = distance(xc, yc, xp, yp)
23. The second step is to find the area of a circle with that radius and return it.
Again we will use one of our earlier functions:
1 .result = area(radius)
2. return result
Wrapping that up in a function, we get:
1.def area2(xc, yc, xp, yp):
2. radius = distance(xc, yc, xp, yp)
3. result = area(radius)
4. return result
We called this function area2 to distinguish it from the area function defined
earlier.
24. The temporary variables radius and result are useful for development, debugging,
and single-stepping through the code to inspect what is happening, but once the
program is working, we can make it more concise by composing the function calls:
1. def area2(xc, yc, xp, yp):
2. return area(distance(xc, yc, xp, yp))
25. Leap Of Faith
Following the flow of execution is one way to read programs, but it can
quickly become overwhelming.
An alternative is what I call the “leap of faith”.
When you come to a function call, instead of following the flow of execution,
you assume that the function works correctly and returns the right result.
In fact, you are already practicing this leap of faith when you use built-in
functions.
.When you call math.cos or math.exp, you don’t examine the bodies of those
functions.
You just assume that they work because the people who wrote the built-in
functions were good programmers.
26. The same is true when you call one of your own functions.
For example above we wrote a function called is_divisible that determines
whether one number is divisible by another.
Once we have convinced ourselves that this function is correct—by
examining the code and testing—we can use the function without looking at
the body again.
The same is true of recursive programs.
27. Checking types
What happens if we call factorial and give it 1.5 as an argument?
>>> factorial(1.5)
RuntimeError: Maximum recursion depth exceeded
It looks like an infinite recursion. But how can that be? There is a base
case—when n == 0.
But if n is not an integer, we can miss the base case and recurse forever.
In the first recursive call, the value of n is 0.5.
In the next, it is -0.5. From there, it gets smaller (more negative), but it
will never be 0.
28. We have two choices. We can try
to generalize the factorial function
to work with floating-point
numbers, or we can make factorial
check the type of its argument.
The first option is called the
gamma function and it’s a little
beyond the scope of this book. So
we’ll go for the second.
We can use the built-in function
isinstance to verify the type of the
argument. While we’re at it, we can
also make sure the argument is
positive:
Program :
def factorial(n):
if not isinstance(n, int):
print('Factorial is only defined for integers.')
return None
elif n < 0:
print('Factorial is not defined for negative integers.')
return None
elif n == 0:
return 1
else:
return n * factorial(n-1)
29. The first base case handles nonintegers.
the second handles negative integers.
In both cases, the program prints an error message and returns None to
indicate that something went wrong:
>>> print(factorial('fred'))
OUTPUT: Factorial is only defined for integers. None
>>> print(factorial(-2))
OUTPUT: Factorial is not defined for negative integers. None
30. Turtle :
Turtle is a special feathers of Python. Using Turtle, we can easily draw in a
drawing board.
First we import the turtle module.
Then create a window.
Next we create turtle object and using turtle method we can draw in the
drawing board.
31. NAME PARAMETER DESCRIPTION
1.Turtle() None It creates and returns a
new turtle Object
2.forward() amount It moves the turtle forward by the
specified amount
3.backward() amount It moves the turtle backward by the
specified amount
4.right() angle It turns the turtle clockwise
5.left() angle It turns the turtle counter clockwise
6.penup() None It picks up the turtle’s Pen
7.pendown() None Puts down the turtle’s Pen
8.up() None Picks up the turtle’s Pen
9.down() None Puts down the turtle's Pen
10.color() Color name Changes the color of the turtle’s pen
32. NAME PARAMETER DESCRIPTION
11.fillcolor() Color name Changes the color of the turtle will
use to fill a polygon
12.heading() None It returns the current heading
13.position() None It returns the current position
14.goto() x, y It moves the turtle to position x,y
15.begin_fill() None Remember the starting point for a
filled polygon
16.end_fill() None It closes the polygon and fills with the
current fill color
17.dot() None Leaves the dot at the current position
18stamp() None Leaves an impression of a turtle shape
at the current location
19.shape() shapename Should be ‘arrow’, ‘classic’, ‘turtle’ or
‘circle’
33. The turtle module
The turtle Module provided by python software, it provide all turtle
methods to perform operations on turtle.
To check whether you have the turtle module, open the Python
interpreter and type
>>> import turtle
>>> bob = turtle.Turtle()
When you run this code, it should create a new window with small
arrow that represents the turtle.
To make use of the turtle methods and functionalities, we need to
import turtle.
for executing a turtle program follows 4 steps:
34. 1.Import the turtle module
2.Create a turtle to control.
3.Draw around using the turtle methods.
4.Run turtle.done().
35. 1.Import the turtle module:
before we can use turtle, we need to import it. We import it as :
1.from turtle import *
( or)
2. import turtle
After importing the turtle library and making all the turtle functionalities available to
us
2. Create a turtle to control:
we need to create a turtle.
The turtle module (with a lowercase ’t’) provides a function called Turtle (with an
uppercase ’T’) that creates a Turtle object, which we assign to a variable named skk.
skk = turtle.Turtle()