Python Loops Python loops allow us to execute a statement or group of statements multiple times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. There may be a situation when you need to execute a block of code several number of times. Programming languages provide various control structures that allow for more complicated execution paths. Flowchart of a Loop The following diagram illustrates a loop statement − Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career. Types of Loops in Python Python programming language provides following types of loops to handle looping requirements − Sr.No. Loop Type & Description 1 while loopRepeats a statement or group of statements while a given condition is TRUE. It tests the condition before executing the loop body. 2 for loopExecutes a sequence of statements multiple times and abbreviates the code that manages the loop variable. 3 nested loopsYou can use one or more loop inside any another while, for or do..while loop. Python Loop Control Statements Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. Python supports the following control statements. Click the following links to check their detail. Let us go through the loop control statements briefly Sr.No. Control Statement & Description 1 break statementTerminates the loop statement and transfers execution to the statement immediately following the loop. 2 continue statementCauses the loop to skip the remainder of its body and immediately retest its condition prior to reiterating. 3 pass statementThe pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute.
Match-Case Statement
Python match-case Statement A Python match-case statement takes an expression and compares its value to successive patterns given as one or more case blocks. Only the first pattern that matches gets executed. It is also possible to extract components (sequence elements or object attributes) from the value into variables. With the release of Python 3.10, a pattern matching technique called match-case has been introduced, which is similar to the switch-case construct available in C/C++/Java etc. Its basic use is to compare a variable against one or more values. It is more similar to pattern matching in languages like Rust or Haskell than a switch statement in C or C++. Syntax The following is the syntax of match-case statement in Python – Example The following code has a function named weekday(). It receives an integer argument, matches it with all possible weekday number values, and returns the corresponding name of day. Open Compiler On executing, this code will produce the following output − Thursday Sunday Invalid day number The last case statement in the function has “_” as the value to compare. It serves as the wildcard case, and will be executed if all other cases are not true. Combined Cases in Match Statement Sometimes, there may be a situation where for more than one cases, a similar action has to be taken. For this, you can combine cases with the OR operator represented by “|” symbol. Example The code below shows how to combine cases in match statement. It defines a function named access() and has one string argument, representing the name of the user. For admin or manager user, the system grants full access; for Guest, the access is limited; and for the rest, there’s no access. Open Compiler On running the above code, it will show the following result − Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career. List as the Argument in Match Case Statement Since Python can match the expression against any literal, you can use a list as a case value. Moreover, for variable number of items in the list, they can be parsed to a sequence with “*” operator. Example In this code, we use list as argument in match case statement. Open Compiler On executing, this code will produce the following output − Using “if” in “Case” Clause Normally Python matches an expression against literal cases. However, it allows you to include if statement in the case clause for conditional computation of match variable. Example In the following example, the function argument is a list of amount and duration, and the intereset is to be calculated for amount less than or more than 10000. The condition is included in the case clause. Open Compiler On executing, this code will produce the following output −
Nested if Statement
Python supports nested if statements which means we can use a conditional if and if…else statement inside an existing if statement. There may be a situation when you want to check for additional conditions after the initial one resolves to true. In such a situation, you can use the nested if construct. Additionally, within a nested if construct, you can include an if…elif…else construct inside another if…elif…else construct. Syntax of Nested if Statement The syntax of the nested if construct with else condition will be like this − Flowchart of Nested if Statement Following is the flowchart of Python nested if statement − Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career. Example of Nested if Statement The below example shows the working of nested if statements − Open Compiler When you run the above code, it will display the following result − Nested if Statement with else Condition As mentioned earlier, we can nest if-else statement within an if statement. If the if condition is true, the first if-else statement will be executed otherwise, statements inside the else block will be executed. Syntax The syntax of the nested if construct with else condition will be like this − Example Now let’s take a Python code to understand how it works − Open Compiler When the above code is executed, it produces the following output −
Else Statement
Python if else Statement The if-else statement in Python is used to execute a block of code when the condition in the if statement is true, and another block of code when the condition is false. Syntax of if-else Statement The syntax of an if-else statement in Python is as follows − If the boolean expression evaluates to TRUE, then the statement(s) inside the if block will be executed otherwise statements of the else block will be executed. Flowchart of if-else Statement This flowchart shows how if-else statement is used − If the expr is True, block of stmt1, 2, 3 is executed then the default flow continues with stmt7. However, if the expr is False, block stmt4, 5, 6 runs then the default flow continues. Python implementation of the above flowchart is as follows − Python if-else Statement Example Let us understand the use of if-else statements with the following example. Here, variable age can take different values. If the expression age > 18 is true, then eligible to vote message will be displayed otherwise not eligible to vote message will be displayed. Following flowchart illustrates this logic − Now, let’s see the Python implementation the above flowchart. Open Compiler On executing this code, you will get the following output − To test the else block, change the age to 12, and run the code again. Python if elif else Statement The if elif else statement allows you to check multiple expressions for TRUE and execute a block of code as soon as one of the conditions evaluates to TRUE. Similar to the else block, the elif block is also optional. However, a program can contains only one else block whereas there can be an arbitrary number of elif blocks following an if block. Syntax of Python if elif else Statement How if elif else Works? The keyword elif is a short form of else if. It allows the logic to be arranged in a cascade of elif statements after the first if statement. If the first if statement evaluates to false, subsequent elif statements are evaluated one by one and comes out of the cascade if any one is satisfied. Last in the cascade is the else block which will come in picture when all preceding if/elif conditions fails. Example Suppose there are different slabs of discount on a purchase − The following flowchart illustrates these conditions − We can write a Python code for the above logic with if-else statements − Open Compiler Set amount to test all possible conditions: 800, 2500, 7500 and 15000. The outputs will vary accordingly − While the code will work perfectly fine, if you look at the increasing level of indentation at each if and else statement, it will become difficult to manage if there are still more conditions. Python if elif else Statement Example The elif statement makes the code easy to read and comprehend. Following is the Python code for the same logic with if elif else statements − Open Compiler The output of the above code is as follows −
if Statement
Python If Statement The if statement in Python evaluates whether a condition is true or false. It contains a logical expression that compares data, and a decision is made based on the result of the comparison. Syntax of the if Statement If the boolean expression evaluates to TRUE, then the statement(s) inside the if block is executed. If boolean expression evaluates to FALSE, then the first set of code after the end of the if block is executed. Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career. Flow Diagram (Flowchart) of the if Statement The below diagram shows flowchart of the if statement − Example of Python if Statement Let us consider an example of a customer entitled to 10% discount if his purchase amount is > 1000; if not, then no discount is applicable. The following flowchart shows the whole decision making process − First, set a discount variable to 0 and an amount variable to 1200. Then, use an if statement to check whether the amount is greater than 1000. If this condition is true, calculate the discount amount. If a discount is applicable, deduct it from the original amount. Python code for the above flowchart can be written as follows − Open Compiler Here the amout is 1200, hence discount 120 is deducted. On executing the code, you will get the following output − Change the variable amount to 800, and run the code again. This time, no discount is applicable. And, you will get the following output −
Decision Making
Python’s decision making functionality is in its keywords − if..elif…else. The if keyword requires a boolean expression, followed by colon (:) symbol. The colon (:) symbol starts an indented block. The statements with the same level of indentation are executed if the boolean expression in if statement is True. If the expression is not True (False), the interpreter bypasses the indented block and proceeds to execute statements at earlier indentation level. Decision structures evaluate multiple expressions which produce TRUE or FALSE as outcome. You need to determine which action to take and which statements to execute if outcome is TRUE or FALSE otherwise. Following is the general form of a typical decision making structure found in most of the programming languages − Python programming language assumes any non-zero and non-null values as TRUE, and if it is either zero or null, then it is assumed as FALSE value. Types of Decision Making Statements in Python Python programming language provides following types of decision making statements. Click the following links to check their detail. Sr.No. Statement & Description 1 if statementsAn if statement consists of a boolean expression followed by one or more statements. 2 if…else statementsAn if statement can be followed by an optional else statement, which executes when the boolean expression is FALSE. 3 nested if statementsYou can use one if or else if statement inside another if or else if statement(s). Let us go through each decision making briefly − Single Statement Suites If the suite of an if clause consists only of a single line, it may go on the same line as the header statement. Example Here is an example of a one-line if clause − Open Compiler When the above code is executed, it produces the following result − Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career. if…else statement In this decision making statement, if the if condition is true, then the statements within this block are executed, otherwise, the else block is executed. The program will choose which block of code to execute based on whether the condition in the if statement is true or false. Example The following example shows the use of if…else statement. Open Compiler On running the above code, it will show the following output − Nested if statements A nested if is another decision making statement in which one if statement resides inside another. It allows us to check multiple conditions sequentially. Example In this example, we will see the use of nested-if statement. Open Compiler On executing the above code, it will display the below output −
Control Flow
Python program control flow is regulated by various types of conditional statements, loops, and function calls. By default, the instructions in a computer program are executed in a sequential manner, from top to bottom, or from start to end. However, such sequentially executing programs can perform only simplistic tasks. We would like the program to have a decision-making ability, so that it performs different steps depending on different conditions. Most programming languages including Python provide functionality to control the flow of execution of instructions. Normally, there are two type of control flow statements in any programming language and Python also supports them. Decision Making Statements Decision making statements are used in the Python programs to make them able to decide which of the alternative group of instructions to be executed, depending on value of a certain Boolean expression. The following diagram illustrates how decision-making statements work − The if Statements Python provides if..elif..else control statements as a part of decision marking. It consists of three different blocks, which are if block, elif (short of else if) block and else block. Example Following is a simple example which makes use of if..elif..else. You can try to run this program using different marks and verify the result. Open Compiler This will produce following result: Passed with distinction The match Statement Python supports Match-Case statement, which can also be used as a part of decision making. If a pattern matches the expression, the code under that case will execute. Example Following is a simple example which makes use of match statement. Open Compiler This will produce following result: Loops or Iteration Statements Most of the processes require a group of instructions to be repeatedly executed. In programming terminology, it is called a loop. Instead of the next step, if the flow is redirected towards any earlier step, it constitutes a loop. The following diagram illustrates how the looping works − If the control goes back unconditionally, it forms an infinite loop which is not desired as the rest of the code would never get executed. In a conditional loop, the repeated iteration of block of statements goes on till a certain condition is met. Python supports a number of loops like for loop, while loop which we will study in next chapters. The for Loop The for loop iterates over the items of any sequence, such as a list, tuple or a string . Example Following is an example which makes use of For Loop to iterate through an array in Python: Open Compiler This will produce following result: The while Loop The while loop repeatedly executes a target statement as long as a given boolean expression is true. Example Following is an example which makes use of While Loop to print first 5 numbers in Python: Open Compiler This will produce following result: Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career. Jump Statements The jump statements are used to jump on a specific statement by breaking the current flow of the program. In Python, there are two jump statements break and continue. The break Statement It terminates the current loop and resumes execution at the next statement. Example The following example demonstrates the use of break statement − Open Compiler This will produce following result: The continue Statement It skips the execution of the program block and returns the control to the beginning of the current loop to start the next iteration. Example The following example demonstrates the use of continue statement − Open Compiler This will produce following result:
Booleans
Python Booleans (bool) In Python, bool is a sub-type of int type. A bool object has two possible values, and it is initialized with Python keywords, True and False. Example A bool object is accepted as argument to type conversion functions. With True as argument, the int() function returns 1, float() returns 1.0; whereas for False, they return 0 and 0.0 respectively. We have a one argument version of complex() function. If the argument is a complex object, it is taken as real part, setting the imaginary coefficient to 0. Example Open Compiler On running this code, you will get the following output − Python Boolean Expression Python boolean expression is an expression that evaluates to a Boolean value. It almost always involves a comparison operator. In the below example we will see how the comparison operators can give us the Boolean values. The bool() method is used to return the truth value of an expresison. Below we have examples which use numbers streams and Boolean values as parameters to the bool function. The results come out as true or false depending on the parameter. Example Open Compiler Print PagePython Booleans (bool) In Python, bool is a sub-type of int type. A bool object has two possible values, and it is initialized with Python keywords, True and False. Example A bool object is accepted as argument to type conversion functions. With True as argument, the int() function returns 1, float() returns 1.0; whereas for False, they return 0 and 0.0 respectively. We have a one argument version of complex() function. If the argument is a complex object, it is taken as real part, setting the imaginary coefficient to 0. Example Open Compiler On running this code, you will get the following output − Python Boolean Expression Python boolean expression is an expression that evaluates to a Boolean value. It almost always involves a comparison operator. In the below example we will see how the comparison operators can give us the Boolean values. The bool() method is used to return the truth value of an expresison. Below we have examples which use numbers streams and Boolean values as parameters to the bool function. The results come out as true or false depending on the parameter. Example Open Compiler Print Page
Numbers
Python has built-in support to store and process numeric data (Python Numbers). Most of the times you work with numbers in almost every Python application. Obviously, any computer application deals with numbers. This tutorial will discuss about different types of Python Numbers and their properties. Python – Number Types There are three built-in number types available in Python: Python also has a bult-in Boolean data type called bool. It can be treated as a sub-type of int type, since it’s two possible values True and False represent the integers 1 and 0 respectively. Python − Integer Numbers In Python, any number without the provision to store a fractional part is an integer. (Note that if the fractional part in a number is 0, it doesn’t mean that it is an integer. For example a number 10.0 is not an integer, it is a float with 0 fractional part whose numeric value is 10.) An integer can be zero, positive or a negative whole number. For example, 1234, 0, -55 all represent to integers in Python. There are three ways to form an integer object. With (a) literal representation, (b) any expression evaluating to an integer, and (c) using int() function. Literal is a notation used to represent a constant directly in the source code. For example − However, look at the following assignment of the integer variable c. Open Compiler It will produce the following output − Here, c is indeed an integer variable, but the expression a + b is evaluated first, and its value is indirectly assigned to c. The third method of forming an integer object is with the return value of int() function. It converts a floating point number or a string in an integer. >>> a=int(10.5)>>> b=int(“100″) You can represent an integer as a binary, octal or Hexa-decimal number. However, internally the object is stored as an integer. Binary Numbers in Python A number consisting of only the binary digits (1 and 0) and prefixed with “0b” is a binary number. If you assign a binary number to a variable, it still is an int variable. A represent an integer in binary form, store it directly as a literal, or use int() function, in which the base is set to 2 Open Compiler It will produce the following output − There is also a bin() function in Python. It returns a binary string equivalent of an integer. Open Compiler It will produce the following output − Octal Numbers in Python An octal number is made up of digits 0 to 7 only. In order to specify that the integer uses octal notation, it needs to be prefixed by “0o” (lowercase O) or “0O” (uppercase O). A literal representation of octal number is as follows − Open Compiler It will produce the following output − Note that the object is internally stored as integer. Decimal equivalent of octal number 107 is 71. Since octal number system has 8 symbols (0 to 7), its base is 7. Hence, while using int() function to covert an octal string to integer, you need to set the base argument to 8. Open Compiler It will produce the following output − Decimal equivalent of octal 30 is 16. In the following code, two int objects are obtained from octal notations and their addition is performed. Open Compiler It will produce the following output − To obtain the octal string for an integer, use oct() function. Open Compiler Hexa-decimal Numbers in Python As the name suggests, there are 16 symbols in the Hexadecimal number system. They are 0-9 and A to F. The first 10 digits are same as decimal digits. The alphabets A, B, C, D, E and F are equivalents of 11, 12, 13, 14, 15, and 16 respectively. Upper or lower cases may be used for these letter symbols. For the literal representation of an integer in Hexadecimal notation, prefix it by “0x” or “0X”. Open Compiler It will produce the following output − To convert a Hexadecimal string to integer, set the base to 16 in the int() function. Open Compiler Try out the following code snippet. It takes a Hexadecimal string, and returns the integer. Open Compiler It will produce the following output − However, if the string contains any symbol apart from the Hexadecimal symbol chart an error will be generated. Open Compiler The above program generates the following error − Python’s standard library has hex() function, with which you can obtain a hexadecimal equivalent of an integer. Open Compiler It will produce the following output − Though an integer can be represented as binary or octal or hexadecimal, internally it is still integer. So, when performing arithmetic operation, the representation doesn’t matter. Open Compiler It will produce the following output − Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career. Python − Floating Point Numbers A floating point number has an integer part and a fractional part, separated by a decimal point symbol (.). By default, the number is positive, prefix a dash (-) symbol for a negative number. A floating point number is an object of Python’s float class. To store a float object, you may use a literal notation, use the value of an arithmetic expression, or use the return value of float() function. Using literal is the most direct way. Just assign a number with fractional part to a variable. Each of the following statements declares a float object. In Python, there is no restriction on how many digits after the decimal point can a floating point number have. However, to shorten the representation, the E or e symbol is used. E stands for Ten raised to. For example, E4 is 10 raised to 4 (or 4th power of 10), e-3 is 10 raised to -3. In scientific notation, number has a coefficient and exponent part. The coefficient should be a float greater than or equal to 1 but less than 10. Hence, 1.23E+3, 9.9E-5, and 1E10 are the examples of floats with scientific notation. The second approach of forming a float object is indirect, using the result of an expression. Here, the quotient of two floats is assigned to a variable, which refers to a float object. Open Compiler It will produce the following output − Python’s float() function returns a float object, parsing a number
User Input
Provide User Input in Python In this chapter, we will learn how Python accepts the user input from the console, and displays the output on the same console. Every computer application should have a provision to accept input from the user when it is running. This makes the application interactive. Depending on how it is developed, an application may accept the user input in the form of text entered in the console (sys.stdin), a graphical layout, or a web-based interface. Python User Input Functions Python provides us with two built-in functions to read the input from the keyboard. Python interpreter works in interactive and scripted mode. While the interactive mode is good for quick evaluations, it is less productive. For repeated execution of same set of instructions, scripted mode should be used. Let us write a simple Python script to start with. Open Compiler Save the above code as hello.py and run it from the command-line. Here’s the output The program simply prints the values of the two variables in it. If you run the program repeatedly, the same output will be displayed every time. To use the program for another name and city, you can edit the code, change name to say “Ravi” and city to “Chennai”. Every time you need to assign different value, you will have to edit the program, save and run, which is not the ideal way. Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career. The input() Function Obviously, you need some mechanism to assign different value to the variable in the runtime − while the program is running. Python’s input() function does the same job. Following is the syntax of Python’s standard library input() function. When the interpreter encounters input() function, it waits for the user to enter data from the standard input stream (keyboard) till the Enter key is pressed. The sequence of characters may be stored in a string variable for further use. On reading the Enter key, the program proceeds to the next statement. Let use change our program to store the user input in name and city variables. When you run, you will find the cursor waiting for user’s input. Enter values for name and city. Using the entered data, the output will be displayed. Now, the variables are not assigned any specific value in the program. Every time you run, different values can be input. So, your program has become truly interactive. Inside the input() function, you may give a prompt text, which will appear before the cursor when you run the code. When you run the program displays the prompt message, basically helping the user what to enter. The raw_input() Function The raw_input() function works similar to input() function. Here only point is that this function was available in Python 2.7, and it has been renamed to input() in Python 3.6 Following is the syntax of the raw_input() function: Let’s re-write the above program using raw_input() function: When you run, you will find the cursor waiting for user’s input. Enter values for name and city. Using the entered data, the output will be displayed. Taking Numeric Input in Python Let us write a Python code that accepts width and height of a rectangle from the user and computes the area. Run the program, and enter width and height. Why do you get a TypeError here? The reason is, Python always read the user input as a string. Hence, width=”20″ and height=”30″ are the strings and obviously you cannot perform multiplication of two strings. To overcome this problem, we shall use int(), another built-in function from Python’s standard library. It converts a string object to an integer. To accept an integer input from the user, read the input in a string, and type cast it to integer with int() function − You can combine the input and type cast statements in one − Now you can input any integer value to the two variables in the program − Python’s float() function converts a string into a float object. The following program accepts the user input and parses it to a float variable − rate, and computes the interest on an amount which is also input by the user. The program ask user to enter amount and rate; and displays the result as follows − The print() Function Python’s print() function is a built-in function. It is the most frequently used function, that displays value of Python expression given in parenthesis, on Python’s console, or standard output (sys.stdout). Open Compiler Any number of Python expressions can be there inside the parenthesis. They must be separated by comma symbol. Each item in the list may be any Python object, or a valid Python expression. The first call to print() displays a string literal and a string variable. The second prints value of two variables and their subtraction. The pow() function computes the square root of a number and square value of a variable. If there are multiple comma separated objects in the print() function’s parenthesis, the values are separated by a white space ” “. To use any other character as a separator, define a sep parameter for the print() function. This parameter should follow the list of expressions to be printed. In the following output of print() function, the variables are separated by comma. Open Compiler The effect of sep=’,’ can be seen in the result − The print() function issues a newline character (‘\n’) at the end, by default. As a result, the output of the next print() statement appears in the next line of the console. Open Compiler Two lines are displayed as the output − To make these two lines appear in the same line, define end parameter in the first print() function and set it to a whitespace string ” “. Open Compiler Output of both the print() functions appear in continuation.