This document discusses compound statements, control flow statements, and loops in Python. It begins by defining compound statements as groups of statements executed as a unit with specific patterns. It then explains the different types of control flow statements - sequence, selection, and iteration. Sequence refers to statements executed sequentially, selection allows execution based on conditions, and iteration repeats statements. The document discusses if, if-else, and nested if statements for selection. It also covers while and for loops for iteration. Finally, it briefly mentions the continue and break statements that can be used within loops to skip iterations or exit loops early.
The document discusses different types of conditional and control statements in Python programming. It describes if, if-else, if-elif-else statements for decision making or conditional execution. It also covers while and for loops as control structures for repetitive execution of code. Nested if statements allow conditional blocks within other conditional blocks. While and for loops can have optional else blocks that execute after the loop completes without breaking.
The document discusses different types of conditional statements in Python including if, if-else, nested if, and while loops. It provides examples of using each statement to check conditions, execute code blocks, and iterate through lists and ranges of numbers. Key conditional statements in Python allow conditionally executing code, checking for multiple conditions, and stopping or continuing iterations of loops.
1. The Python if statement is used to execute code conditionally based on the evaluation of an expression. It can be used with simple conditions, if-else statements, and nested if statements.
2. Python if-else statements allow executing one block of code if a condition is true and another block if the condition is false.
3. Nested if statements in Python allow checking multiple conditions, with inner if statements executing only if the outer conditions are met.
The document discusses various programming concepts in Python including conditional statements, loops, functions, and random number generation. Conditional statements like if, if-else, and nested if are used to perform tasks based on conditions. Loops like while and for are used for sequential traversal and repetition. Functions allow reusable blocks of code and can accept parameters and return values. The random and randint functions in Python can generate random floating numbers and integers within a given range for probabilistic behavior.
Types of Statements in Python Programming LanguageExplore Skilled
Â
The slide describes the types of flow control statements in Python including conditional statement , loop statement , control statement such as break and continue .
The document discusses different types of conditional and control statements in Python including if, if-else, elif, nested if-else, while, for loops, and else with loops. It provides the syntax and examples of each statement type. The if statement and if-else statement are used for simple decision making. The elif statement allows for multiple conditions. Nested if-else allows if statements inside other conditionals. While and for loops are used to repeatedly execute code while/for a condition remains true. The else statement with loops executes code if the entire loop finishes without breaking.
Python uses indentation to define code blocks for decision making statements like if, elif and else. The if statement executes code if a condition is true, elif allows checking multiple conditions, and else runs code if all conditions are false. Loops like while and for repeat code, with while looping until a condition is false and for iterating over a sequence. Nested loops can run inner loops multiple times during outer loop iterations. The else block after a for runs if all iterations complete without breaking from the loop.
The document discusses different types of conditional and control statements in Python programming. It describes if, if-else, if-elif-else statements for decision making or conditional execution. It also covers while and for loops as control structures for repetitive execution of code. Nested if statements allow conditional blocks within other conditional blocks. While and for loops can have optional else blocks that execute after the loop completes without breaking.
The document discusses different types of conditional statements in Python including if, if-else, nested if, and while loops. It provides examples of using each statement to check conditions, execute code blocks, and iterate through lists and ranges of numbers. Key conditional statements in Python allow conditionally executing code, checking for multiple conditions, and stopping or continuing iterations of loops.
1. The Python if statement is used to execute code conditionally based on the evaluation of an expression. It can be used with simple conditions, if-else statements, and nested if statements.
2. Python if-else statements allow executing one block of code if a condition is true and another block if the condition is false.
3. Nested if statements in Python allow checking multiple conditions, with inner if statements executing only if the outer conditions are met.
The document discusses various programming concepts in Python including conditional statements, loops, functions, and random number generation. Conditional statements like if, if-else, and nested if are used to perform tasks based on conditions. Loops like while and for are used for sequential traversal and repetition. Functions allow reusable blocks of code and can accept parameters and return values. The random and randint functions in Python can generate random floating numbers and integers within a given range for probabilistic behavior.
Types of Statements in Python Programming LanguageExplore Skilled
Â
The slide describes the types of flow control statements in Python including conditional statement , loop statement , control statement such as break and continue .
The document discusses different types of conditional and control statements in Python including if, if-else, elif, nested if-else, while, for loops, and else with loops. It provides the syntax and examples of each statement type. The if statement and if-else statement are used for simple decision making. The elif statement allows for multiple conditions. Nested if-else allows if statements inside other conditionals. While and for loops are used to repeatedly execute code while/for a condition remains true. The else statement with loops executes code if the entire loop finishes without breaking.
Python uses indentation to define code blocks for decision making statements like if, elif and else. The if statement executes code if a condition is true, elif allows checking multiple conditions, and else runs code if all conditions are false. Loops like while and for repeat code, with while looping until a condition is false and for iterating over a sequence. Nested loops can run inner loops multiple times during outer loop iterations. The else block after a for runs if all iterations complete without breaking from the loop.
The document discusses different types of conditional and control statements in Python including if, if-else, elif, nested if-else, while, for loops, and else with loops.
It provides the syntax and examples of each statement type. The if statement and if-else statement are used for simple decision making. The elif statement allows for chained conditional execution with more than two possibilities. Nested if-else allows if/elif/else statements within other conditionals. While and for loops are used to repeatedly execute blocks of code, with while looping until a condition is false and for looping over sequences. The else statement with loops executes code when the loop condition is false.
Python Session - 4
if
nested-if
if-else
elif (else if)
for loop (for iterating_var in sequence: )
while loop
break
continnue
pass
What is a function in Python?
Types of Functions
How to Define & Call Function
Scope and Lifetime of variables
lambda functions(anonymous functions)
The document provides an introduction to object-oriented programming concepts in C++ including objects, classes, data abstraction, encapsulation, inheritance, polymorphism, dynamic binding, and message passing. It then describes the structure of a C++ program including include files, class definitions, data declarations, member functions, and main functions. Finally, it discusses control structures in C++ including decision making statements like if/else and switch statements, looping statements like while, do-while and for loops, and functions.
Operators and expressions are fundamental concepts in Python programming. The document discusses various types of operators used to manipulate operands, including arithmetic, comparison, assignment, logical, bitwise, and membership operators. It also covers expressions, which are combinations of operators and operands that evaluate to a value. Several types of expressions are described, such as constant, arithmetic, integral, floating, relational, logical, bitwise, and combinational expressions. Control flow statements like if, if-else, if-elif-else are also covered, along with looping using for and while loops and the break, continue, and pass statements.
INTRODUCTION TO PYTHON PROGRMMING AND FUNCTIONSKalaivaniD12
Â
A function is a block of reusable code that performs a specific task. Functions provide modularity and code reusability. To define a function in Python, you use the def keyword followed by the function name and parentheses. Any parameters go inside the parentheses. The function body is indented and starts with a colon. A return statement exits the function and optionally returns a value. Functions can take arguments which are values passed when calling the function. Arguments can have default values. Functions return None by default if there is no return statement.
This document discusses different types of flow control in Python programs. It explains that a program's control flow defines the order of execution and can be altered using control flow statements. There are three main types of control flow: sequential, conditional/selection, and iterative/looping.
Sequential flow executes code lines in order. Conditional/selection statements like if/else allow decisions based on conditions. Iterative/looping statements like for and while loops repeat code for a set number of iterations or as long as a condition is true. Specific conditional statements, loops, and examples are described in more detail.
The document discusses various programming concepts in C# including namespaces, data conversion, relational operators, Boolean expressions, and conditional control structures like if, else if, and switch statements. Namespaces are used to organize code elements and create unique types. The Convert class contains methods for converting between data types like strings and numbers. Conditional statements like if/else and switch/case allow for executing different blocks of code depending on conditional expressions being true or false.
The document discusses various concepts related to data, expressions, and statements in Python programming. It begins by defining an interpreter as a program that executes instructions in a programming language. It then discusses invoking the Python interpreter in both script and interactive modes. In interactive mode, the interpreter provides immediate feedback for each statement. The document also defines various Python concepts like values and variables, keywords, expressions, operators, data types, functions, and control flow. It provides examples to illustrate function definition and calls, math functions, and basic Python programs to swap variables, check leap years, and convert Celsius to Fahrenheit.
The document provides an introduction and tutorial to the Python programming language. It covers 13 chapters that introduce very basic Python concepts up to more advanced topics like classes and CGI programming. The chapters include variables, data types, operators, conditionals, functions, iteration, strings, collection data types, exception handling, modules, files, documentation, and classes. The document also notes several sources that were used to create the tutorial and provides example code snippets throughout to demonstrate the concepts discussed.
Slides for Lecture 1 of the course: Introduction to Programming with Python offered at ICCBS.
It covers the following topics:
1.) Variables, Statements and Expressions
2.) Functions
3.) Flow Control
The document discusses Python control structures including if-else statements, indentation, and loops. It provides examples of if statements, if-else statements, nested if statements, and elif statements to test conditions and execute code blocks accordingly. It also discusses for loops and the range() function to iterate through sequences and generate number sequences to repeat code. Loops simplify problems by allowing code to repeat without rewriting and help traverse data structures.
This document discusses decision making and loops in Python. It describes the different types of decision making statements like IF, IF-ELSE, and nested IF statements. It also explains while and for loops used to repeat a block of code. Additionally, it covers loop control statements such as break, continue, and pass that alter normal loop execution.
The document discusses various control structures and functions used in Arduino programming including decision making structures like if, else if, else statements and switch case statements. It also covers different types of loops like while, do-while and for loops that allow repeating blocks of code. Functions are described as reusable blocks of code that perform tasks and help organize a program. Strings can be implemented as character arrays or using the String class, and various string functions are provided to manipulate and work with strings.
Complete Information till 2D arrays. In this slides you can also find information about loops and control decision....
Best slides for beginners who wants to learn about C programming language..
This document provides an outline and overview of a presentation on learning Python for beginners. The presentation covers what Python is, why it is useful, how to install it and common editors used. It then discusses Python variables, data types, operators, strings, lists, tuples, dictionaries, conditional statements, looping statements and real-world applications. Examples are provided throughout to demonstrate key Python concepts and how to implement various features like functions, methods and control flow. The goal is to give attendees an introduction to the Python language syntax and capabilities.
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.
The document discusses various control flow statements in Python including conditional statements like if, if-else, if-elif-else, loop statements like while and for loops, and jump statements like break and continue. Indentation is used to declare blocks in Python instead of curly braces or parentheses. Conditional statements allow performing different computations depending on conditions. Loop statements repeat a block of code a specified number of times. Jump statements alter the flow of loops by skipping or terminating parts of a loop.
The document discusses different types of conditional and control statements in Python including if, if-else, elif, nested if-else, while, for loops, and else with loops.
It provides the syntax and examples of each statement type. The if statement and if-else statement are used for simple decision making. The elif statement allows for chained conditional execution with more than two possibilities. Nested if-else allows if/elif/else statements within other conditionals. While and for loops are used to repeatedly execute blocks of code, with while looping until a condition is false and for looping over sequences. The else statement with loops executes code when the loop condition is false.
Python Session - 4
if
nested-if
if-else
elif (else if)
for loop (for iterating_var in sequence: )
while loop
break
continnue
pass
What is a function in Python?
Types of Functions
How to Define & Call Function
Scope and Lifetime of variables
lambda functions(anonymous functions)
The document provides an introduction to object-oriented programming concepts in C++ including objects, classes, data abstraction, encapsulation, inheritance, polymorphism, dynamic binding, and message passing. It then describes the structure of a C++ program including include files, class definitions, data declarations, member functions, and main functions. Finally, it discusses control structures in C++ including decision making statements like if/else and switch statements, looping statements like while, do-while and for loops, and functions.
Operators and expressions are fundamental concepts in Python programming. The document discusses various types of operators used to manipulate operands, including arithmetic, comparison, assignment, logical, bitwise, and membership operators. It also covers expressions, which are combinations of operators and operands that evaluate to a value. Several types of expressions are described, such as constant, arithmetic, integral, floating, relational, logical, bitwise, and combinational expressions. Control flow statements like if, if-else, if-elif-else are also covered, along with looping using for and while loops and the break, continue, and pass statements.
INTRODUCTION TO PYTHON PROGRMMING AND FUNCTIONSKalaivaniD12
Â
A function is a block of reusable code that performs a specific task. Functions provide modularity and code reusability. To define a function in Python, you use the def keyword followed by the function name and parentheses. Any parameters go inside the parentheses. The function body is indented and starts with a colon. A return statement exits the function and optionally returns a value. Functions can take arguments which are values passed when calling the function. Arguments can have default values. Functions return None by default if there is no return statement.
This document discusses different types of flow control in Python programs. It explains that a program's control flow defines the order of execution and can be altered using control flow statements. There are three main types of control flow: sequential, conditional/selection, and iterative/looping.
Sequential flow executes code lines in order. Conditional/selection statements like if/else allow decisions based on conditions. Iterative/looping statements like for and while loops repeat code for a set number of iterations or as long as a condition is true. Specific conditional statements, loops, and examples are described in more detail.
The document discusses various programming concepts in C# including namespaces, data conversion, relational operators, Boolean expressions, and conditional control structures like if, else if, and switch statements. Namespaces are used to organize code elements and create unique types. The Convert class contains methods for converting between data types like strings and numbers. Conditional statements like if/else and switch/case allow for executing different blocks of code depending on conditional expressions being true or false.
The document discusses various concepts related to data, expressions, and statements in Python programming. It begins by defining an interpreter as a program that executes instructions in a programming language. It then discusses invoking the Python interpreter in both script and interactive modes. In interactive mode, the interpreter provides immediate feedback for each statement. The document also defines various Python concepts like values and variables, keywords, expressions, operators, data types, functions, and control flow. It provides examples to illustrate function definition and calls, math functions, and basic Python programs to swap variables, check leap years, and convert Celsius to Fahrenheit.
The document provides an introduction and tutorial to the Python programming language. It covers 13 chapters that introduce very basic Python concepts up to more advanced topics like classes and CGI programming. The chapters include variables, data types, operators, conditionals, functions, iteration, strings, collection data types, exception handling, modules, files, documentation, and classes. The document also notes several sources that were used to create the tutorial and provides example code snippets throughout to demonstrate the concepts discussed.
Slides for Lecture 1 of the course: Introduction to Programming with Python offered at ICCBS.
It covers the following topics:
1.) Variables, Statements and Expressions
2.) Functions
3.) Flow Control
The document discusses Python control structures including if-else statements, indentation, and loops. It provides examples of if statements, if-else statements, nested if statements, and elif statements to test conditions and execute code blocks accordingly. It also discusses for loops and the range() function to iterate through sequences and generate number sequences to repeat code. Loops simplify problems by allowing code to repeat without rewriting and help traverse data structures.
This document discusses decision making and loops in Python. It describes the different types of decision making statements like IF, IF-ELSE, and nested IF statements. It also explains while and for loops used to repeat a block of code. Additionally, it covers loop control statements such as break, continue, and pass that alter normal loop execution.
The document discusses various control structures and functions used in Arduino programming including decision making structures like if, else if, else statements and switch case statements. It also covers different types of loops like while, do-while and for loops that allow repeating blocks of code. Functions are described as reusable blocks of code that perform tasks and help organize a program. Strings can be implemented as character arrays or using the String class, and various string functions are provided to manipulate and work with strings.
Complete Information till 2D arrays. In this slides you can also find information about loops and control decision....
Best slides for beginners who wants to learn about C programming language..
This document provides an outline and overview of a presentation on learning Python for beginners. The presentation covers what Python is, why it is useful, how to install it and common editors used. It then discusses Python variables, data types, operators, strings, lists, tuples, dictionaries, conditional statements, looping statements and real-world applications. Examples are provided throughout to demonstrate key Python concepts and how to implement various features like functions, methods and control flow. The goal is to give attendees an introduction to the Python language syntax and capabilities.
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.
The document discusses various control flow statements in Python including conditional statements like if, if-else, if-elif-else, loop statements like while and for loops, and jump statements like break and continue. Indentation is used to declare blocks in Python instead of curly braces or parentheses. Conditional statements allow performing different computations depending on conditions. Loop statements repeat a block of code a specified number of times. Jump statements alter the flow of loops by skipping or terminating parts of a loop.
Strategies for Effective Upskilling is a presentation by Chinwendu Peace in a Your Skill Boost Masterclass organisation by the Excellence Foundation for South Sudan on 08th and 09th June 2024 from 1 PM to 3 PM on each day.
How to Manage Your Lost Opportunities in Odoo 17 CRMCeline George
Â
Odoo 17 CRM allows us to track why we lose sales opportunities with "Lost Reasons." This helps analyze our sales process and identify areas for improvement. Here's how to configure lost reasons in Odoo 17 CRM
The simplified electron and muon model, Oscillating Spacetime: The Foundation...RitikBhardwaj56
Â
Discover the Simplified Electron and Muon Model: A New Wave-Based Approach to Understanding Particles delves into a groundbreaking theory that presents electrons and muons as rotating soliton waves within oscillating spacetime. Geared towards students, researchers, and science buffs, this book breaks down complex ideas into simple explanations. It covers topics such as electron waves, temporal dynamics, and the implications of this model on particle physics. With clear illustrations and easy-to-follow explanations, readers will gain a new outlook on the universe's fundamental nature.
Executive Directors Chat Leveraging AI for Diversity, Equity, and InclusionTechSoup
Â
Letâs explore the intersection of technology and equity in the final session of our DEI series. Discover how AI tools, like ChatGPT, can be used to support and enhance your nonprofit's DEI initiatives. Participants will gain insights into practical AI applications and get tips for leveraging technology to advance their DEI goals.
How to Make a Field Mandatory in Odoo 17Celine George
Â
In Odoo, making a field required can be done through both Python code and XML views. When you set the required attribute to True in Python code, it makes the field required across all views where it's used. Conversely, when you set the required attribute in XML views, it makes the field required only in the context of that particular view.
ā¤šā¤ŋā¤ā¤ĻāĨ ā¤ĩā¤°āĨā¤Ŗā¤Žā¤žā¤˛ā¤ž ā¤ĒāĨā¤ĒāĨā¤āĨ, hindi alphabet PPT presentation, hindi varnamala PPT, Hindi Varnamala pdf, ā¤šā¤ŋā¤ā¤ĻāĨ ā¤¸āĨā¤ĩā¤°, ā¤šā¤ŋā¤ā¤ĻāĨ ā¤ĩāĨā¤¯ā¤ā¤ā¤¨, sikhiye hindi varnmala, dr. mulla adam ali, hindi language and literature, hindi alphabet with drawing, hindi alphabet pdf, hindi varnamala for childrens, hindi language, hindi varnamala practice for kids, https://www.drmullaadamali.com
How to Setup Warehouse & Location in Odoo 17 InventoryCeline George
Â
In this slide, we'll explore how to set up warehouses and locations in Odoo 17 Inventory. This will help us manage our stock effectively, track inventory levels, and streamline warehouse operations.
How to Setup Warehouse & Location in Odoo 17 Inventory
Â
if else python.pdf
1. UNIT 4:SCRATCH OR PYTHON (THEORY AND PRACTICAL) 3. COMPOUND STATEMENT
A compound statement represents a
group of statements executed as a unit. The compound statements
of python are written in a specific pattern as shown in example.
Conditions and >>> testl=2
>>>test2=4
testi:
Loops in Python >>>
t test2:
print (test1)
Let's Recal
Write advantages and disadvantages ofPython.
What doyou mean by interactive mode programming and scripting mode of
programming?
STATEMENTS FLOW OF CONTROL
Statementl
SEQUENCE
Sequence means the statements are being executed sequentially. This represents the
default flow of statement.
Statement2
Let's Learn At the end of this chapter, you should be able to:
Comprehend and
useconditionalstatements: if, if-else statements
dComprehend and use loop structure: for, while
Statement3
Fig. 1 Flow of Control
Condition
SELECTION
The selection constructs means the execution of statements depending upon
a condition. If condition evaluates to true. a course -of-action (a set of
statements) is followed otherwise another course-of-action (a different set of
statements) is followed.
true false
Let's Begin Statement(s)
Python provides control statements that serves to state what has to be done by the program, when and
under which condition(s). This chapter discusses conditional and looping statements in detail.
Fig. 2 Flow of
STATEMENTS false
Selection Construct
Decision
tarementsarethe instructions given to
the computer to perform any kind of action such as, data ITERATION
movement, decision making, repetitive action etc. Statements form the smallest executable unit within a The iteration construct means repetition of a set-of-statements depending
upon a condition till the time a condition is true (or false depending upon the
loop). a set-of-statements are repeated again and again until the condition
becomes false (or true).
true
Python program. Statements are
always terminated by semicolon.
Sequence
TYPES OF STATEMENTS IN PYTHON
1. EMPTY STATEMENTS
The simplest statement is the empty statement, which has nothing. In python empty statement is
po
IF STATEMENT Fig. 3 Flow of Iteration
statement. The if statement is the conditional statement in python and it follows selection constructs (decision
constructs).
2. SiMPLE STATEMENT
The simplest form of if statements tests a condition and if the condition evaluates to true, it carries out
some instructions and does nothing in case condition evaluates to false.
It is comprised within a
single logical line.
For example: Syntax:
name=input ("ert.I u! ame") # thls is a
staement
if test expression:
-
statement(s)
Here, the program evaluates the test expression and will execute statement() only if the text
expression is True.
Conditions and Loops in Python
2. Output:
If the text expression is False. the statement(5) is not executed.
Test
false
In Python, the body of the if statement is indicated by the indentation. Body
tarts with an indentation and the first unintended line marks the end.
Expression Python console
Console 1/A 3
true
Python interprets non-zero values as True. None and 0 are interpreted as False.
Example 1: Print a given statement if the number is positive.
Body of if [8]:
In
Python 3.7.0 Shell
In [8]: runfile("D:/python class /statementsi.py', wdir='D: /python class ')
x is less than y
File Edit Shell Debug Options Window Help
PYEhon 3.7.0 (v3.7.0:lbf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Inte
1)) on win32 Fig. 4 Flowchart for
if Statement
2pcopyright
", "credits" or "license ()
"
for more information.
nun=3
>>> num>0:
In [9]:
print (num, "is a positive number. ")
rint("*his is à ways Tntea. ")
Example 3: Program to test the divisibility of a number with another number.
3 is a positive number
this is always printed. Spyder (Python 3.6)
File Edit Search Source Run Debug Consoles Projects Tools View Help
F-ELSE STATEMENT
Editor D:python_ dass 11felse stat.py
n else statement can be combined with an if statement. An else statement contains the block of code
nat executes if the conditional expression in the if statement resolves to 0 or a FALSE value.
The else statement is an optional statement and there could be at
nost only one else statement following if.
Syntax:
temp.Py ifelse stat.py
1
number1=int(input("enter first number: "))
2
number2=int(input(""enter second number: "))
3 remainder=number1%numberr2
4 if remainder==0:
Test False
Expression
The syntax of the if..else statement is -
print(number1, "is divisible by",number2)
if expression:
6 else:
True
statement(s)
print(number1, "is not divisible by", number2)
else:
Body of if Body ofelse
statement()
10
Example 2: Find out which is
greater Fig. 2 Flowchart for if..
Output:
Spyder (Python 3.6)
else statement
File Edit Search Source Run Debug Consoles Projects Tools View Help
IPython console
Console 1/A 3
Python 3.6.5 JAnaconda, Inc.| (default, Mar 29 2018, 13:32:41) [MSC v.1900 64 bit
(AMD64)]
Type copyright", "credits" or "license" for more information.
Editor D:python dass
_11statements1.py
{ temp.py" statements.py statementsi.py
-
1 Codin7: utf
2***
3 Created on iue Sep 18 i4:22:39 2018
IPython 6.4.0 -- An enhanced Interactive Python.
5"
In [1]: runfile( 'D:/python class /if else stat. .py', wdir='D: /python clàs ')
7 K=4
8y=5
9if(x*y):
10
print("x is less than y")
! else:
enter first number :123
enter second number: 23
print("y is greater than x"
123 is not divisible by 23
13
Conditions and Loops in Python
Computer Applica
cations
3. In a nested if construct. you can have an if..elif...else construct inside another if...elif...else construct.
IF-ELIF STATEMENT
ometimes a situation arises when there are several conditions. To handle such a situation. Python all
adding any number of. elif clause after an if and before an else clause.
allows Syntax:
if expressionl:
statement(s)
elif expression3: elif expression4:
statement{s)
Syntax: statement(s)
else:
ifexpressionl: elif expression2 : elifexpression3: if expression2: else: else:
statement1 statement_3 statement_5 statement_7 statements) statement() statement(s)
statement_2 statement_4 statement_6 statement_8 Example 5: Print a value depending on the given condition.
***********°°*
Spyder Python 3.6)
File Edit Search Source Run Debug Consoles Projects Tools View Help
.
Example 4: Program to input the marks of 5 subjects and display the grade.
Spyder (Python 3.6)
Editor-D:Python dass lnested f.py
Fie Edit Search Source Run Debug Consoles Projects Tools View Help
temp-Py eise zat.-py untted1.py 3 grade.py nestedif.py
1 var 16
2 if (var 200)
print ("Express ion value is less than 200")
if (var =
150)
print ("Which is 150")
elif (var = 100):
print (hich is 180")
elif (var ==
S0):
print( "uhich is 50")
elif( var < 50):
Editor - D:python dasS 11gradePY
tep-Py f elsesat.PY untrtledi.py grade.py
?subi=int(input("Enter marks of the first subject: "))
sub2-int (input("Enter marks of ihe second subject: "))
4 sub3=int(input("Enter marks of the third subject: "))
5
sub4=int(input("Enter marks of the fourth subject: "))
subS=int(input("Enter marks of the fifth subject: "))
avg=(subl+sub2+sub3+sub4+sub5) /5
S if(avg>90):
print("grade A")
telif(avg>=88 and avg<98)
11 print "Expressi0n value is less than 50")
2 else:
print (" Could not find true expression ")|
14
prirt grade )
12 elif(avg>=76 and avg<80):
13
print grade ")
14
elif(avg>=60 and avg<70)):
Output:
15 print("grade D")
16 else:
Python console
print("grade )
Console 1/A
Output: Expression value is less than 200
Which is 180
Enter manrks of the first subject: 78
In (3]:
Enter marks of the second subject: 98
Enter marks of the third subject: 95
LOOPING CONSTRUCTS
Enter marks of the fourth subject: 89 Loopsare used to repeatedly execute the same code in a program. Python provides two types of looping
Enter marks of the fifth subject: 85
constructs:
Erade While statement (condition based loop)
For statement (loop for a given number of times)
NESTED IF STATEMENT
InformationByte
There may be a situation when you want to check for another condition after a condition resoivE
true. In such a situation. you can use the nested if construct.
The iteration statements allow a setof instructions to be performed repeatedly until a certain condition is full filled. The
iteration statements are also called loops or looping statements.
252
Computer Application5
Onditions and LoopsinPy
253
4. RANGE) FUNCTION
What follows next is block of statement().
The statement(s) in BLOCK 1 keeps on
executing till condition in while remains True: once the
Before we start with loops, let us discuss range() function which Is used in for loop. range() fun..
generates a list and has a special sequence type. A sequence in python is a succession of values bound condition becomes False and if the else clause is written in while. then else will get executed. While loop
together by a single name. may not execute even once, if the condition evaluates to false, initially. as the condition is tested before
entering the loop.
Example 6: Print numbers 1 to 10.
Some python sequence types are: strings, list. tuples etc.
The common use of range() function are:
Spyder Python 3.6)
range(<lower limit>, <upper limit>) #both limits should be integers
File Edit Search Source Run Debug Consoles Projects Tools View Help
The function in the form range (1.u) will provide a list having values starting from l,1+1,1+2.
(u-1).
range(0,8) Editor D:python dass_11while.Py
list as[o.1.2.3,4.5.6.7] temp.py ifelse stat..py untitled1.py grade.py 3 nested f.py while.py
1 i-1
range(<lower limit>,<upper limit>,<step value>) #al values should be integers
range(l.u.5)
2 while(i <=10):
print (i),
i it1
gers
it will produce list having values as l, I+s, I+25..=u-1
range(0,10,2)
it will produce list as [O,2.4.6.8] Output:
range(5.0.-1) In [3]: runfile( 'D:/python_ class /vhile.py', wdir='D:/python_ <lass ")
list[5.4.3,2.1] 2
3
range(<number>)
it creates a list from O(zero) to <number>.
For example:
Range(5) 9
List as[o.1.2.3.4] 10
WHILE LoOP You can almost read the statement like English sentence. The first statement initialized the variable
(controlling loop) and then while evaluates the condition. which is True so the block of statements
It is a condition based loop.
written next will be executed.
Syntax:
Last statement in the block ensures that, with every execution of loop. loop control variable moves
while condition: # caondition is Boolean expression returning either True or False near to the termination point. If this does not happen then the loop will keep on executing infinitely.
STATEMENT BLOCK 1
As soon as i becomes 11, condition in while will evaluate to False and this will terminate the locop.
Telse: # optional part of while
STATEMENT BLOCK 2] NESTED WHILE LOOP
We can see that while looks like if statement. The staternent explains with keyword while foll
by a Boolean condition followed by colon (:).
Block of statement belonging to while can have another while statement, i.e., a while can contain another
ed
while.
254
Conditions and Loops in Python
255
r A P p l i c a t i o n
5. Example 8: Program to find the sum of all numbers stored in a list.
Example 7: Program with nested loop. Spyder (Python 3.6)
Spyder (Python 3.6) File Edit Search Source Run Debug Consoles Projects Tools View Help
File Edit Search Source Run Debug Consoles Projects Tools View HelpP
Editor- D:python_dass11forloop1.pPY
Cy ifelsestat..pyE untited1.py grade.py
Editor D:python dass_11nested while.py nested if.py while.py nested while.p
while.py nesi| 1# iist of.nunbers
untitled1.py grade.py nestedif.py
temp-py if
else stat..py s
2 numbers =
[6, 5, 3, 8, 4, 2, 5, 4, 11]
1 i = 1
4 # Variable tO store the sun
2j 5
Sum =
while 4:
while j < 8:
print(i, ",", i
4 i terate over the tist
8 for val in numbers:
9 sum = sum+val
LO
11
12 print(" The sum is", um)
Output: Output:
Python console
Python console
Console 1/A Console2/A Console 1/A
Python 3.6.5 |Anaconda, Inc.| (default, Mar 29 2018, 13:32:41) [MSC v.1900 64 bit
(AMD64) ]
Type "copyright", "credits" or "license" for more information.
Python 3.6.5 Anaconda, Inc.| (default, Mar 29 2018, 13:32:41) [MSC v.1900 64 bit
(AMD64)1
Type "copyright", "credits" or "license" for more information .
IPython 6.4.0 An enhanced Interactive Python.
IPython 6.4.0 -- An enhanced Interactive Python.
In [1]:
In 1: runfile( "b:/python class/nested while.py', wdir='D:/python class')
1 In [1]: runfile("D:/python_ class / for loop1.py', wdir='D:/python_ class')
The sum is 48
In [2]:
FOR LOODP NESTED FoR LooÃP
The for loop in Python is used to iterate over a sequence (list, tuple, string) or other objects. Iterating y contain arnotherloop in
its body. This is
called nested loop. But in nested loop. the inne
e
over a sequence is called traversal. loop must terminate before the outer loop. for loop can be nested within another for loop.
Syntax:
for each item
Example 9: Nested for loop.
in sequence
for <val> in <sequence>: Spyder (Python 3.6)
Body of for File Edit Search Source Run Debug Consoles Projects Tools View Help
es
Last i
Here, val is the variable that takes the value of the item inside the
reached
sequence on each iteration. Editor D:Python class_11nested forloop-pY
No
Loop continues until we reach the last item in the sequence. The body of
for loop is separated from the rest of the code using indentation.
statment3.py E3
1 for outer in range (6,10,4):
for inner in range(1,outer,2):
print (outer, inner)
nested for loop-py 3
Bodyoffor
Exit loop
ig. 3 Flowchart of for Loo
Conditions and Loops in Python
256 257
o m p u t e r
Applications
i o n s
andL
6. cONTINUE STATEMENT
Output: Enter loop
The continue statement is used to skip the rest of the code inside a loop
for the current iteration only. Loop does not terminate but continues on
n 1: runfile( D:/python lass /nested for loop.py', wdir='D:/python class")
Test
False
expression of
oop
6 3 with the next iteration.
Syntax:
True
Continue
JUMP STATEMENTSs BREAKANDCONTINUE
Yes
Python offers two jump statements to be used within loops tojump out of loop-iterations. These
break and continue statements.
s. These are Example 11: Program using continue Statement. Continue?
Spyder(Python3.6)
File Edit Search Source Run Debug Consoles Projects Tools View Help
Enter loop |No
Exit
loOP
THE BREAK STATEMENT Test Remaining8
False Editor-D:python cass 11continuel.py
body ofloop
Ihe break statement terminates the loop containing it. Control of
the program flows to the statement immediately after the body of
the loop.
expression of
looP
19y gradepy nestedfpy3 while.py3 nested wnie.py PYunon.py or oop1.g
Fig. 5 Flowchart of Continue
2 for val in "string":
True 3 if val == "i":
4 continue
If break statement is inside a nested loop (loop inside another
loop). break will terminate the innermost loop.
5 print(val1)
Yes
Break? 7 print(The end")
Syntax:
No
break
Output:
Exit
loop
Remaining
bodyofloop Tn [4]: runfile( 'D: /python_ class /continue1 .Py', wdir='D: /python_ class ")
Fig. 4 Flowchart of break
Example 10:
Theend
Spyder (Python 3.6)
File Edit Search Source Run Debug Consoles Projects Tools View Help
Example 12: Program to illustrate the difference between break and continue statement.
Spyder (Python3.6)
File Edit Search Source Run Debug Consoles Projects Tools View HelpP
Editor D:python dass_1iibreaki.py
at-py untitied.Py gade.py nested f-py while.py nested while.py Pyon
1 for val in "string" : Editor-D:ythonclass_11statment3.py
if val == "i": statment3.py
break 1 #break condit ion
print(val) 2print("the loop with break statement produces output as:
3 for i in range(1,10):
if ik2==0:
6 print(The end") 4
break
B else:
print(i
8 #cont inue condtit ion
Output: 9print("the loop with continue statement produces output as: ")
18 for i in range(1,10):
In [2]: runfile( D:/python_ class (break1.py', wdir='D:/python_ class ')
if ix2==0:
12 continue
t
L3 else:
4 print(i)
The end
Computer
plication Conditions and Loops in Python
259
258
7. Output: Ans. Ans. it will calculate square of numbers
enter an integer3
lass/statment3.py', wdir='D:/python
class
")
In [7]: runfile( D. /python
the loop with break statement produces output as
the loop with continue statement produces output as Q4. Find the output offollowing code.
=1
*2
1= 3 Q8. Write a program to check whether given numberis
even or odd.
sum=
ANS.
number=int (input ("enter any e"))
for i in (x.y.2): number$2==0:
if (isinstancei, int): print
(number,"i an even
nher")|
Lets Summarise Sum =sum+i print (number, "1s an dd nunber ")
print fsum)
Output:
Python supports selection orconditional statements.
There are three types ofstatements in python, namely emply statements, simple statements. compound statements.
The iteration constructs mean repetition of a set-of-Stalements depending upon a condition till the time a condition is true (or
Ans. enter any nunber12
n even nunber
Q5. What gets printed?
false depending upon the loop), a set-of-statements are repeated again and again. Q9. Program to print whetlher a given character is an
if x>3:
uppercase or a lowercase character or a digit or any
other character.
A Compound statement represents a group of statements executed as a unit.
if x>4:
------~----- -----*- printA",end=" ") AnS.
character iiput"entei d
ligL cia ")
Character>*' 11d charaCter<='2':
else:
Glossary haTActe .tLacter")
charact
printB".end="*")
, .
prnt("yo 7t
charactetx"i ' ai character<'':
P a t e i r u ilg
if(x!=0):
. Endless Loop: A loop that never ends or called infinite loop.
printc",end="*)
2 Empty Statement: A statement that appears in the code but does nothing.
3. Body: The blocks of statement in a compound statenments that follows the header.
print( D"
Ans. =RESTART:
D/python class/code3.py
Output:
********** RE.TART: D:/pytho ciess11/Gutputi.py **muanuzsa
4. Nested Loop: A loop contains another loop inside its body. D > ***
A iPytnon_ Class1/outputl.pY ***=e*au
5. teration: set of instructions to be performed repeatedly.
Q6. What gets printed? You entered i7t
6. Entry-controlled loop: that control over entry in the loop in the form of test condition.
temp=int(input(""enter temperature")
if temp<32:
************* RE3TART: D:/PYthon ciass11/output!.py ****aon**u
* ***** atacte?
print(ice") nrer . r a t e c P T O n Ca35 cutputi.Fy w*m*=n*a*me
Solved Questions elif temp<212: ya entered an uyperca3e chiaracter
*aaauw=mvananazanz RESTART: D:/python class
i/Gutpatl.9ÂĨ****
entez a single characer:ÂŽ
p C i a Charucter
print"water")
else:
Q1. Can you use one or more loop inside any another while, for or do.... while loop? print("steam")
Ans. Yes. Q10. Program to calculate the factorial of a number
Ans. enter temperature 37
Ans. nu1nt(input(enter a nnbe: "))
water
Q2 Write the name of loop which executes a sequence of statements multiple times and abbreviates the coue
manages the loop variable.
Tacc
>>>
acsnum:
"**
Ans. or-ioop. tact"
97 What would the follow ing code print if you input
the value 3?
a
printIactoti e Iact)
Q3. What is the output ofthe following?
i =0 n=intinput("enter an integer") Output:
while i < 3: if n<l: enter d unoEt
printii) print(invalid value")
else:
fori in range(1,n+1)
printi*i)
else: a c t o d l oL nnDer izU
Iactorial or numbeT 120
printi) Iactor1ai ot number 5040
260
mnuter Applicatio Conditions and Loops in Python
8. print("Input lengths of the triangie sides: ")
X = int (input ("x: "))
Y int (input("Y: "))
Z =
int (input("z: "))
Q11. Program to Reverse a Given Number Ans.
Ans. n=int (input("Enter number: "})
rev=0
.e(n>0)
dig=n$10
rev=rev*10+dig
n=n//10
print("ECquiiaterai triangle")
if x != y != z:
print("Reverse of the numioer: ", rev) print ("Scalene triarngie"))
Output: print("isosceles triangle")
Enter number: 123
Reverse of the number: 321
Output:
==== RESTART: D:/python class _11/pattern 3
Input engths of the triangle sides:
x:10
Y: 15
2: 19
Scalene triangle
Q12. Program to Print an Inverted Star Pattern.
n=int(input("Enter number of rows: "))
or i range (n,0,-1):
print (n-i) *
+ i * 'a'
Ans.
Output:
Enter number of rows: 4
==u====== RESTART: D:/python class 11/pattern
Input iengths of the triangle sides:
10
y: 10
2:
Equilatera! triangle
>>>
* * *
10
=== RESTART: D:/python class_1/pattern
Q13. Write a program to input 3 sides ofa triangle and
|Input 1engths of the triangle sides:
10
x
10
print whether and print whether it is an equilateral,
scalene or isosceles triangle.
Y:
z: 15
isosceles triangle