Found 10407 Articles for Python

How to use single statement suite with Loops in Python?

karthikeya Boyini
Updated on 17-Jun-2020 12:29:42

360 Views

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. Here are the syntax and example of a one-line for loop:for i in range(5): print(i)This will give the output:0 1 2 3 4

How will you explain Python for-loop to list comprehension?

Ramu Prasad
Updated on 17-Jun-2020 12:32:24

167 Views

List comprehensions offer a concise way to create lists based on existing lists. When using list comprehensions, lists can be built by leveraging any iterable, including strings and tuples. list comprehensions consist of an iterable containing an expression followed by a for the clause. This can be followed by additional for or if clauses.Let’s look at an example that creates a list based on a string:hello_letters = [letter for letter in 'hello'] print(hello_letters)This will give the output:['h', 'e', 'l', 'l', 'o']string hello is iterable and the letter is assigned a new value every time this loop iterates. This list comprehension ... Read More

Why python for loops don't default to one iteration for single objects?

Chandu yadav
Updated on 30-Jul-2019 22:30:22

148 Views

Python cannot iterate over an object that is not 'iterable'. The 'for' loop construct in python calls inbuilt functions within the iterable data-type which allow it to extract elements from the iterable.Since non-iterable data-types don't have these methods, there is no way to extract elements from them. And hence for loops ignore them.

How to handle exception inside a Python for loop?

Arjun Thakur
Updated on 17-Jun-2020 12:20:33

3K+ Views

You can handle exception inside a Python for loop just like you would in a normal code block. This doesn't cause any issues. For example,for i in range(5):    try:       if i % 2 == 0:          raise ValueError("some error")       print(i) except ValueError as e:    print(e)This will give the outputsome error 1 some error 3 some error

What are the best practices for using if statements in Python?

karthikeya Boyini
Updated on 30-Jul-2019 22:30:22

636 Views

Here are some of the steps that you can follow to optimize a nested if...elif...else.1. Ensure that the path that'll be taken most is near the top. This ensures that not multiple conditions are needed to be checked on the most executed path.2. Similarly, sort the paths by most use and put the conditions accordingly.3. Use short-circuiting to your advantage. If you have a statement like:if heavyOperation() and lightOperation():Then consider changing it toif lightOperation() and heavyOperation():This will ensure that heavyOperation is not even executed if lightOperation is false. Same can be done with or conditions as well.4. Try flattening the ... Read More

What are the best practices for using loops in Python?

Samual Sam
Updated on 05-Mar-2020 10:05:05

684 Views

This is a language agnostic question. Loops are there in almost every language and the same principles apply everywhere. You need to realize that compilers do most heavy lifting when it comes to loop optimization, but you as a programmer also need to keep your loops optimized.It is important to realize that everything you put in a loop gets executed for every loop iteration. The key to optimizing loops is to minimize what they do. Even operations that appear to be very fast will take a long time if the repeated many times. Executing an operation that takes 1 microsecond ... Read More

Python: Can not understand why I am getting the error: Can not concatenate 'int' and 'str' object

Ayush Gupta
Updated on 12-Mar-2020 12:31:58

101 Views

This error is coming because the interpreter is replacing the %d with i and then trying to add 1 to a str, ie, adding a str and an int. In order to correct this, just surround the i+1 in parentheses. exampleprint("\ Num %d" % (i+1))

Python: Cannot understand why the error - cannot concatenate 'str' and 'int' object ?

Jayashree
Updated on 13-Mar-2020 05:15:39

175 Views

This can be corrected by putting n+1 in brackets i.e. (n+1)for num in range(5):     print ("%d" % (num+1))Using %d casts the object following % to string. Since a string object can't be concatnated with a number (1 in this case) interpreter displays typeerror.

How to create a lambda inside a Python loop?

Lakshmi Srinivas
Updated on 05-Mar-2020 09:54:01

1K+ Views

You can create a list of lambdas in a python loop using the following syntax −Syntaxdef square(x): return lambda : x*x listOfLambdas = [square(i) for i in [1,2,3,4,5]] for f in listOfLambdas: print f()OutputThis will give the output −1 4 9 16 25You can also achieve this using a functional programming construct called currying. examplelistOfLambdas = [lambda i=i: i*i for i in range(1, 6)] for f in listOfLambdas:    print f()OutputThis will give the output −1 4 9 16 25

How do I loop through a JSON file with multiple keys/sub-keys in Python?

Sravani S
Updated on 05-Mar-2020 08:14:19

14K+ Views

You can parse JSON files using the json module in Python. This module parses the json and puts it in a dict. You can then get the values from this like a normal dict. For example, if you have a json with the following content −{    "id": "file",    "value": "File",    "popup": {       "menuitem": [          {"value": "New", "onclick": "CreateNewDoc()"},          {"value": "Open", "onclick": "OpenDoc()"},          {"value": "Close", "onclick": "CloseDoc()"}       ]    } }ExampleYou can load it in your python program and loop ... Read More

Advertisements