Example: Print first 10 numbers using a for loop Here we used the range() function to generate integers from 0 to 9 Next, we used the for loop to iterate over the numbers produced by the range() function In the body of a loop, we printed the current number. for num in range(10...
6.Using while loop to generate(print) all of even numbers ranging from 0 to 1000(1000 is included) # Using while loop to generate(print) all of even numbers # ranging from 0 to 1000(1000 is included) i = 0 j = 0 while i <= 1000: print(i,end=' ') i += 2 j += 1 if ...
Example – Find A Fibonacci Sequence Upto nth Term Using The While Loop A Fibonacci sequence has the formula. 0,1,1,...((n-1)th + (n-2)th) The first two numbers are 0 and 1, then the next numbers are the sum of the two previous numbers (n-1)th and (n-2)th. The Fibonacc...
Let’s say we have a function to print the sum of numbers if and only if all the numbers are even. We can use break statement to terminate the for loop if an odd number is present. We can print the sum in the else part so that it gets printed only when the for loop is executed...
1. Python while Loop Python while loop is used to repeat a block of code as long as the given condition stays true. Here’s an example: a=1whilea<=10:print(a)a=a+1 Output 1 2 3 4 5 6 7 8 9 10 2. Python do while Loop (Not Present in Python) ...
It checks divisibility only for odd numbers starting from 3 up to the square root of the number. Main Function (print_first_10_primes): Similar to the first method, this function uses a while loop to find and print the first 10 prime numbers. ...
print(weekdays[day])while循环# Initialize counter counter = 1 # Iterate the loop 5 times while ...
def add_numbers(a, b): return a + b print(add_numbers(5, 3)) Output: Explanation: Here, add_numbers() adds the two numbers given as input and returns the sum as a result. Function to Check Even or Odd This function checks whether a given number is even or odd using the modulus...
print(i) While Loop: A while loop continues executing as long as the specified condition is true. It’s useful when the number of iterations is not known in advance. Python Copy Code Run Code 1 2 3 4 5 count = 0 while count < 5: print(count) count += 1 Nested For-Loop in ...
The following code creates an empty list and uses a while loop to populate the list: Python >>> import random >>> numbers = [] >>> while sum(numbers) <= 21: ... numbers.append(random.randint(1, 10)) ... >>> numbers [3, 10, 4, 7] >>> numbers[len(numbers) - 1] 7...