Found 10805 Articles for Python

Can we change Python for loop range (higher limit) at runtime?

Samual Sam
Updated on 17-Jun-2020 12:27:13

293 Views

No, You can't modify a range once it is created. Instead what you can do is use a while loop instead. For example, if you have some code like:for i in range(lower_limit, higher_limit, step_size):# some code if i == 10:    higher_limit = higher_limit + 5You can change it to:i = lower_limit while i < higher_limit:    # some code    if i == 10:       higher_limit = higher_limit + 5    i += step_size

How to create a triangle using Python for loop?

Sravani S
Updated on 17-Jun-2020 12:24:20

4K+ Views

There are multiple variations of generating triangle using numbers in Python. Let's look at the 2 simplest forms:for i in range(5):    for j in range(i + 1):       print(j + 1, end="")    print("")This will give the output:1 12 123 1234 12345You can also print numbers continuously using:start = 1 for i in range(5):    for j in range(i + 1):       print(start, end=" ")       start += 1    print("")This will give the output:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15You can also print these numbers in reverse using:start = 15 for i in range(5):    for j in range(i + 1):       print(start, end=" ")       start -= 1    print("")This will give the output:15 14 13 12 11 10 9 8 7 6 5 4 3 2 1

How do I run two python loops concurrently?

Lakshmi Srinivas
Updated on 17-Jun-2020 12:22:33

564 Views

You will need to use a multiprocessing library. You will need to spawn a new process and provide the code to it as an argument. For example,from multiprocessing import Processdef loop_a():    for i in range(5):       print("a") def loop_b():    for i in range(5):       print("b") Process(target=loop_a).start() Process(target=loop_b).start()This might process different outputs at different times. This is because we don't know which print will be executed when.

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

500 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

553 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

71 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

103 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 make loops run faster using Python?

Samual Sam
Updated on 05-Mar-2020 09:55:17

787 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. They 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

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

Advertisements