0% found this document useful (0 votes)
14 views1 page

Python Loop Syntax and Examples

The document provides syntax and examples for 'for' and 'while' loops in programming. It includes three sample programs: one to print natural numbers up to a given number, another to calculate the sum of those numbers, and a third to reverse a given number. Each example includes code snippets and expected output.

Uploaded by

darkflux514
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views1 page

Python Loop Syntax and Examples

The document provides syntax and examples for 'for' and 'while' loops in programming. It includes three sample programs: one to print natural numbers up to a given number, another to calculate the sum of those numbers, and a third to reverse a given number. Each example includes code snippets and expected output.

Uploaded by

darkflux514
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Computer Science

Syntax: (for loop)


for variable in range(start,stop+1,step):
statements
Syntax: (while loop)
while (condition):
Statements
Example:
1. Write a program to input any number and to print all natural numbers up to given number.
Code:
n = input("enter any number")
for i in range(1,n+1):
print i,
Output:
enter any number10
1 2 3 4 5 6 7 8 9 10
2. Write a program to input any number and to find sum of all natural numbers up to given number.
Code:
n = input("Enter any number")
sum= 0
for i in range(1,n+1):
sum = sum+i
print "sum=",sum
Output:
Enter any number5
sum = 15
3. Write a program to input any number and to find reverse of that number.
Code:
n = input("Enter any number")
r=0
while(n>0):
r = r*10+n%10
n = n/10

12

You might also like