Python For Loop Practice Worksheet
Python For Loop Practice Worksheet
The output of the code will be: 2 4 6 8 10, with each number printed on a new line .
Within a for loop, the loop variable changes its value on each iteration, adopting each successive value from the provided iterable. This behavior allows the loop to access each item in the sequence sequentially, enabling operations to be performed on each element in turn .
The function range(5) generates numbers from 0 to 4 .
The Python program would use a for loop with range(1, 11) as follows: for i in range(1, 11): print(i).
The program could use a for loop as follows: for i in range(1, 11): print(f"7 x {i} = {7*i}").
The principle is to use a negative step value in the range function to decrement the sequence. The code for i in range(5, 0, -1) prints: 5 4 3 2 1, as it starts from 5 and decreases by 1 each iteration until it reaches 1, stopping before 0 .
The output of the code snippet will be 'Hello' printed three times, each on a new line .
A 'for loop' is used for repetitive tasks, allowing the execution of a block of code a fixed number of times .
To check if a number is prime in Python, one would iterate from 2 to the square root of the number, checking for divisibility. If any number divides evenly, it is not prime. Here is basic logic: num = int(input("Enter a number: ")) if num > 1: for i in range(2, int(num**0.5)+1): if (num % i) == 0: print(num, "is not a prime number") break else: print(num, "is a prime number") else: print(num, "is not a prime number").
To simulate a password guessing system, one could loop through a list of guesses and check each against a defined password. The code might look like: password = "secret" guesses = ["guess1", "password", "secret"] for guess in guesses: if guess == password: print("Correct password!") break else: print("Incorrect password. Try again.").