Professional Documents
Culture Documents
Practical Guide and Programs
Practical Guide and Programs
Practical Guide and Programs
Python is a widely used general-purpose, high level programming language. It was created by
Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was
designed with an emphasis on code readability, and its syntax allows programmers to express
their concepts in fewer lines of code.
Keywords are some predefined and reserved words in python that have special meanings.
Keywords are used to define the syntax of the coding.
Identifier is a name used to identify a variable, function, class, module, etc. The identifier is a
combination of character digits and underscore. The identifier should start with a character or
Underscore then use a digit. The characters are A-Z or a-z, an Underscore ( _ ) , and digit (0-9). we
should not use special characters ( #, @, $, %, ! ) in identifiers.
Examples of valid identifiers:
var1
_var1
_1_var
var_1
Examples of invalid identifiers
!var1
1var
1_var
var#1
This is a logical operator it returns true if both the operands are true else return
and false.
This is also a logical operator it returns true if anyone operand is true else return
Or false.
This is again a logical operator it returns True if the operand is false else return
not false.
Else is used with if and elif conditional statement the else block is executed if the
else given condition is not true.
Keywords Description
This function is used for debugging purposes. Usually used to check the correctness
assert of code
Finally is use with exceptions, a block of code that will be executed no matter if
finally there is an exception or not.
Keywords Description
None This is a special constant used to denote a null value or avoid. It’s important to
remember, 0, any empty container(e.g empty list) do not compute to None
Data Structures
Python have 4 types of built in Data Structures namely List, Dictionary, Tuple and Set.
List is the most basic Data Structure in python. List is a mutable data structure i.e items can be
added to list later after the list creation. It’s like you are going to shop at the local market and
made a list of some items and later on you can add more and more items to the list.
append() function is used to add data to the list.
Output:
[21, 40.5, String]
Comments:
# is used for single line comment in Python
""" this is a comment """ is used for multi line comments
Input and Output
In this section, we will learn how to take input from the user and hence manipulate it or simply
display it. input() function is used to take input from the user.
Output:
hello harssh
Output:
Enter num1: 8 Enter num2: 6 ('Product is: ', 48)
Selection
Selection in Python is made using the two keywords ‘if’ and ‘elif’ and else (elseif)
Output:
Num1 is good
input ( prompt )
input (): This function first takes the input from the user and converts it into a string. The type
of the returned object always will be <type ‘str’>. It does not evaluate the expression it just
returns the complete statement as String. For example, Python provides a built-in function called
input which takes the input from the user. When the input function is called it stops the program
and waits for the user’s input. When the user presses enter, the program resumes and returns
what the user typed.
Syntax:
inp = input('STATEMENT')
Example:
1. >>> name = input('What is your name?\n') # \n ---> newline ---> It causes a line break
>>> What is your name?
Ram
>>> print(name)
Ram
Output:
Python print() function prints the message to the screen or any other standard output
device.
Syntax:
print(value(s), sep= ' ', end = '\n', file=file, flush=flush)
Parameters:
value(s): Any value, and as many as you like. Will be converted to a string before printed
sep=’separator’ : (Optional) Specify how to separate the objects, if there is more than
one.Default :’ ‘
end=’end’: (Optional) Specify what to print at the end.Default : ‘\n’
file : (Optional) An object with a write method. Default :sys.stdout
flush : (Optional) A Boolean, specifying if the output is flushed (True) or buffered (False). Default:
False
Return Type: It returns output to the screen.
Though it is not necessary to pass arguments in the print() function, it requires an empty
parenthesis at the end that tells python to execute the function rather calling it by name. Now,
let’s explore the optional arguments that can be used with the print() function.
String Literals
String literals in python’s print statement are primarily used to format or design how a specific
string appears when printed using the print() function.
\n : This string literal is used to add a new blank line while printing a statement.
“” : An empty quote (“”) is used to print an empty line.
Python if...else
Statement
In computer programming, we use
the if statement to run a block code only
when a certain condition is met.
For example, assigning grades (A, B,
C) based on marks obtained by a student.
1. if the percentage is above 90, assign
grade A
2. if the percentage is above 75, assign
grade B
3. if the percentage is above 65, assign
grade C
2. if...else statement
3. if...elif...else statement
1. Python if statement
The syntax of if statement in Python is:
if condition:
# body of if statement
Output
Number is positive.
The if statement is easy
number > 0
number = -5
if condition:
# block of code if condition is True
else:
# block of code if condition is False
if number > 0:
print('Positive number')
else:
print('Negative number')
Output
Positive number
This statement is always executed
number > 0
number = -5
Number is negative.
This statement is always executed.
3. Python if...elif...else
Statement
The if...else statement is used to execute
a block of code among two alternatives.
However, if we need to make a choice
between more than two alternatives, then
we use the if...elif...else statement.
The syntax of the if...elif...else statement
is:
if condition1:
# code block 1
elif condition2:
# code block 2
else:
# code block 3
Here,
if number > 0:
print("Positive number")
elif number == 0:
print('Zero')
else:
print('Negative number')
Output
Zero
This statement is always executed
# outer if statement
if condition1:
# statement(s)
# inner if statement
if condition2:
# statement(s)
Notes:
We can add else and elif statements to the
inner if statement as required.
We can also insert inner if statement inside
the outer else or elif statements(if they
exist)
We can nest multiple layers
of if statements.
Example 4: Python Nested if
Statement
number = 5
# outer if statement
if (number >= 0):
# inner if statement
if number == 0:
print('Number is 0')
for loop
while loop
Output
Swift
Python
Go
JavaScript
values = range(4)
Here, 4 inside range() defines a range
containing values 0, 1, 2, 3.
In Python, we can use for loop to iterate
over a range. For example,
# use of range() to define a range of values
values = range(4)
# iterate from i = 0 to i = 3
for i in values:
print(i)
Run Code
Output
0
1
2
3
for i in digits:
print(i)
else:
print("No items left.")
Run Code
Output
0
1
5
No items left.
left.
while condition:
# body of while loop
Here,
Output
1
2
3
4
5
i = 1
True 1 is printed.
n = 5
i = 2
True 2 is printed.
n = 5
i = 3
True 3 is printed.
n = 5
i = 4
True 4 is printed.
n = 5
i = 5
True 5 is printed.
n = 5
i = 6
False The loop is terminated.
n = 5
game_completed = True
print('Level Ends')
Run Code
Output
Output
Inside loop
Inside loop
Inside loop
Inside else
num1 = 1.5
num2 = 6.3
s = (a+b+c)/2
area = √(s(s-a)*(s-b)*(s-c))
Source Code
# Python Program to find the area of triangle
a = 5
b = 6
c = 7
# Uncomment below to take inputs from the user
# a = float(input('Enter first side: '))
# b = float(input('Enter second side: '))
# c = float(input('Enter third side: '))
x = 5
y = 10
# conversion factor
conv_fac = 0.621371
# calculate miles
miles = kilometers * conv_fac
print('%0.2f kilometers is equal to %0.2f miles' %(kilometers,miles))
# calculate fahrenheit
fahrenheit = (celsius * 1.8) + 32
print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit' %
(celsius,fahrenheit))
Python Program to Check if a
Number is Positive, Negative or 0
num = float(input("Enter a number: "))
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
Using Nested if
num = float(input("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
year = 2000
# if not divided by both 400 (century year) and 4 (not century year)
# year is not leap year
else:
print("{0} is not a leap year".format(year))
Python program to find the largest number among the three input numbers
lower = 900
upper = 1000
factorial = 1
num = 12
while(True):
if((greater % x == 0) and (greater % y == 0)):
lcm = greater
break
greater += 1
return lcm
num1 = 54
num2 = 24
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
while True:
# take input from the user
choice = input("Enter choice(1/2/3/4): ")
if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))
Output
Select operation.
1.Add
2.Subtract
3.Multiply
4.Divide
Enter choice(1/2/3/4): 3
Enter first number: 15
Enter second number: 14
15.0 * 14.0 = 210.0
Let's do next calculation? (yes/no): no
* *
* * *
* * * *
* * * * *
Source Code
rows = int(input("Enter number of rows: "))
for i in range(rows):
for j in range(i+1):
print("* ", end="")
print("\n")
Run Code
First, we get the height of the pyramid rows from the user.
In the first loop, we iterate from i = 0 to i = rows .
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Source Code
rows = int(input("Enter number of rows: "))
for i in range(rows):
for j in range(i+1):
print(j+1, end=" ")
print("\n")
Run Code
First, we get the height of the pyramid rows from the user.
In the first loop, we iterate from i = 0 to i = rows .
In the second loop, we print numbers starting from 1 to j , where j ranges
from 0 to i .
After each iteration of the first loop, we print a new line.
B B
C C C
D D D D
E E E E E
Source Code
rows = int(input("Enter number of rows: "))
ascii_value = 65
for i in range(rows):
for j in range(i+1):
alphabet = chr(ascii_value)
print(alphabet, end=" ")
ascii_value += 1
print("\n")
Run Code
The working of the above example is also similar to the other examples
discussed above except that the ascii values are printed here. The ascii
value for alphabets start from 65 (i.e. A). Therefore, in each iteration, we
increase the value of ascii_value and print its corresponding alphabet.
* * * * *
* * * *
* * *
* *
*
Source Code
rows = int(input("Enter number of rows: "))
print("\n")
Run Code
This example is similar to an upright pyramid except that here we start from
the total number of rows and in each iteration we decrease the number
of rows by 1.
1 2 3 4 5
1 2 3 4
1 2 3
1 2
Source Code
rows = int(input("Enter number of rows: "))
print("\n")
Run Code
The only difference between an upright and an inverted pyramid using
numbers is that the first loop starts from the total number of rows to 0.
* * *
* * * * *
* * * * * * *
* * * * * * * * *
Source Code
rows = int(input("Enter number of rows: "))
k = 0
while k!=(2*i-1):
print("* ", end="")
k += 1
k = 0
print()
Run Code
This type of pyramid is a bit more complicated than the ones we studied
above.
The outermost loop starts from i = 1 to i = row + 1 .
Among the two inner loops, the for loop prints the required spaces for each
row using formula (rows-i)+1 , where rows is the total number of rows
and i is the current row number.
The while loop prints the required number stars using formula 2 * i - 1.
This formula gives the number of stars for each row, where row is i .
2 3 2
3 4 5 4 3
4 5 6 7 6 5 4
5 6 7 8 9 8 7 6 5
Source Code
rows = int(input("Enter number of rows: "))
k = 0
count=0
count1=0
while k!=((2*i)-1):
if count<=rows-1:
print(i+k, end=" ")
count+=1
else:
count1+=1
print(i+k-(2*count1), end=" ")
k += 1
count1 = count = k = 0
print()
Run Code
Like example 6, this example also makes use of two loops inside a for loop.
Here we use two counters count and count1 for printing the spaces and
numbers respectively.
The inner for loop prints the required spaces using formula (rows-i)+1 ,
where rows is the total number of rows and i is the current row number.
The while loop prints the numbers where 2 * i - 1 gives the number of
items in each row.
* * * * * * * * *
* * * * * * *
* * * * *
* * *
Source Code
rows = int(input("Enter number of rows: "))
The first inner for loop prints the spaces required in each row.
The second inner for loop prints the first half of the pyramid (vertically cut),
whereas the last inner for loop prints the other half.
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
Source Code
rows = int(input("Enter number of rows: "))
coef = 1
The second inner loop first finds the number to be printed using
statement coef = coef * (i - j) // j and then prints it. Here, i is the row
number and j is the value ranging from 0 to i .
2 3
4 5 6
7 8 9 10
Source Code
rows = int(input("Enter number of rows: "))
number = 1
The inner for loop starts from 1 to i + 1, where i is the row number. After
each iteration, the value of the number is increased.