Friday

For and While Loops in Python Examples 1

Below is the first  example program of Loops

# This program asks user to input a integer number
# It sums all the integers from 1 to the user input
# The for loop runs the same program several times

# for Loop
for m in range(0,3):

# User input
    x = int(input("Input a number : "))

# Variables
    sum = 0
    counter = 1

# while Loop
    while counter <= x :
        sum = sum + counter
        counter = counter + 1

# Print is outside of while loop but inside for Loop
    print("Sum of all numbers from 1 to %d is : %d" % (x,sum))

Link to program Code

Below is the Second  example program of Loops

# This program generates a random number between 0 to 20
# It aks user guess the number
# It allows the user 5 attempts
# Every incorrect attempt is alerted by a message
# Hinting if the answer is a bigger or a smaller

# import random module
import random

# randint function
x = random.randint(0,20)

# variables
guess = 0
attempts = 0

# loop
while(attempts < 5):
#   waiting for User input 
    guess = int(input("Enter your guess (from 0 to 20): "))

    if guess > x:
        print("You entered a bigger number")
    elif guess < x:
        print("You entered a smaller number")
    elif guess == x:
        print("That's a right answer!")
        break
#   loop increment 
    attempts = attempts + 1
# End of while loop
else:
    print("\nYou have exhausted 5 attempts, Better luck next time !!!")


Link to Program 2 Code
 

Featured Post

Creating Games in Scratch for ICSE Class 6

An Introduction to Creating Games in Scratch  for ICSE Class 6 Hello friends, I hope you have already read the previous post on An Int...