Python Programs
Python Programs
")
Python Indentation
Indentation refers to the spaces at the beginning of a code line.
Where in other programming languages the indentation in code is for
readability only, the indentation in Python is very important.
Python uses indentation to indicate a block of code.
if 5 > 2:
print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!")
You have to use the same number of spaces in the same block of
code, otherwise Python will give you an error:
if 5 > 2:
print("Five is greater than two!")
print("Five is greater than two!")
Python Variables
In Python, variables are created when you assign a value to it:
x = 5
y = "Hello, World!"
_
Comments
Python has commenting capability for the purpose of in-code
documentation.
Comments start with a #, and Python will render the rest of the
line as a comment:
#This is a comment.
print("Hello, World!")
#print("Hello, World!")
print("Cheers, Mate!")
#This is a comment
#written in
#more than just one line
print("Hello, World!")
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
Creating Variables
Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.
x = 5
y = "John"
print(x)
print(y)
Variables do not need to be declared with any particular type, and
can even change type after they have been set.
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)
num1 = 1.5
num2 = 6.3
num = 16
if num < 0:
print("Enter a positive number")
else:
sum = 0
# use while loop to iterate until zero
while(num > 0):
sum += num
num -= 1
print("The sum is", sum)
_
# Driver Code
num = 5
print("Factorial of",num,"is",factorial(num))
def Fibonacci(n):
if n<= 0:
print("Incorrect input")
# First Fibonacci number is 0
elif n == 1:
return 0
# Second Fibonacci number is 1
elif n == 2:
return 1
else:
return Fibonacci(n-1)+Fibonacci(n-2)
# Driver Program
print(Fibonacci(10))
_
Python Program to Find Area of a Circle
def findArea(r):
PI = 3.142
return PI * (r*r);
# Driver method
print("Area is %.6f" % findArea(5));
Factorial Program
# import math
# def fact(num):
# i=num
# z=1
# while i<=num and i !=0:
# print(i)
# z *= i
# i -= 1
# return z
# def factorial(n):
# if n == 0:
# return 1
# else:
# return n * factorial(n - 1)
# print(fact(10))
# print(math.factorial(10))
# print(factorial(10))
# def sumOfNaturalNumber(num):
# z=0
# while 0 < num:
# z += num
# num -= 1
# return z
# print(sumOfNaturalNumber(3))
# def sumOfNaturalNumberWithForLoop(num):
# total=0
# for i in range(1, num + 1):
# print(i)
# total += i
# return total
# print(sumOfNaturalNumberWithForLoop(3))
# print(newFruits)
if choice == 'a':
print (num_1, " + ", num_2, " = ", add(num_1, num_2))
__________________
# create a class
class Room:
length = 0.0
breadth = 0.0