Python Notes unit 2
Python Notes unit 2
Python Notes unit 2
Decision Making---
Decision-making is the anticipation of conditions occurring during the
execution of a program and specified actions taken according to the
conditions.
if statements
1
An if statement consists of a boolean expression followed by
one or more statements.
if...else statements
An if statement can be followed by an optional else
2 statement, which executes when the boolean expression is
FALSE.
nested if statements
3
You can use one if or else if statement inside
another if or else if statement(s).
If Statement
If-Else Statement
Nested if Statements (if with in if)
If-elif-else Statement
num1,num2,num3=map(int,input("Enter three
numbers:").split(" "))
if(num1>num2 and num1>num3):
print("{} is greatest".format(num1))
elif (num2>num3):
print("{} is greatest".format(num2))
else:
print("{} is greatest".format(num3))
For first 150 units, charges are Rs. 3.0 per unit
For units >150 and <=300, charges are Rs. 4.5 per unit
For units>300 and <=500, charges are Rs. 6.0 per units
else:
amount = 150*3.00 + 150*4.50 +200*6.00+ ((units - 500) * 8.00)
Loops---
A loop statement allows us to execute a statement or group of statements multiple
times.
Python programming language provides the following types of loops to
handle looping requirements.
While Loop----
For Loop ----For loop provides a mechanism to repeat a task until a
particular condition is True. It is usually known as a determinate or definite loop
because the programmer knows exactly how many times the loop will repeat.
The range() produces a sequence of numbers starting with beg (inclusive) and
ending with one less than the number end. The step argument is option (that is
why it is placed in brackets). By default, every number in the range is incremented
by 1 but we can specify a different increment using step. It can be both negative
and positive, but not zero.
• If range() has three arguments then the third argument specifies the interval of
the sequence produced. In this case, the third argument must be an integer. For
example, range(1,20,3).
A for loop can be used to control the number of times a particular set of statements
will be executed. Another outer loop could be used to control the number of times
that a whole loop is repeated.
2. n=int(input("Enter a number:"))
3. tot=0
4. while(n>0):
5. dig=n%10
6. tot=tot+dig
7. n=n//10
8. print("The total sum of digits is:",tot)
9. n=int(input("Enter number:"))
10. temp=n
11. rev=0
12. while(n>0):
13. dig=n%10
14. rev=rev*10+dig
15. n=n//10
16. if(temp==rev):
17. print("The number is a palindrome!")
18. else:
19. print("The number isn't a palindrome!")
3. Write a program to check whether a given number is armstrong or not.
n=int(input("Enter number:"))
fact=1
while(n>0):
fact=fact*n
n=n-1
print("Factorial of the number is: ")
print(fact)