0% found this document useful (0 votes)
6 views4 pages

Python Answers

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

Python Answers

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

1.

Rules for Python variables:

 A variable name must start with a letter or the underscore


character
 A variable name cannot start with a number
 A variable name can only contain alpha-numeric
characters and underscores (A-z, 0-9, and _ )
 Variable names are case-sensitive (age, Age and AGE are
three different variables)
 A variable name cannot be any of the Python keywords.

2.If statement syntax

if condition:
# body of if statement

Example
if number > 0:
print('Number is positive.')

3.If else syntax

if condition:
# block of code if condition is True

else:
# block of code if condition is False

Example
number = 10

if number > 0:
print('Positive number')

else:
print('Negative number')

4.nested if example
number = 5
if (number >= 0):
if number == 0:
print('Number is 0')

else:
print('Number is positive')

else:
print('Number is negative')

5. LOOP
Looping means repeating something over and over until a particular
condition is satisfied.

6.syntax while loop

while <condition>:
{ code block }

Example:
i=1
while i < 6:
print(i)
i += 1

7.For loop syntax


for value in sequence:
{ code block }

Example
for k in range (1,11):
if(k%2==0):
print(k)

8.Break and Continue


The break statement is used to terminate the loop immediately when it
is encountered.
for i in range(5):
if i == 3:
break
print(i)

The continue statement is used to skip the current iteration of the loop
and the control flow of the program goes to the next iteration.
for i in range(5):
if i == 3:
continue
print(i)

9.prime numbers
i=2

while i <= 100:


j=2
while j < 100:
if i%j == 0:
break
j += 1
if i == j:
print(i,end=',')
i += 1

10.perfect numbers
for n in range(1,101):
sum = 0

for i in range(1, n):


if n%i == 0:
sum += i
#print(n, sum)

if n == sum:
print(n)
11.reverse number
n=int(input("enter any digit"))
r=0
while(n>0):
r=n%10
print(r,end="")
n=n//10

12.sum of digits
n=input("any integer")
n=int(n)
ds=0
while(n>0):
r=n%10
ds=ds+r
n=n//10
print("the sum of digits is",ds)

You might also like