Writing compound statements in Python

Writing compound statements in Python

In this post, we'll learn about different compound statements including if condition, loop (while, for) statement, and loop control ( continue, break, pass) statement in Python

A compound statement is defined as a group of statements that affect or control the execution of other statements in some way. Python programming language provides different ways to construct or write compound statements. These are mainly defined as:

if Statement

This statement is used for conditional execution. The syntax of the statement is as follows,

if expression: suite  
elif expression: suite  
else: suite  

if statement evaluates the expressions (condition) one by one until one is found to be true then executes the following suite (a group of statements) for example

a, b = 10, 20  
if a > b:    
    print("a is greater than b")   
elif a < b:     
    print("b is greater than a")   
else:     
    print("Both a and b are equal") 

Python programming language allows us to use one if statement inside other if statement, for example:

a, b = 10, 20  
    
if a != b:   
    if a > b:   
        print("a is greater than b")   
    else:   
        print("b is greater than a")   
else:   
    print("Both a and b are equal")  

while Statement

while statement is used to execute a block of statements repeatedly until a given condition is fulfilled. Syntax of the statement is as follows

while expression:  
    statement(s)  

As we know that Python uses indentation as its method of grouping statements, statements after while expression: must be indented by the same number of character spaces otherwise they will not be considered as part of a single block of code. While statement executes repeatedly until a given condition is fulfilled and executes the statement immediately after the loop when the condition becomes false for example,

i = 1  
while i < 6:  
  print('inside while loop - printing value of i -', i)  
  i += 1  
  print('after while loop finished')

Else statement can also be used to execute a statement when the while condition becomes false

i = 1  
while i < 6:  
  print('inside while loop - printing value of i -', i);  
i += 1  
else :  
  print('after while loop finished') 

Please note that it is not recommended to use a while loop for iterators as mentioned in the above example instead of using for-in (or for each) loop method in Python.

for statement

for statement is used to traverse a list or string or array in a sequential manner for example

print("List Iteration")   
l = ["python", "for", "programmers"]   
for i in l:   
   print(i)  

There are few in-built Python functions available that take input as list or string or array etc. and iterate through elements of list or string or array and return index, data or both.

Range() method

Which returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number. Please refer to the example for more detail

print("List Iteration")   
l = ["python", "for", "programmers"]   
for i in range(len(l)):   
    print(l[i]) 

We can use for-in loop inside another for-in loop. we can even use any type of control statement condition inside of any other type of loop. Please refer to the example for more detail

print("List Iteration")   
carMake = ["Maruti", "Fiat", "Honda"]   
carModel = {'Maruti':'Alto', 'Fiat':'Punto', 'Honda':'Jazz'}  
for i in range(len(carMake)):   
    for x in carModel:  
        if(x==carMake[i]):  
            print("%s  %s" %(x, carModel[x]))  

Enumerate

Another built-in Python function that takes input as iterator, list etc. and returns a tuple containing index and data at that index in the iterator sequence. For example, enumerate (carMake), returns a iterator that will return (0, carMake[0]), (1, carMake[1]), (2, carMake[2]), and so on.

print("List Iteration")   
carMake = ["Maruti", "Fiat", "Honda"]   
for i, x in enumerate(carMake):  print("%s  %s" %(i, x))  

zip

Another in-built python function which is helpful to combine similar types of  iterators (list-list or dictionary- dictionary etc.) data items at ith position. It uses the shortest length of these input iterators. Other items of larger length iterators are skipped.

carMake = ["Maruti", "Fiat", "Honda"]   
carModel = ['Alto', 'Punto', 'Jazz']  
for m,mo in zip(carMake, carModel):   
   print("car %s is a product of %s" %(mo, m))  

try statement

The try statement specifies exception handlers and/or cleanup code for a group of statements.

_except _clause or statement is a place that contains code to handle the exception or error raised in try block and multiple except clauses while a single try statement clause can be added into the code. In the below example, print command will raise a ‘TypeError’ because %d is expecting integer value

print("List Iteration")   
carMake = ["Maruti", "Fiat", "Honda"]   
carModel = {'Maruti':'Alto', 'Fiat':'Punto', 'Honda':'Jazz'}  
try:  
    for i in range(len(carMake)):       
        for x in carModel:  
            if(x==carMake[i]):  
                print("%s  %d" %(x, carModel[x]))   
except TypeError:   
    print('oops! Type error -- ', t)  

  • You can include try-except statements within other try-except statements
  • finally: clause can be added to clean up the resources or objects
  • finally: block is a place to put any code that must execute, whether the try-block raised an exception or not

Please refer to the example for better understanding or implementation

print("List Iteration")   
carMake = ["Maruti", "Fiat", "Honda"]   
carModel = {'Maruti':'Alto', 'Fiat':'Punto', 'Honda':'Jazz'}  
try:  
    for i in range(len(carMake)):       
        for x in carModel:  
            if(x==carMake[i]):  
                print("%s  %d" %(x, carModel[x]))   
except TypeError as t:   
    print('oops! Type error -- ', t)  
except ValueError:  
    print('oops! incorrect value')  
finally:  
 print('Finally Code Execution - done');  

with statement

The with statement is used to wrap the execution of a block with methods defined by a context manager where a context manager is an object that defines the runtime context to be established. In the below example, accessing a file by using the open() function returns a file object that is being used for further execution.

with open("c:\welcome.txt") as file: # Use file to refer to the file object  
    data = file.read()  
    print(data)  

Loop Control Statements

The Loop control statement is meant to be used when you want to change the execution flow from its normal sequence, which means it either terminates the execution in between or transfers control to execute or skip the remaining code block. Python programming language supports the following loop control statements:

break

This statement terminates the loop statement and transfers execution to the statement immediately following the loop. In the below example it terminates the execution as soon as the first even number present in the list is found and printed

List = [15, 3, 4, 7, 5]  
print('find and print first even number present in the list %s' %List)  
for number in List:  
    if(number % 2 == 0):  
        print('%d is first even number present in the list' %number)  
 break;  
Continue

This statement causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating. In the below example it skips the execution the moment an odd number is found and continues iterating next items to find and print all the even numbers present in the list

List = [15, 3, 16, 9, 24, 4, 7, 5]  
evenNumbers = []  
print('find and print all even number present in the list %s' %List)  
for number in List:  
    if(number % 2 != 0):          
        continue;  
    else:  
        evenNumbers.append(number)  
              
print('even numbers %s present in the list ' %evenNumbers)  

pass

This statement causes the loop to pass the control to execute any additional code on a specific condition, then proceeds to execute the remainder of its body. In the below example pass is the execution control to double the number when an odd number is found then continue printing the numbers.

List = [15, 3, 16, 9, 24, 4, 7, 5]  
EvenNumbers = []  
print('double the number when odd number is found in the list %s' %List)  
for number in List:  
    x = number  
    if(x % 2 != 0):          
        pass  
        print('odd number %s found- double the number' %x)  
        x=x+x   
    else:  
        print('even number %s found- do nothing' %x)           
    print(x)  

Conclusion

We want learned about different compound statements including if condition, loop (while, for) statement, and loop control ( continue, break, pass) statement.

Thank for reading!

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

What’s new in HTML6

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Guide to Python Programming Language

Guide to Python Programming Language

Guide to Python Programming Language

Description
The course will lead you from beginning level to advance in Python Programming Language. You do not need any prior knowledge on Python or any programming language or even programming to join the course and become an expert on the topic.

The course is begin continuously developing by adding lectures regularly.

Please see the Promo and free sample video to get to know more.

Hope you will enjoy it.

Basic knowledge
An Enthusiast Mind
A Computer
Basic Knowledge To Use Computer
Internet Connection
What will you learn
Will Be Expert On Python Programming Language
Build Application On Python Programming Language

Best Way to Learn Python Programming Language | Python Tutorial

Best Way to Learn Python Programming Language | Python Tutorial

Worried that you have no experience in handling Python? Don’t! Python programming language teaching from Simpliv puts you right there to be able to write Python programs with ease. Place object-oriented programing in a Python context and use Python to perform complicated text processing.

Description
A Note on the Python versions 2 and 3: The code-alongs in this class all use Python 2.7. Source code (with copious amounts of comments) is attached as a resource with all the code-alongs. The source code has been provided for both Python 2 and Python 3 wherever possible.

What's Covered:

Introductory Python: Functional language constructs; Python syntax; Lists, dictionaries, functions and function objects; Lambda functions; iterators, exceptions and file-handling
Database operations: Just as much database knowledge as you need to do data manipulation in Python
Auto-generating spreadsheets: Kill the drudgery of reporting tasks with xlsxwriter; automated reports that combine database operations with spreadsheet auto-generation
Text processing and NLP: Python’s powerful tools for text processing - nltk and others.
Website scraping using Beautiful Soup: Scrapers for the New York Times and Washington Post
Machine Learning : Use sk-learn to apply machine learning techniques like KMeans clustering
Hundreds of lines of code with hundreds of lines of comments
Drill #1: Download a zip file from the National Stock Exchange of India; unzip and process to find the 3 most actively traded securities for the day
Drill #2: Store stock-exchange time-series data for 3 years in a database. On-demand, generate a report with a time-series for a given stock ticker
Drill #3: Scrape a news article URL and auto-summarize into 3 sentences
Drill #4: Scrape newspapers and a blog and apply several machine learning techniques - classification and clustering to these
Using discussion forums

Please use the discussion forums on this course to engage with other students and to help each other out. Unfortunately, much as we would like to, it is not possible for us at Loonycorn to respond to individual questions from students:-(

We're super small and self-funded with only 2 people developing technical video content. Our mission is to make high-quality courses available at super low prices.

The only way to keep our prices this low is to NOT offer additional technical support over email or in-person. The truth is, direct support is hugely expensive and just does not scale.

We understand that this is not ideal and that a lot of students might benefit from this additional support. Hiring resources for additional support would make our offering much more expensive, thus defeating our original purpose.

It is a hard trade-off.

Thank you for your patience and understanding!

Who is the target audience?

Yep! Folks with zero programming experience looking to learn a new skill
Machine Learning and Language Processing folks looking to apply concepts in a full-fledged programming language
Yep! Computer Science students or software engineers with no experience in Java, but experience in Python, C++ or even C#. You might need to skip over some bits, but in general the class will still have new learning to offer you :-)
Basic knowledge
No prior programming experience is needed :-)
The course will use a Python IDE (integrated development environment) called iPython from Anaconda. We will go through a step-by-step procedure on downloading and installing this IDE.
What will you learn
Pick up programming even if you have NO programming experience at all
Write Python programs of moderate complexity
Perform complicated text processing - splitting articles into sentences and words and doing things with them
Work with files, including creating Excel spreadsheets and working with zip files
Apply simple machine learning and natural language processing concepts such as classification, clustering and summarization
Understand Object-Oriented Programming in a Python context

Python Programming Tutorials For Beginners

Python Programming Tutorials For Beginners

Python Programming Tutorials For Beginners

Description
Hello and welcome to brand new series of wiredwiki. In this series i will teach you guys all you need to know about python. This series is designed for beginners but that doesn't means that i will not talk about the advanced stuff as well.

As you may all know by now that my approach of teaching is very simple and straightforward.In this series i will be talking about the all the things you need to know to jump start you python programming skills. This series is designed for noobs who are totally new to programming, so if you don't know any thing about

programming than this is the way to go guys Here is the links to all the videos that i will upload in this whole series.

In this video i will talk about all the basic introduction you need to know about python, which python version to choose, how to install python, how to get around with the interface, how to code your first program. Than we will talk about operators, expressions, numbers, strings, boo leans, lists, dictionaries, tuples and than inputs in python. With

Lots of exercises and more fun stuff, let's get started.

Download free Exercise files.

Dropbox: https://bit.ly/2AW7FYF

Who is the target audience?

First time Python programmers
Students and Teachers
IT pros who want to learn to code
Aspiring data scientists who want to add Python to their tool arsenal
Basic knowledge
Students should be comfortable working in the PC or Mac operating system
What will you learn
know basic programming concept and skill
build 6 text-based application using python
be able to learn other programming languages
be able to build sophisticated system using python in the future

To know more: