Conditions and loops in python

Conditions and Loops in Python

What if you want to do some specific tasks when the string is «Python» and some other tasks when the string is «Java». To achieve this conditioning we can use conditional statements in python or any other language. When we want to do some task for n number of times or we want to loop through some specific list, we can use different types of loops in this kind of situation.

Conditional Statements in Python

Both conditional statements seem almost similar, and actually, they are. There is just a minor difference between these two statements. We will understand this difference using code examples. If you know any other language(s), you might be wondering if python has a switch case or not. NO, python does not have a switch case.

if-else

if(conditional expresson): statement else: statement 

If I have explained the if-else statement in plain English then it would be the «either this or that» statement.

Let’s assume if the string is java, I want to do the sum of two numbers else I want to multiply two numbers.

num1 = 5 num2 = 2 lang = 'java' if(lang=="java"): # check if value of lang variable is 'java' c = num1 + num2 print(c) else: c = num1 * num2 print(c) # OUTPUT: 7 
num1 = 5 num2 = 2 lang = 'java' if(lang!="java"): # check if value of lang variable is NOT 'java' c = num1 + num2 print(c) else: c = num1 * num2 print(c) # OUTPUT: 10 

It is not compulsory to use else part. You can use only if part as well. For example, add the string «Programming» to the existing string if it is «Python» or does nothing.

lang = 'Python' if(lang=="Python"): lang = lang +" Programming" print(lang) # Output: Python Programming lang = 'Java' if(lang=="Python"): lang = lang +" Programming" print(lang) # Output: Java 

Sometimes, you can go into the if statement using only variable as well. For example,

lang = 'Python' if(0): lang = lang +" Programming" print(lang) # OUTPUT: Python lang = 'Python' if(1): lang = lang +" Programming" print(lang) # OUTPUT: Python Programming lang = 'Python' if(True): lang = lang +" Programming" print(lang) # OUTPUT: Python Programming lang = 'Python' if(False): lang = lang +" Programming" print(lang) # OUTPUT: Python lang = 'Python' if(""): lang = lang +" Programming" print(lang) # OUTPUT: Python lang = 'Python' if("random string"): lang = lang +" Programming" print(lang) # OUTPUT: Python Programming lang = 'Python' if(None): lang = lang +" Programming" print(lang) # OUTPUT: Python lang = 'Python' if([1]): lang = lang +" Programming" print(lang) # OUTPUT: Python Programming lang = 'Python' if([]): lang = lang +" Programming" print(lang) # OUTPUT: Python lang = 'Python' if('a':1>): lang = lang +" Programming" print(lang) # OUTPUT: Python Programming lang = 'Python' if(<>): lang = lang +" Programming" print(lang) # OUTPUT: Python 

If we want to combine multiple conditions we can use and and or within the if statement.

lang = 'PYTHON' if(lang.isupper() and len(lang) > 2): print("Worked!") # OUTPUT: Worked! if(lang.islower() or len(lang) == 6): print("Worked again!") # OUPUT: Worked again! 

if-elif-else

if(conditional expresson): statement elif(conditional expresson): statement else: statement 

We use this conditional statement when we want to test more than one scenario. Let’s understand this by an example.

marks = 75 if(marks >= 34 and marks  50): print("Grade C!") elif(marks > 50 and marks  75): print("Grade B!") elif(marks > 75 and marks  100): print("Grade A!") elif(marks >= 0 and marks  34): print("FAIL!") else: print("Something is wrong!") # OUTPUT: Grade A! 

Be aware when you use multiple if and if-elif. A single error in your logic and all your code-base can throw an error. To understand this, see the below example.

marks = 75 if(marks > 75 and marks  100): print("Grade A!") elif(marks > 50): print("Grade B!") elif(marks >=34): print("Grade C!") else: print("Something is wrong!") print("-----------------------------------") marks = 75 if(marks > 75 and marks  100): print("Grade A!") if(marks > 50): print("Grade B!") if(marks >=34): print("Grade C!") """ OUTPUT: Grade B! ----------------------------------- Grade B! Grade C! """ 

Loops in Python

In python, we have two kinds of loops.

for Loop in Python

for iterator in sequence: statement(s) 

For loop is used when we want to traverse through the sequential datatype. For example traversing through lists, tuples, strings etc.

fruits = ['apple', 'banana', 'mango', 'grapes', 'peach'] for fruit in fruits: print(fruit) """ OUTPUT: apple banana mango grapes peach """ for i in range(len(fruits)): print(fruits[I]) """ OUTPUT: apple banana mango grapes peach """ 

In the first example above, in the fruit variable, we are directly getting each element of the fruits list. Whereas, in the second example, we are accessing each element by index reference. The range(n) function returns a sequence of numbers.
Syntax: range(start, stop, step) .

for i in range(2, 13, 3): print(i) """ OUTPUT: 2 5 8 11 """ 

We can use for loop with dictionaries as well.

dict1 = "lang": "python", "year": "2021", "month": "november"> for item in dict1: print(item, ":" , dict1[item]) """ OUTPUT: lang : python year : 2021 month : november """ 

Источник

The Basics of Python Loops

The Basics of Python Loops

Python is one of the most popular and versatile programming languages available today, deployed across many industries and used for web development, machine learning, and data science. Given its widespread use, particularly in such in-demand (and interrelated) fields as machine learning and big data, it’s not surprising that Python has surpassed Java as the top programming language.

In this article, we will be learning about Python loops, including the different types of loops and how conditional statements work.

Basics to Advanced — Learn It All!

What Are Python loops?

A loop is an instruction that repeats multiple times as long as some condition is met.

flowchart.

Fig: Flowchart of Python loop

Significance of indentation

Indentation is significant in Python. It is used to define a block of code; without indentation, the program will show an error.

Type of Loops

There are mainly two types of loops. Let’s discuss them one by one.

1. For Loop

A for loop in Python is used to iterate over a sequence (list, tuple, set, dictionary, and string).

for-loop

Fig: Flowchart of a for loop

Syntax: for iterating_var in sequence:

for-loop-ex.

The preceding code executes as follows: The variable i is a placeholder for every item in your iterable object. The loop iterates as many times as the number of elements and prints the elements serially.

2. While Loop

The while loop is used to execute a set of statements as long as a condition is true.

whileloop

Syntax: while expression:

while-loop

The preceding code executes as follows: We assign the value to variable x as 1. Until the value of x is less than 3, the loop continues and prints the numbers.

Automation Test Engineer Master’s Program

3. Nested Loop

If a loop exists inside the body of another loop, it is called a nested loop.

nested-loop

The preceding code executes as follows: The program first encounters the outer loop, performing its first iteration. This first iteration triggers the inner, nested loop, which then runs to completion. Then the program returns to the top of the outer loop, completing the second iteration and again triggers the nested loop. The nested loop runs to completion, and the program returns to the top of the outer loop until the sequence is complete.

Conditional Statements in Python

Decision-making statements are used to execute the statements only when a particular condition is fulfilled.

conditional-statement

Fig: Conditional statement flowchart

There are three main types of conditional statements. They are:

1. If statement: The if statement is used to test a specific condition. If the condition is true, a block of code is executed.

Syntax: if expression:

flowchart-if

Fig: flowchart of if statement in Python loop

if

Fig: if statement in Python loop

2. Else statement: The else statement is executed when the expression in the if condition is false.

else-flow

Fig: else flowchart in Python loop

/else-state

3. Elif statement: The elif statement in Python enables you to check multiple conditions and execute specific blocks of statements if the previous conditions were false.

elif-stat.

Fig: elif statement in Python

Practice Exercises

It’s time to test our understanding with these practice exercises. We will suggest trying to solve the questions on your own.

Question 1: Write a program to check if the given number is prime or not.

sol-1.

The preceding code executes as follows: You assign value to a variable number. If the number entered is greater than 1, you check for factors of that number. If a factor is found, it is not a prime number. Otherwise, the given number is a prime number.

Question 2: Write a program to print the numbers from 1 to 10. Exit the loop if the number becomes equal to 6.

The preceding code executes as follows: Until the value of myNum does not become equal to myVar, the while loop iterates. As soon as the value becomes equal, the loop breaks.

Learn data operations in Python, strings, conditional statements, error handling, and the commonly used Python web framework Django. Check out Simplilearn’s Post Graduate Program In Full Stack Web Development.

Master Python and Increase Your Stock as a Programmer

Mastering the popular and highly versatile Python programming language is a great way to enter the exciting fields of data science, artificial intelligence, and machine learning. Consider signing up for Simplilearn’s Post Graduate Program In Full Stack Web Development, which provides a great foundation for this dynamic programming language.

Источник

Читайте также:  View html in safari
Оцените статью