Keyword Arguments

Tutorials

Keyword Arguments Python allows to pass function arguments in the form of keywords which are also called named arguments. Variables in the function definition are used as keywords. When the function is called, you can explicitly mention the name and its value. Calling Function With Keyword Arguments The following example demonstrates keyword arguments in Python. In the second function call, we have used keyword arguments. 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. Order of Keyword Arguments By default, the function assigns the values to arguments in the order of appearance. However, while using keyword arguments, it is not necessary to follow the order of formal arguments in function definition. Use of keyword arguments is optional. You can use mixed calling. You can pass values to some arguments without keywords, and for others with keyword. Example Let us try to understand with the help of following function definition − Open Compiler Since the values are assigned as per the position, the output is as follows − Example Instead of passing the values with positional arguments, let us call the function with keyword arguments − Open Compiler Unlike positional arguments, the order of keyword arguments does not matter. Hence, it will produce the following output − However, the positional arguments must be before the keyword arguments while using mixed calling. Example Try to call the division() function with the keyword arguments as well as positional arguments. Open Compiler As the Positional argument cannot appear after keyword arguments, Python raises the following error message −

October 3, 2024 / 0 Comments
read more

Default Arguments

Tutorials

Python Default Arguments Python allows to define a function with default value assigned to one or more formal arguments. Python uses the default value for such an argument if no value is passed to it. If any value is passed, the default value is overridden with the actual value passed. Default arguments in Python are the function arguments that will be used if no arguments are passed to the function call. Example of Default Arguments The following example shows use of Python default arguments. Here, the second call to the function will not pass value to “city” argument, hence its default value “Hyderabad” will be used. 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. Example: Calling Function Without Keyword Arguments Let us look at another example that assigns default value to a function argument. The function percent() has a default argument named “maxmarks” which is set to 200. Hence, we can omit the value of third argument while calling the function. Open Compiler On executing, this code will produce the following output − Mutable Objects as Default Argument Python evaluates default arguments once when the function is defined, not each time the function is called. Therefore, If you use a mutable default argument and modify it within the given function, the same values are referenced in the subsequent function calls. Those Python objects that can be changed after creation are called as mutable objects. Example The code below explains how to use mutable objects as default argument in Python. Open Compiler On executing the above code, it will produce the following output −

October 3, 2024 / 0 Comments
read more

Functions

Tutorials

A Python function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing. A top-to-down approach towards building the processing logic involves defining blocks of independent reusable functions. A Python function may be invoked from any other function by passing required data (called parameters or arguments). The called function returns its result back to the calling environment. Types of Python Functions Python provides the following types of functions − Sr.No Type & Description 1 Built-in functionsPython’s standard library includes number of built-in functions. Some of Python’s built-in functions are print(), int(), len(), sum(), etc. These functions are always available, as they are loaded into computer’s memory as soon as you start Python interpreter. 2 Functions defined in built-in modulesThe standard library also bundles a number of modules. Each module defines a group of functions. These functions are not readily available. You need to import them into the memory from their respective modules. 3 User-defined functionsIn addition to the built-in functions and functions in the built-in modules, you can also create your own functions. These functions are called user-defined functions. Defining a Python Function You can define custom functions to provide the required functionality. Here are simple rules to define a function in Python − Syntax to Define a Python Function By default, parameters have a positional behavior and you need to inform them in the same order that they were defined. Once the function is defined, you can execute it by calling it from another function or directly from the Python prompt. Example to Define a Python Function The following example shows how to define a function greetings(). The bracket is empty so there aren’t any parameters. Here, the first line is a docstring and the function block ends with return statement. When this function is called, Hello world message will be printed. Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career. Calling a Python Function Defining a function only gives it a name, specifies the parameters that are to be included in the function and structures the blocks of code. Once the basic structure of a function is finalized, you can call it by using the function name itself. If the function requires any parameters, they should be passed within parentheses. If the function doesn’t require any parameters, the parentheses should be left empty. Example to Call a Python Function Following is the example to call printme() function − Open Compiler When the above code is executed, it produces the following output − Pass by Reference vs Value In programming languages like C and C++, there are two main ways to pass variables to a function, which are Call by Value and Call by Reference (also known as pass by reference and pass by value). However, the way we pass variables to functions in Python differs from others. Python uses pass by reference mechanism. As variable in Python is a label or reference to the object in the memory, both the variables used as actual argument as well as formal arguments really refer to the same object in the memory. We can verify this fact by checking the id() of the passed variable before and after passing. Example In the following example, we are checking the id() of a variable. Open Compiler If the above code is executed, the id() before passing and inside the function will be displayed. The behavior also depends on whether the passed object is mutable or immutable. Python numeric object is immutable. When a numeric object is passed, and then the function changes the value of the formal argument, it actually creates a new object in the memory, leaving the original variable unchanged. Example The following example shows how an immutable object behaves when it is passed to a function. Open Compiler It will produce the following output − Let us now pass a mutable object (such as a list or dictionary) to a function. It is also passed by reference, as the id() of list before and after passing is same. However, if we modify the list inside the function, its global representation also reflects the change. Example Here we pass a list, append a new item, and see the contents of original list object, which we will find has changed. Open Compiler It will produce the following output − Python Function Arguments Function arguments are the values or variables passed into a function when it is called. The behavior of a function often depends on the arguments passed to it. While defining a function, you specify a list of variables (known as formal parameters) within the parentheses. These parameters act as placeholders for the data that will be passed to the function when it is called. When the function is called, value to each of the formal arguments must be provided. Those are called actual arguments. Example Let’s modify greetings function and have name an argument. A string passed to the function as actual argument becomes name variable inside the function. Open Compiler This code will produce the following output − Types of Python Function Arguments Based on how the arguments are declared while defining a Python function, they are classified into the following categories − Positional or Required Arguments Required arguments are the arguments passed to a function in correct positional order. Here, the number of arguments in the function call should match exactly with the function definition, otherwise the code gives a syntax error. Example In the code below, we call the function printme() without any parameters which will give error. Open Compiler When the above code is executed, it produces the following result − Keyword Arguments Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name. This allows you to skip arguments or place them out of order because the Python interpreter is able to use the keywords provided to match

October 3, 2024 / 0 Comments
read more

Nested Loops

Tutorials

In Python, when you write one or more loops within a loop statement that is known as a nested loop. The main loop is considered as outer loop and loop(s) inside the outer loop are known as inner loops. The Python programming language allows the use of one loop inside another loop. A loop is a code block that executes specific instructions repeatedly. There are two types of loops, namely for and while, using which we can create nested loops. You can put any type of loop inside of any other type of loop. For example, a for loop can be inside a while loop or vice versa. Python Nested for Loop The for loop with one or more inner for loops is called nested for loop. A for loop is used to loop over the items of any sequence, such as a list, tuple or a string and performs the same action on each item of the sequence. Python Nested for Loop Syntax The syntax for a Python nested for loop statement in Python programming language is as follows − Python Nested for Loop Example The following program uses a nested for loop to iterate over months and days lists. Open Compiler When the above code is executed, it produces following result − Python Nested while Loop The while loop having one or more inner while loops are nested while loop. A while loop is used to repeat a block of code for an unknown number of times until the specified boolean expression becomes TRUE. Python Nested while Loop Syntax The syntax for a nested while loop statement in Python programming language is as follows − Python Nested while Loop Example The following program uses a nested while loop to find the prime numbers from 2 to 100 − Open Compiler On executing, the above code produces following result −

October 3, 2024 / 0 Comments
read more

pass Statement

Tutorials

Python pass Statement Python pass statement is used when a statement is required syntactically but you do not want any command or code to execute. It is a null which means nothing happens when it executes. This is also useful in places where piece of code will be added later, but a placeholder is required to ensure the program runs without errors. For instance, in a function or class definition where the implementation is yet to be written, pass statement can be used to avoid the SyntaxError. Additionally, it can also serve as a placeholder in control flow statements like for and while loops. Syntax of pass Statement Following is the syntax of Python pass statement − pass Example of pass Statement The following code shows how you can use the pass statement in Python − Open Compiler When the above code is executed, it produces the following output − Dumpy Infinite Loop with pass Statement This is simple enough to create an infinite loop using pass statement in Python. Example If you want to code an infinite loop that does nothing each time through, do it as shown below − Because the body of the loop is just an empty statement, Python gets stuck in this loop. Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career. Using Ellipses (…) as pass Statement Alternative Python 3.X allows ellipses (coded as three consecutive dots …) to be used in place of pass statement. Both serve as placeholders for code that are going to be written later. Example For example if we create a function which does not do anything especially for code to be filled in later, then we can make use of …

October 3, 2024 / 0 Comments
read more

Continue Statement

Tutorials

Python continue Statement Python continue statement is used to skip the execution of the program block and returns the control to the beginning of the current loop to start the next iteration. When encountered, the loop starts next iteration without executing the remaining statements in the current iteration. The continue statement is just the opposite to that of break. It skips the remaining statements in the current loop and starts the next iteration. Syntax of continue Statement 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 of continue Statement The flow diagram of the continue statement looks like this − Python continue Statement with for Loop In Python, the continue statement is allowed to be used with a for loop. Inside the for loop, you should include an if statement to check for a specific condition. If the condition becomes TRUE, the continue statement will skip the current iteration and proceed with the next iteration of the loop. Example Let’s see an example to understand how the continue statement works in for loop. Open Compiler When the above code is executed, it produces the following output − Python continue Statement with while Loop Python continue statement is used with ‘for’ loops as well as ‘while’ loops to skip the execution of the current iteration and transfer the program’s control to the next iteration. Example: Checking Prime Factors Following code uses continue to find the prime factors of a given number. To find prime factors, we need to successively divide the given number starting with 2, increment the divisor and continue the same process till the input reduces to 1. Open Compiler On executing, this code will produce the following output − Assign different value (say 75) to num in the above program and test the result for its prime factors.

October 3, 2024 / 0 Comments
read more

Break Statement

Tutorials

Python break Statement Python break statement is used to terminate the current loop and resumes execution at the next statement, just like the traditional break statement in C. The most common use for Python break statement is when some external condition is triggered requiring a sudden exit from a loop. The break statement can be used in both Python while and for loops. If you are using nested loops in Python, the break statement stops the execution of the innermost loop and start executing the next line of code after the block. Syntax of break Statement The syntax for a break statement in Python is as follows − 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 of break Statement Following is the flowchart of the break statement − break Statement with for loop If we use break statement inside a for loop, it interrupts the normal flow of program and exit the loop before completing the iteration. Example In this example, we will see the working of break statement in for loop. Open Compiler When the above code is executed, it produces the following result − break Statement with while loop Similar to the for loop, we can use the break statement to skip the code inside while loop after the specified condition becomes TRUE. Example The code below shows how to use break statement with while loop. Open Compiler On executing the above code, it produces the following result − break Statement with Nested Loops In nested loops, one loop is defined inside another. The loop that enclose another loop (i.e. inner loop) is called as outer loop. When we use a break statement with nested loops, it behaves as follows − Example The following program demonstrates the use of break in a for loop iterating over a list. Here, the specified number will be searched in the list. If it is found, then the loop terminates with the “found” message. Open Compiler The above program will produce the following output −

October 3, 2024 / 0 Comments
read more

While Loops

Tutorials

Python while Loop A while loop in Python programming language repeatedly executes a target statement as long as the specified boolean expression is true. This loop starts with while keyword followed by a boolean expression and colon symbol (:). Then, an indented block of statements starts. Here, statement(s) may be a single statement or a block of statements with uniform indent. The condition may be any expression, and true is any non-zero value. As soon as the expression becomes false, the program control passes to the line immediately following the loop. If it fails to turn false, the loop continues to run, and doesn’t stop unless forcefully stopped. Such a loop is called infinite loop, which is undesired in a computer program. Syntax of while Loop The syntax of a while loop in Python programming language is − In Python, all the statements indented by the same number of character spaces after a programming construct are considered to be part of a single block of code. Python uses indentation as its method of grouping statements. Flowchart of While loop The following flow diagram illustrates the while loop − Example 1 The following example illustrates the working of while loop. Here, the iteration run till value of count will become 5. Open Compiler On executing, this code will produce the following output − Example 2 Here is another example of using the while loop. For each iteration, the program asks for user input and keeps repeating till the user inputs a non-numeric string. The isnumeric() function returns true if input is an integer, false otherwise. On running the code, it will produce the following output − Python Infinite while Loop A loop becomes infinite loop if a condition never becomes FALSE. You must be cautious when using while loops because of the possibility that this condition never resolves to a FALSE value. This results in a loop that never ends. Such a loop is called an infinite loop. An infinite loop might be useful in client/server programming where the server needs to run continuously so that client programs can communicate with it as and when required. Example Let’s take an example to understand how the infinite loop works in Python − On executing, this code will produce the following output − The above example goes in an infinite loop and you need to use CTRL+C to exit the program. Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career. Python while-else Loop Python supports having an else statement associated with a while loop. If the else statement is used with a while loop, the else statement is executed when the condition becomes false before the control shifts to the main line of execution. Flowchart of While loop with else Statement The following flow diagram shows how to use else statement with while loop − Example The following example illustrates the combination of an else statement with a while statement. Till the count is less than 5, the iteration count is printed. As it becomes 5, the print statement in else block is executed, before the control is passed to the next statement in the main program. Open Compiler On running the above code, it will print the following output − Single Statement Suites Similar to the if statement syntax, if your while clause consists only of a single statement, it may be placed on the same line as the while header. Example The following example shows how to use one-line while clause. Open Compiler When you run this code, it will display the following output − Change the flag value to “1” and try the above program. If you do so, it goes into infinite loop and you need to press CTRL+C keys to exit.

October 3, 2024 / 0 Comments
read more

Else Loops

Tutorials

Python – For Else Loop Python supports an optional else block to be associated with a for loop. If a else block is used with a for loop, it is executed only when the for loop terminates normally. The for loop terminates normally when it completes all its iterations without encountering a break statement, which allows us to exit the loop when a certain condition is met. Flowchart of For Else Loop The following flowchart illustrates use of for-else loop − Syntax of For Else Loop Following is the syntax of for loop with optional else block − Example of For Else Loop The following example illustrates the combination of an else statement with a for statement in Python. Till the count is less than 5, the iteration count is printed. As it becomes 5, the print statement in else block is executed, before the control is passed to the next statement in the main program. Open Compiler On executing, this code will produce the following output − For-Else Construct without break statement As mentioned earlier in this tutorial, the else block executes only when the loop terminates normally i.e. without using break statement. Example In the following program, we use the for-else loop without break statement. Open Compiler On executing, the above program will generate 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. For-Else Construct with break statementIn case of forceful termination (by using break statement) of the loop, else statement is overlooked by the interpreter and hence its execution is skipped. Example The following program shows how else conditions work in case of a break statement. Open Compiler On executing, the above program will generate the following output − T For-Else with break statement and if conditions If we use for-else construct with break statement and if condition, the for loop will iterate over the iterators and within this loop, you can use an if block to check for a specific condition. If the loop completes without encountering a break statement, the code in the else block is executed. Example The following program shows how else conditions works in case of break statement and conditional statements. Open Compiler On executing, the above program will generate the following output −

October 3, 2024 / 0 Comments
read more

For Loops

Tutorials

The for loop in Python provides the ability to loop over the items of any sequence, such as a list, tuple or a string. It performs the same action on each item of the sequence. This loop starts with the for keyword, followed by a variable that represents the current item in the sequence. The in keyword links the variable to the sequence you want to iterate over. A colon (:) is used at the end of the loop header, and the indented block of code beneath it is executed once for each item in the sequence. Syntax of Python for Loop Here, the iterating_var is a variable to which the value of each sequence item will be assigned during each iteration. Statements represents the block of code that you want to execute repeatedly. Before the loop starts, the sequence is evaluated. If it’s a list, the expression list (if any) is evaluated first. Then, the first item (at index 0) in the sequence is assigned to iterating_var variable. During each iteration, the block of statements is executed with the current value of iterating_var. After that, the next item in the sequence is assigned to iterating_var, and the loop continues until the entire sequence is exhausted. Flowchart of Python for Loop The following flow diagram illustrates the working of for loop − Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career. Python for Loop with Strings A string is a sequence of Unicode letters, each having a positional index. Since, it is a sequence, you can iterate over its characters using the for loop. Example The following example compares each character and displays if it is not a vowel (‘a’, ‘e’, ‘i’, ‘o’, ‘u’). Open Compiler On executing, this code will produce the following output − Python for Loop with Tuples Python’s tuple object is also an indexed sequence, and hence you can traverse its items with a for loop. Example In the following example, the for loop traverses a tuple containing integers and returns the total of all numbers. Open Compiler On running this code, it will produce the following output − Python for Loop with Lists Python’s list object is also an indexed sequence, and hence you can iterate over its items using a for loop. Example In the following example, the for loop traverses a list containing integers and prints only those which are divisible by 2. Open Compiler When you execute this code, it will show the following result − Python for Loop with Range Objects Python’s built-in range() function returns an iterator object that streams a sequence of numbers. This object contains integers from start to stop, separated by step parameter. You can run a for loop with range as well. Syntax The range() function has the following syntax − Where, Example In this example, we will see the use of range with for loop. Open Compiler When you run the above code, it will produce the following output − Python for Loop with Dictionaries Unlike a list, tuple or a string, dictionary data type in Python is not a sequence, as the items do not have a positional index. However, traversing a dictionary is still possible with the for loop. Example Running a simple for loop over the dictionary object traverses the keys used in it. Open Compiler On executing, this code will produce the following output − Once we are able to get the key, its associated value can be easily accessed either by using square brackets operator or with the get() method. Example The following example illustrates the above mentioned approach. Open Compiler It will produce the following output − The items(), keys() and values() methods of dict class return the view objects dict_items, dict_keys and dict_values respectively. These objects are iterators, and hence we can run a for loop over them. Example The dict_items object is a list of key-value tuples over which a for loop can be run as follows − Open Compiler It will produce the following output − Using else Statement with For Loop Python supports to have an else statement associated with a loop statement. However, the else statement is executed when the loop has exhausted iterating the list. Example The following example illustrates the combination of an else statement with a for statement that searches for prime numbers from 10 to 20. Open Compiler When the above code is executed, it produces the following result −

October 3, 2024 / 0 Comments
read more

Posts pagination

Previous 1 … 13 14 15 … 18 Next