Condition list Python

Credit: Unsplash

In this fourth chapter of the Quick Code-Python series, we are going to understand and implement various Conditional and looping statements available in python. Along with that, we’ll see how to use list comprehension to write your code efficiently.

Note: I’ve written the Quick Code-Python series in a linear fashion so that even a newbie can follow along the series to get a grasp of what python can actually do. For folks that are good with the fundamentals, you can follow along with the series to refresh your concepts or choose any of the chapters in the series that you want to know more about.

Comparison Operators

Before understanding the conditional and looping statements, let’s understand what comparison and logical operators are. A comparison operator can be defined as comparing two values. The output would either be True or False [ boolean].

The basic comparison operators are given below,

Credit: engineering big data

Logical Operators

Logical Operators are mostly used in conditional statements, which when true executes the statements or when it is false doesn’t execute them. The most important logical operator that we would use in python are Logical AND, Logical OR.

If you are familiar with logical gates, then the same principle applies here.

Note that in the above explanation you can replace 0 as False and 1 as True. Example, TRUE and FALSE = FALSE , TRUE OR FALSE = TRUE and so on.

Conditional Statements

Conditional statements are if, elif, and else statements that we use in python in order to use them as checks to see if the given condition is true or false.

if the condition is True then the code within the if condition will run and if it is False then it won’t run.

elif the condition given in the elif is True then the code within the elif will run and if it is False it won’t run.

else when no other condition is True then the code within the else statement will run.

Code to block sam inside the college campus

Sam may trick us by using his friend's name to enter the campus, let’s make sure that doesn’t happen

Code to return only elements from the dictionary that are greater than 25. Note that there are more efficient ways to do this, but for now let’s do this with if condition.

Code to check if a randomly generated number and the user inputted number are the same

Code to indicate the number of digits in an integer

Code to find if a number is even or odd

Append marks to a list from a dictionary only if they are greater than 75

For Loop

Loops in python are used to check if a condition is true then they execute a chunk of code within the block continuously until the condition becomes false. The main looping statements in python are for, nested loops, while and other concepts such as list comprehension, range are also important to understand.

  • break[] is used to exit a for loop or a while loop
  • continue[] is used to skip the current block, and return to the For or while statement.

The i in the for loop is used to run through the loop and get the values for us from the list.

Using the break statement in the loop to break out of the loop

Using the Continue statement in the loop to print the odd numbers in a list

In the above code we are telling the for loop to check for even numbers and if it is true, then do nothing on the if condition and continue with the for loop. It would have been very difficult for us to do the same operation using only an if condition. We’ll have to write conditions for every element in a list and check if they are even or odd

credit meme overflow

Calculate the sum of the numbers in a list

Let’s give our student’s list an index using enumerate[]

List Comprehension

List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or a looping statement. They can also be created based upon a condition set upon a particular list and put the results in a new list.

Let’s see two versions of code to square the elements in the list using the normal method and the other version using list comprehension.

Without using list comprehension

Using list comprehension

Looks simple right !! I love list comprehensions because it allows me to not write more lines of code for simple list operations and calculations.

Credit: meme generator

Let’s take a look at another example, printing the square of even numbers from a given list

Without using list comprehension,

Using list comprehension,

Nested Loops

Nested loops are simply a loop within a loop. We can use a nested loop when we want to loop within the primary for a loop. An example would be printing multiplication tables.

Printing the 4th and 5th multiplication table

Let’s go through the above code to understand what’s going on.

The first For loop x, loops through 4 and 5 [upper limit-1 when using the range function]. When we are at 4[ starting the loop] we enter into another loop y which loops through 1 to 10. Then we print the tables using the print function. After completing the 4th table, i.e printing from 1 to 10, we move back to the x loop, start with 5 and print the same way.

Range

We use the range function in a for loop, to specify the number that iterates during the execution of a loop.

Indexes in the range start with 0 and end with [n-1].

Example : range[0,11] means iterate through 0 to 10

We can even use a step number in the range, to specify the increase or decrease in range while iterating the loop

While loop

A while loop can be used to execute a set of statements as long as a certain condition remains True. Remember to specify the condition in the end, else the program would run infinitely and you’ll have to interrupt and restart the kernel again. Trust me it’s happened to me multiple times, best to avoid that problem.

Credit: ah see it

Creating a simple while loop to print numbers

We’ll see how to run a loop keeping it Trueduring inital stage, while specifying the condition in the end.

Keep in mind that inserting a colon after a conditional or looping statement is mandatory so that the IDE would automatically indent the next block of code.

Credit: Meme generator

Some Practical examples using the above concepts

Printing the numbers from an input string using list comprehension

Printing every name in the list except ‘Kate’

Code to generate the following table

Print the numbers between a given range that are only even

Code to generate a password for a user using random letters, punctuations, numbers depending on the length that the user provides

Sorting the words in a sentence from the reply given by the user

Hope you’ve understood how to implement looping, conditional statements and using list comprehension to reduce the size of your code significantly.

Note: If you are reading the blog in a smartphone, the codes may not be very presentable to you. If you can’t understand the code properly, read the blog in a PC/MAC

Just reading the blog isn’t enough. Run the code by copy-pasting on an IDE. Change the variables for yourselves and see how the output changes. Finally, try to write your own code.

Check out the previous chapter of the Quick Code-Python series.

Video liên quan

Chủ Đề