Found 10784 Articles for Python

How to generate prime twins using Python?

Govinda Sai
Updated on 05-Mar-2020 10:07:04

6K+ Views

Twin primes are pairs of primes which differ by two. The first twin primes are {3,5}, {5,7}, {11,13} and {17,19}. You can generate prime twins in python by running a for loop and checking for primality of the numbers as you do so. exampledef is_prime(n):    for i in range(2, n):       if n % i == 0:          return False    return True def generate_twins(start, end):    for i in range(start, end):       j = i + 2       if(is_prime(i) and is_prime(j)):          print("{:d} and {:d}".format(i, j)) generate_twins(2, 100)OutputThis will give the output −3 and 5 5 and 7 11 and 13 17 and 19 29 and 31 41 and 43 59 and 61 71 and 73

How to use multiple for and while loops together in Python?

Ankith Reddy
Updated on 17-Jun-2020 12:36:21

255 Views

You can create nested loops in python fairly easily. You can even nest a for loop inside a while loop or the other way around. For example,for i in range(5):    j = i    while j != 0:       print(j, end=', ')       j -= 1    print("")This will give the output1, 2, 1, 3, 2, 1, 4, 3, 2, 1,You can take this nesting to as many levels as you like.

How to generate a sorted list in Python?

Lakshmi Srinivas
Updated on 17-Jun-2020 12:35:01

326 Views

The sort method on lists in python uses the given class's gt and lt operators to compare. Most built in classes already has these operators implemented so it automatically gives you sorted list. You can use it as follows:words = ["Hello", "World", "Foo", "Bar", "Nope"] numbers = [100, 12, 52, 354, 25] words.sort() numbers.sort() print(words) print(numbers)This will give the output:['Bar', 'Foo', 'Hello', 'Nope', 'World'] [12, 25, 52, 100, 354]If you don't want the input list to be sorted in place, you can use the sorted function to do so. For example, words = ["Hello", "World", "Foo", "Bar", "Nope"] sorted_words ... Read More

How to use single statement suite with Loops in Python?

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

239 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

98 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

99 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.

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

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

313 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

5K+ 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

623 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

Advertisements