Python for Data Science
About Lesson

1 if Statement

A decision box in a flowchart is implemented by an if statement in Python.
Using an if statement, a programmer can essentially ask a yes/no question, and if the answer is yes, then some code will run, otherwise another code will run.

And here is the syntax of the if statement in Python:

Syntax
				
					if <Boolean expression>: 
# notice the colon at the end of the line
    <indented block of code>
    # indented block may contain any number of indented lines
				
			

Together if statement and indented block of code is called ‘Body of if’.

1.1 Boolean Expression

Think of a Boolean expression as a condition or a question that can only have two possible answers: True or False.

The indented block of code will be executed only when the Boolean expression is evaluates to True.

EX1
				
					
if 5 > 2: # This is going to result into True - Condition is satisfied
    print("5 is greater than 2") # This will be executed


				
			
				
					
if 5 < 2: # This is going to result into False - Condition is not satisfied
    print("5 is less than 2") # This won't be executed
				
			

We can also write ‘True’ directly in the place of Boolean Expression. 

In such a case the code inside if will be always executed.

EX2
				
					
if True: # Condition is satisfied
    print("Instead of Boolean Expression True is directly written")
    print("Therefore condition of if is always True")
    print("All of these lines are going to execute")

				
			

Similarly, if the Boolean Expression condition evaluates to False or if we write False directly in the place of Boolean Expression condition, none of the code inside if is going to be executed.

EX3
				
					
if False: # Condition is not satisfied
    print("This line will not get executed") # Won't execute
				
			

Remember: The boolean equivalent of any non-zero number (even negative numbers) is True. 

EX4
				
					if 1: # Condition is satisfied
	print("Hi")
if -1.2: # Condition is satisfied
	print("How are you?")
if 0: # Condition is not satisfied
	print("Hope you are doing good")
				
			

The boolean equivalent of any non-empty string (even “0”) is True (even “0”) and boolean equivalent of empty strings is False.

EX5
				
					if "abc": # Non-empty string; Condition is satisfied
    print("Hi") # Will be printed
if "": # Empty string; Condition is not satisfied
	print("Hi There!") # Won't print
				
			

Boolean equivalent of None keyword is False.

EX6
				
					
if None: # Condition is not satisfied
    print("Hi There!") # Won't be printed
    

				
			

1.2 Indentation

Notice that all the code to be executed when the Boolean expression evaluates to True is indented.

Indention in Python simply means left margin of 4 spaces.

When you type an if statement (that ends in a colon), IDLE automatically indents any subsequent lines that you type.

The first line must end with a colon. The colon always tells IDLE that the programmer is providing an indented line or block of lines.

There can be any number of indented lines.

However all indented lines in a block must have the same indention (i.e. equal left margin)

When you are finished entering lines that should execute when the Boolean expression evaluates to True, you press the Backspace key (Windows) or the Delete key (Mac) to move the cursor back to the indent level of the matching if statement.

Syntax
				
					if <Boolean expression>:
    <indented block of code> # Inside if and part of body of if
<another block of code># Not inside if and not part of body of if

				
			

1.3 Comparison Operators

Two equal to signs together == (known as equals equals operator) are used to compare two values.

Remember:

Don’t use single equals sign (=) for comparison.

The single equals sign (=) is used for assigning value and is called the assignment operator.

If you try to use a single equals sign inside an if statement, Python will generate an error.

EX7
				
					
if courseName == 'PyStrike Embark':
    print('You will be successful')
    yourWorth = yourWorth * 2

				
			
				
					
if teachersName == 'Jolly':
    teachingPython = True
    print('Pay attention to his wisdom')
    respectPoints = respectPoints + 10

				
			
				
					
if nReadersUnderstandingPython == 0:
	fireJolly()
    getNewTeacher()
				
			

Try Yourself 1

Ask the user whether he is ready or not to learn Python. If the user is ready, print ‘Ok, here we go.’

Solution

				
					
answer = input('Are you ready to learn Python (yes or no)? ')
if answer == 'yes':
    print('OK, here we go.')
				
			

Try Yourself

Write a program to check if a number entered by user is even.

Solution

				
					num = int(input("Enter a number: "))
if (num%2 == 0):
    print("Number is even")

				
			

Try Yourself

Write a program to check if a number entered by user is a multiple of 6.

Solution

				
					num = int(input("Enter a number "))
if (num % 6 == 0):
    print("Number is multiple of 6 ")
				
			

In addition to the equals equals (==) operator, following are the additional operators that you can use in if statements for comparisons

Operator

Meaning

Example

==

Equals

if a == b:

!=

Not equals

if a != b:

<

Less than

if a < b:

>

Greater than

if a > b:

<=

Less than or equal to

if a <= b:

>=

Great than or equal to

if a >= b:

EX8
				
					
if userPassword != savedPassword:
    giveErrorMessageAboutPassword()
				
			
				
					
if cashInWallet < costOfProduct:
    print('You need more cash')
				
			
				
					
if cashInWallet > costOfProduct:
	purchaseProduct()
    cashInWallet = cashInWallet - costOfProduct
				
			
				
					
if salesAchieved <= 10000:
    eligibleForBonus = False
				
			
				
					
if age >= 18:
    allowedToVote = True
				
			

Try Yourself 2

Write a program to check if a number entered by user is greater than 10.

Solution

				
					num = int(input("Enter a number: "))
if num > 10:
    print("Your number is greater than 10")

				
			

Try Yourself 3

Take two numbers as input and check if the first number is greater than the second number.

Solution

				
					num1 = input("Enter first number ")
num2 = input("Enter second number ")
 
if num1 > num2:
    print("First number is greater than the second number")

				
			

2 Nested if Statements

When a Boolean expression in an if statement evaluates to True, then the indented block of code runs.

But the indented block of code can contain another if statement (called nested if).

And if the Boolean expression in an indented if statement (nested if) also evaluates to True, then the indented code block associated with that if statement (nested if) will run.

EX9
				
					hoursWorked = int(input("Enter the number of hours worked: "))
if hoursWorked  > 40:
   wages = hoursWorked * 100
   if hoursWorked > 60:
      wages = 40 * 100 + (hoursWorked - 40) * 200
print(wages)
				
			
				
					
if balanceMoney > 100:
	feeling = evaluateEmotions()
	if feeling == 'lucky':
		buyLotteryTicket()
        balanceMoney = balanceMoney - 20
				
			

Remember

You can nest if statements as many times as you need to. However, too much nesting makes code difficult to read.

3 else Statement

In an if statement, we often want to execute different blocks of code based on whether the answer to a Boolean expression is True or False.

Here is the syntax of an if/else:

Syntax
				
					
if <Boolean expression>:
	<some indented code>
else: # Notice the colon here too
    <other indented code>
				
			

In this case, the indented code runs only if the original Boolean expression in the if statement evaluated to False.

The else statement and the block of code associated with it are commonly known as an else clause or body of else.

The else clause is optional.

Similar to the if statement, the else statement must have a trailing colon.

Also, similar to if, we use indentation to represent the body of else.

EX10
				
					hoursWorked = int(input("Enter the number of hours worked: "))
if hoursWorked  > 40:
   wages = hoursWorked * 100
else:
   wages = hoursWorked * 50
print(wages)
				
			
EX11
				
					
userAnswer = input('What is 6 + 3? ') # Get the user's answer
userAnswer = int(userAnswer) # convert to an integer
if userAnswer == 9:
	print('You are a genius')
else:
    print('Sorry, that is not correct. The correct answer was 9')
				
			

Try Yourself 4

Ask the user to enter a number that is under 20. If they enter a number that is 20 or more, display the message “Too high”, otherwise display “Thank you”.

Solution

				
					num = int (input ("Enter a value less than 20: "))
if num >= 20:
    print ("Too high")
else: 
    print ("Thank you")

				
			

Try Yourself

Ask for two numbers. If the first one is larger than the second, display the second number first and then the first number, otherwise show the first number first and then the second.

Solution

				
					numl = int (input ("Enter first number: "))
num2 = int (input ("Enter second number: "))
if numl > num2 :
    print (num2, numl)
else:
    print (numl, num2 )
				
			

Try Yourself

Ask the user to enter a number, convert it to a floating point number. Use that floating point number in a call to your absoluteValue function, and print the result.

Solution

				
					
# we could ask the user to enter a number, use that number in a call to our function, and print the result.
# Get user input and convert to a floating point number
userNumber = input('Enter a number: ')
userNumber = float(userNumber)
# Call the function with the user's number and print the answer
result = absoluteValue(userNumber)
print('The absolute value of', userNumber, 'is', result)
				
			

Try Yourself

Ask the user to enter first double digit number. Then ask the user to enter another double digit number. Ask the user the total of these two numbers. If the user answers correctly print “You are a genius” otherwise print “You need more practice”.

Solution

				
					
number1=input('Enter first double digit number?')
number1 = int(number1)
number2=input('Enter second double digit number?')
number2 = int(number2)
sum = number1 + number2
answer=input('Now answer what is the total of these two numbers?')
answer=int(answer)

if answer == sum:
    print("You are a genius")
else:
    print("You need more practice")
				
			

Try Yourself

Write a program to check whether the input number is even or odd.

Solution

				
					num = int(input("Enter a number: "))
if(num % 2 == 0):
    print("Number is even")
else:
    print("Number is odd")

				
			

Try Yourself

Write a program to check whether a person is eligible for voting or not. Assume that the voting age is equal to or greater than18 years.

Solution

				
					age = int(input("Enter your age"))
if age >= 18:
    print("Eligible for voting")
else:
    print("Not eligible for voting")

				
			

Try Yourself

Write a program to take two integer inputs from user and check if the division of the first number by the second number is possible. If the division is possible, print the remainder, otherwise print “Division is not possible”.

Solution

				
					m = int(input("Enter dividend :- "))
n = int(input("Enter divisor :- "))
if(n == 0):
    print("Division not possible")
else:
    print("Remainder =", m % n)
				
			

Try Yourself

Write a program to take two numbers as input and check whether the first number is greater than the second or not.

Solution

				
					first_number = int(input("Enter the first number: "))
second_number = int(input("Enter the second number: "))

if first_number > second_number:
    print(first_number, "is greater than the", second_number)
else:
    print(first_number, "is not greater than the", second_number)
				
			

Try Yourself 5

A company decided to give bonus of 5% to employee if his/her year of service is more than 5 years.

Ask user for their salary and year of service and print the net bonus amount.

Solution

				
					print ("Enter salary")
salary=int(input())
print ("Enter year of service")
yos=int(input())
if yos>5:
    print ("Bonus is",.05*salary)
else:
    print ("No bonus")
				
			

Try Yourself 6

Take values of length and breadth of a rectangle from user and check if it is square or not.

Solution

				
					print("Enter length")
length=input()
print("Enter breadth")
breadth=input()

if length==breadth:
    print("Yes, it is square")
else:
    print("No, it is only Rectangle")
				
			

Try Yourself

Write a program to print absolute value of a number entered by user. Example

INPUT: 1        OUTPUT: 1

INPUT: -1        OUTPUT: 1

Solution

				
					print ("Enter a number")
number = int(input())

if number<0:
  print (number*-1)
else:
  print (number)
				
			

4 elif Statement

It turns out that you often need to check for three, four, five, or any number of different cases.

To handle this, Python gives us another addition to the if statement, called the elif statement.

elif is a made-up word that came from taking the words else if and smashing them together—so it really means else if.

Elif is used as an extended else statement to test another condition when the earlier condition evaluates to False.

You can ask multiple Boolean questions, and when there is a match (that is, a Boolean expression evaluates to True), then the block of code associated with that case is executed.

Here is what the syntax looks like in Python:

Syntax
				
					
if <Boolean expression>:
	<some code>
elif <Boolean expression>:
	<some code>
elif <Boolean expression>:
	<some code>
# as many elif's as you need ...
else:
    <some default code>
				
			

Remember

Once one of the Boolean expressions evaluates to True, then the indented code below it runs.

When that block is finished, control is passed to the first statement beyond the if/elif/else.

If none of the Boolean expressions evaluates to True, then the code block associated with the else will execute.

This way, the else block serves as a “catchall.”

We can also skip else if needed.

EX12
				
					
def createHeader(fullName, gender):
	if gender == 'm':
		title = 'Mr.'
	elif gender == 'f':
		title = 'Ms.'
	else: #not sure, could be male or female
		title = 'Mr. or Ms.'
	header = 'Dear ' + title + ' ' + fullName + ',' # use concatenation
	return header

print(createHeader('Joe Smith', 'm'))
print(createHeader('Susan Jones', 'f'))
print(createHeader('Chris Smith', '?')) # Not sure if this is male or female
				
			

Let’s take an example to compare two numbers entered by a user. Without using else, we can do:

				
					first_number = int(input("Enter the first number: "))
second_number = int(input("Enter the second number: "))

if first_number > second_number:
    print(first_number, "is greater than the", second_number)

if first_number < second_number:
    print(second_number, "is greater than the", first_number)

if first_number == second_number:
    print(first_number, "is equal to the", second_number)
				
			

We can write the above code using elif as:

				
					first_number = int(input("Enter the first number: "))
second_number = int(input("Enter the second number: "))

if first_number > second_number:
    print(first_number, "is greater than the", second_number)

elif first_number < second_number:
    print(second_number, "is greater than the", first_number)

else:
    print(first_number, "is equal to the", second_number)
				
			

Try Yourself

Take two int values from user and print greatest among them.

Solution

				
					print ("Enter first number")
first = input()
print ("Enter second number")
second = input()
if first>second:
  print ("Greatest is",first)
elif second>first:
  print ("Greatest is",second)
else:
  print ("Both are equal")

				
			

4.1 Using many elif Statements

EX13
				
					
def whatToWear(temperature):
	if temperature > 90:
		clothes = 'swim suit'
	elif temperature > 70:
		clothes = 'shorts'
	elif temperature > 50:
		clothes = 'long pants'
	else:
		clothes = 'thermal underwear and long pants'
	return 'Put on ' + clothes

print(whatToWear(100))
print(whatToWear(40))
print(whatToWear(71))
				
			

When we run this code, we get the following output:

				
					Put on swim suit

Put on thermal underwear and long pants

Put on shorts
				
			

Try Yourself 7

Write a function to convert a number score to a letter grade:
score >= 90: A
score >= 80: B
score >= 70: C
score >= 60: D
else: F

Solution

				
					
#Convert a number score to a letter grade:
def letterGrade(score):
	if score >= 90:
		letter = 'A'
	elif score >= 80:
		letter = 'B'
	elif score >= 70:
		letter = 'C'
	elif score >= 60:
		letter = 'D'
	else:
		letter = 'F' #fall through or default case
	return letter

print(letterGrade(95)) #call and print in one statement
				
			

Try Yourself

Write a program to find Day of week by taking input as a number.

For number = 1 output Will be MONDAY.

Solution

				
					n = int(input("Enter week number from(1-7): "))
if(n == 1):
    print("MONDAY")
elif(n == 2):
    print("TUESDAY")
elif(n == 3):
    print("WEDNESDAY")
elif(n == 4):
    print("THURSDAY")
elif(n == 5):
    print("FRIDAY")
elif(n == 6):
    print("SATURDAY")
elif(n == 7):
    print("SUNDAY")
				
			

Try Yourself

Write a program to input the day of week as an integer value and display the name of the week day in words. Assume the week starts from Monday and ends with Sunday.

The input should be an integer from 1 to 7. In case of any other input, print Invalid day.

Solution

				
					day = int(input("Enter a number for day of the week: "))
if day == 1:
    print("Monday")
elif day == 2:
    print("Tuesday")
elif day == 3:
    print("Wednesday")
elif day == 4:
    print("Thursday")
elif day == 5:
    print("Friday")
elif day == 6:
    print("Saturday")
elif day == 7:
    print("Sunday")
else:
    print("Invalid day")
				
			

5 Conditional Logic

There are three logical operator keywords: not, and, and or.

5.1 The Logical not Operator

Remember that a Boolean can only have a value of True or False. The not operator takes a Boolean value and reverses it.

If a Boolean value is False, applying the not operator changes the value to True.

If the value is True, not operator changes the value to False.

The not operator is entered directly in front of any Boolean variable or expression.

EX14
				
					
if not open:
	# closed
if not broken:
	# working
if not(width == length):
    # not a square
				
			
EX15
				
					true_value = (5 > 2) # true
false_value = (5 % 2 == 0) # false

print(not(true_value)) # false
print(not(false_value)) # true
				
			

5.2 The Logical and Operator

The and operator works between two Boolean values like (age >= 12) and (height >= 48)

It allows you to do multiple comparisons within a single if statement.

Input1

 

Input2

Result

False

and

False

False

False

and

True

False

True

and

False

False

True

and

True

True

Notice that you get a result of False in every case except when both inputs are True.

EX16
				
					true_value = (5 > 2) # True
false_value = (5 % 2 == 0) # False

print(true_value and true_value) # True
print(true_value and false_value) # False
print(false_value and true_value) # False
print(false_value and false_value) # False
				
			

The indented block of code following the if statement will only execute if the expressions on both sides of an and operator evaluate to True.

EX17
				
					
if (age >= 12) and (height >= 48):
    # OK to get on roller coaster at amusement park
				
			
EX18
				
					
if (location == 'Hamburger Restaurant') and (nDollars > 4):
    # can buy a hamburger and fries
				
			
EX19
				
					
if (x >= 5) and (x =< 10):
	# x is between 5 and 10

				
			

Try Yourself

Ask the user to enter a student’s marks and attendance. A student will be eligible to sit in the exam if marks >= 35 and attendance >=40. Print the eligibility to sit in the exam.

Solution

				
					marks = int(input("Enter marks: "))
attendence = int(input("Enter Attendence: "))

eligible_to_sit_in_exam = (marks >= 35) and (attendence >= 40)

print("Eligible to sit in exam: ", eligible_to_sit_in_exam)

				
			

Try Yourself 8

Ask the user to enter a number between 10 and 20 (inclusive). If they enter a number within this range, display the message “Thank you”, otherwise display the message “Incorrect answer”.

Solution

				
					num = int (input ("Enter a value between 10 and 20: "))
if num >= 10 and num <=20:
    print ("Thank you")
else:
    print ("Incorrect answer")
				
			

Try Yourself

Check if the number entered by the user is a 3-digit number.

Solution

				
					num = int(input("Enter your number: "))
if(num < 1000 and num > 99):
    print(num, "is a 3 digit number")
else:
    print(num, "is not a 3 digit number")

				
			

Try Yourself

Ask the user to enter 1, 2 or 3. If they enter a 1, display the message “Thank you”, if they enter a 2, display “Well done”, if they enter a 3, display “Correct”. If they enter anything else, display “Error message”.

Solution

				
					num = input("Enter 1, 2 or 3: ")
if num == "1":
    print ("Thank you")
elif num == "2":
    print ("Well done")
elif num == "3":
    print ("Correct")
else:
    print ("Error message")
    
				
			

Try Yourself

A school has following rules for grading system:

a. Below 25 – F

b. 25 to 45 – E

c. 45 to 50 – D

d. 50 to 60 – C

e. 60 to 80 – B

f. Above 80 – A

Ask user to enter marks and print the corresponding grade.

Solution

				
					print("Enter marks")
marks = int(input())
if marks<25:
  print("F")
elif marks>=25 and marks<45:
  print("E")
elif marks>=45 and marks<50:
  print("D")
elif marks>=50 and marks<60:
  print("C")
elif marks>=60 and marks<80:
  print("B")
else:
  print("A")
				
			

Try Yourself 9

Write a program that accepts percentage from the user and displays the grade according to the following criteria:

Marks                       Grade

> 90                           A

> 80 and <= 90        B

>= 60 and <= 80      C

below 60                  D

Solution

				
					per = int(input("Enter percentage: "))
if per > 90:
    print("Grade is A")
elif per > 80 and per <= 90:
    print("Grade is B")
elif per >= 60 and per <= 80:
    print("Grade is C")
else:
    print("Grade is D")
				
			

Try Yourself 10

A company decided to give bonus to employee according to following criteria:

Time period of Service        Bonus

More than 10 years              10%

=6 and <=10                         8%

Less than 6 years                 5%

Ask user for their salary and years of service and print the net bonus amount.

Solution

				
					year = int(input("Enter the time period of service: "))
sal = int(input("Enter your salary: "))
if year > 10:
    b = 10 / 100 * sal
if year >= 6 and year <= 10:
    b = 8 / 100 * sal
if year < 6:
    b = 5 / 100 * sal
print("Bonus is", b)
				
			

5.3 The Logical or Operator

The or operator also works between two Boolean values, and it also allows you to do multiple comparisons in a single if statement.

Input1

 

Input2

Result

False

or

False

False

False

or

True

True

True

or

False

True

True

or

True

True

Notice that the result is True in every case except when both inputs are False.

EX20
				
					true_value = (5 > 2) # True
false_value = (5 % 2 == 0) # False

print(true_value or true_value) # True
print(true_value or false_value) # True
print(false_value or true_value) # True
print(false_value or false_value) # False

print(not(true_value)) # False
print(not(false_value)) # True
				
			

The indented block of code following the if statement will execute if either side of an or operator evaluates to True.

EX21
				
					
if (userCommand == 'q') or (userCommand == 'quit'):
    # quit the program

				
			
EX22
				
					
if (age > 65) or disabled:
    # can get government benefits

				
			

Try Yourself

Write a program to check whether a character entered by user is a vowel.

Solution

				
					ch = str(input("Enter a character "))
if (ch == 'a' or ch == 'e' or ch == 'i' or ch == 'o' or ch == 'u' or
        ch == 'A' or ch == 'E' or ch == 'I' or ch == 'O' or ch == 'U'):
    print("This character is a vowel ")
				
			

Try Yourself

Write a program to check input given as a character is a vowel or a consonent.

Solution

				
					ch = input("Enter the character: ")
if(ch == "a" or ch == "A" or ch == "e" or ch == "E" or ch == "i" or ch == "I" or  ch == "o" or ch == "O" or ch == "u" or ch == "U"):
    print("Vowel")
else:
    print("Consonent")
				
			

Try Yourself 11

Get the Years of Service and Performance Rating (out of 10) from the user. If the Performance Rating is greater than 7 or Years of Service are greater than 5 then the candidate is eligible for bonus. Print the eligibility of the candidate based on above conditions.

Solution

				
					year_of_service = int(input("Enter year of service: "))
rating = int(input("Enter rating (out of 10): "))

eligible_for_bonus = (rating > 7) or (year_of_service > 5)

print("Eligible for Bonus: ", eligible_for_bonus)

				
			

Try Yourself

Ask the user to enter their favourite colour. If they enter “red”, “RED” or “Red” display the message “I like red too”, otherwise display the message “I don’t like [colour], I prefer red”.

Solution

				
					colour = input ("Type in your favourite colour: ")
if colour == "red" or color == "RED" or colour == "Red":
    print ("I like red too.")
else:
    print("I don't like that color, I prefer red")
				
			

Try Yourself

Ask the user to enter a number. If it is under 10, display the message “Too low”, if their number is between 10 and 20, display “Correct”, otherwise display “Too high”.

Solution

				
					num = int(input("Enter a number: "))
if num <10:
    print("Too low")
elif num >=10 and num <=20:
    print ("Correct")
else:
    print("Too high")
				
			

Try Yourself

Write a program to take the three sides of a triangle as input and check whether the triangle is valid or not.

A triangle is valid if sum of any two sides of the triangle is greater than or equal to the third side.

Solution

				
					a = int(input("First side :- "))
b = int(input("Second side :- "))
c = int(input("Third side :- "))
if (a + b <= c) or (a + c <= b) or (b + c <= a) :
    print("Not Valid")
else:
    print("Valid")
				
			

6 Precedence of Comparison and Logical Operators

Use parentheses to force the order of comparison and logical operators.

Adding a set or sets of parentheses makes your intentions clear by creating groupings.

EX23
				
					
if not(inJail) and ((cash >= 1000000) or (haveHighPayingJob and (downPayment >= 90000)):
    # Can buy a house in Silicon Valley

				
			

7 Booleans in if Statements

Very often, programmers use a Boolean variable to remember the result of an early calculation or

setting. Then later, the code tests the Boolean to see which piece of code should run.

EX24
				
					
if (age > 21) and (gender == 'f'):
	adultFemale = True
else:
	adultFemale = False

if adultFemale == True:
    # Make some special comment/recommendation

				
			

However, comparing a Boolean to True is not necessary. The following is exactly equivalent:

EX25
				
					
if adultFemale:
    # Make some special comment/recommendation

				
			

8 pass Statement

If we want to use if, elif or else without anything in their body, we can use the pass keyword.

EX26
				
					if 5>2:
    print("5 is greater than 2")
else:
    pass


				
			
EX27
				
					num = int(input("Enter number: "))

if num < 10:
    print("Number is less than 10")
elif num < 100:
    pass
else:
    print("Number is greater than 100")

				
			

9 Nesting

Nesting is just having a block of code inside another. We can write any code inside if, elif or else and thus we can also write if, elif and else inside one another. For example:

Syntax
				
					
if condition:
    code_line1 # Inside outer if
    if condition2:
        code_line2 # Inside outer and inner if
        code_line3 # Inside outer and inner if
    code_line4 # Inside outer if
				
			

Here, the condition of the first if will be checked first and if it satisfies, then its body is going to be executed. Inside it, firstly we have code_line1. So, it will be executed. After this, we have another if with a condition condition2. If this satisfies, then code_line2 and code_line3 are going to be executed, otherwise, simple code_line4 will be executed as it is outside the inner if.

Try Yourself

Write a program to call appropriate fuction for applying to either Top Level Company or Middle Level Company or Low Level Company, depending on the value of grade point average(GPA) achieved.

If GPA is greater than equal to 3.5 call function applyToTopLevelCompany( ).

If GPA is greater than 3.0 call function applyToMediumLevelCompany( ) otherwise call applyToLowLevelCompany( ) .

Solution

				
					if gpa >= 3.5:
	applyToTopLevelCompany()
else:
	if gpa > 3.0:
		applyToMediumLevelCompany()
	else:
		applyToLowLevelCompany()

#Note: The else clause contains a nested if/else.
				
			

Problem(The Else Statement)

Write a function to generate the absolute value of a number passed by the user.

Solution

				
					# Function to generate the absolute value of a number
def absoluteValue(valueIn):
   if valueIn >= 0 :
      valueOut = valueIn
   else: #must be negative, multiply by minus one to get a positive value
      valueOut = -1 * valueIn
   return valueOut
				
			
				
					num = int(input("Enter a number: "))
result = absoluteValue(num)
print('The absolute value of',num,'is',result)
				
			
				
					Enter a number: 10.5
The absolute value of 10.5 is 10.5
				
			
				
					Enter a number: -9
The absolute value of -9 is 9
				
			

Problem(The Else Statement)

Write a function to create a header statement like “Dear Mr. Jolly” based on the gender and firstName passed by the user.

Solution

				
					
def salutation(gender,firstName):
	if gender=='m':
		title="Mr."
	else:
		title="Mrs."
	header ='Dear'+' '+title+' '+firstName
	return header

print(salutation('m','Jolly'))
				
			

Problem(The Else Statement)

A shop will give discount of 10% if the cost of purchased quantity is more than 1000.

Ask user for quantity

Suppose, one unit will cost 100.

Judge and print total cost for user.

Solution

				
					print ("Enter quantity")
quantity = int(input())

if quantity*100 > 1000:
  print ("Cost is",((quantity*100)-(.1*quantity*100)))
else:
  print ("Cost is",quantity*100)
				
			

Problem(The Else Statement)

A student will not be allowed to sit in exam if his/her attendence is less than 75%.

Take following input from user

Number of classes held

Number of classes attended.

And print

percentage of classes attended

Is student allowed to sit in exam or not.

Solution

				
					print ("Number of classes held")
noh = int(input())
print ("Number of classes attended")
noa = int(input())
atten = round((noa/float(noh))*100,2)
print ("Attendence is",atten)
if atten >= 75:
  print ("You are allowed to sit in exam")
else:
  print ("Sorry, you are not allowed. Attend more classes from next time.")
				
			

Problem(Using many elif statements)

Write a program to accept two numbers and mathematical operators and perform operation accordingly.

Operators allowed(+,-,*,/)

First line will take first number as input

Second line will take second number as input

Third line will take Operator as input

Solution

				
					m = int(input("Enter first number: "))
n = int(input("Enter second number: "))
a = input("Enter the operator: ")
if(a == "+"):
    print(m + n)
elif(a == "-"):
    print(m - n)
elif(a == "*"):
    print(m * n)
else:
    print(m / n)
				
			

Problem(Logical And Operator)

Suppose you are in Delhi and you have to pay your electricity bill. Write a program to calculate the electricity bill (accept the number of units from user) according to the following criteria:

Units                    Price

First 100 units     No charge

Next 100 units     Rs 5 per unit

After 200 units     Rs 10 per unit

Solution

				
					amount = 0
num = int(input("Enter number of electric unit "))
if num <= 100:
    amount = 0
if num > 100 and num <= 200:
    amount = (num - 100) * 5
if num > 200:
    amount = 500 + (num - 200) * 10
print("Amount to pay :", amount)

				
			

Problem(The Logical and operator)

Take input of age of 3 people by user and determine oldest and youngest among them.

Solution

				
					print ("Enter first age")
first = input()
print ("Enter second age")
second = input()
print ("third age")
third = input()

if first >= second and first >= third:
  print ("Oldest is",first)
elif second >= first and second >= third:
  print ("Oldest is",second)
elif third >= first and third >= second:
  print ("Oldest is",third)
else:
  print ("All are equal")
				
			

Problem(The logical and operator)

Ask user to enter age and sex ( M or F ), and then using following rules print their place of service.

if employee is female, then she will work only in urban areas.

if employee is a male and age is in between 20 to 40 then he may work in anywhere

if employee is male and age is in between 40 to 60 then he will work in urban areas only.

And any other input of age should print “ERROR”.

Solution

				
					print ("Enter age")
age = int(input())
print ("SEX? (M or F)")
sex = input()

if sex == "F" and (age>=20 and age<=60):
  print ("Urban areas only")
elif sex == "M" and (age>=20 and age<=40):
  print ("You can work anywhere")
elif sex == "M" and (age>40 and age<=60):
  print ("Urban areas only")
else:
  print ("ERROR")
				
			

Problem(The logical and operator)

Take three numbers as input from the user and find the greatest number out of three entered numbers.

Solution

				
					age1 = int(input("Enter age of first person: "))
age2 = int(input("Enter age of second person: "))
age3 = int(input("Enter age of third person: "))
age4 = int(input("Enter age of fourth person: "))
if age1 > age2 and age1 > age3 and age1 > age4:
    print("Age of oldest person is ", age1)
elif age2 > age1 and age2 > age3 and age2 > age4:
    print("Age of oldest person is ", age2)
elif age3 > age2 and age3 > age1 and age3 > age4:
    print("Age of oldest person is ", age3)
elif age4 > age1 and age4 > age2 and age4 > age3:
    print("Age of oldest person is ", age4)
				
			

Problem(The Logical And operator)

Write a program to check whether an integer entered by user is positive even, positive odd, negative even, negative odd or zero.

Solution

				
					num = int(input("Enter a number: "))
if num == 0:
    print("Zero")
elif num % 2 == 0 and num > 0:
    print("Positive Even number")
elif num % 2 == 0 and num < 0:
    print("Negative Even number")
elif num % 2 != 0 and num > 0:
    print("Positive Odd number")
elif num % 2 != 0 and num < 0:
    print("Negative Odd number")
				
			

Problem(The Logical and operator)

Take input of the age of four people and display the age of the oldest person.

Solution

				
					age1 = int(input("Enter age of first person"))
age2 = int(input("Enter age of second person"))
age3 = int(input("Enter age of third person"))
age4 = int(input("Enter age of fourth person"))
if age1 > age2 and age1 > age3 and age1 > age4:
    print("Age of oldest person is ", age1)
elif age2 > age1 and age2 > age3 and age2 > age4:
    print("Age of oldest person is ", age2)
elif age3 > age2 and age3 > age1 and age3 > age4:
    print("Age of oldest person is ", age3)
elif age4 > age1 and age4 > age2 and age4 > age3:
    print("Age of oldest person is ", age4)
				
			

Problem(The Logical and operator)

Take input of the number of days the user spends at a library and calculate the charge for library according to following criteria:

Till 5 days : Rs 2/day.

6 to 10 days : Rs 3/day.

11 to 15 days : Rs 4/day

After 15 days : Rs 5/day

Solution

				
					days = int(input("Enter number of days: "))
 
if days <= 5:
    amount = days * 2
    
elif days >= 6 and days <= 10:
    amount = days * 3
 
elif days >= 11 and days <= 15:
    amount = days * 4
 
else:
    amount = days * 5
 
print("Total amount to pay is ", amount)
				
			

Problem(The Logical and operator)

Write a program to take the three sides of a triangle as input and check whether the triangle is valid or not.

A triangle is valid if sum of any two sides of the triangle is greater than or equal to the third side.

Solution

				
					s1 = int(input("Enter first side of triangle: "))
s2 = int(input("Enter second side of triangle: "))
s3 = int(input("Enter third side of triangle: "))
 
if s1 + s2 > s3 and s2 + s3 > s1 and s1 + s3 > s2:
    print("Triangle is possible")
else:
    print("Triangle is not possible")
				
			

Problem(the logical or operator)

Take input of three sides of a triangle and check whether it is an equilateral, isosceles or scalene triangle.

An equilateral triangle is a triangle in which all three sides are equal.

A scalene triangle is a triangle in which all three sides are unequal.

An isosceles triangle is a triangle with (at least) two equal sides.

Solution

				
					s1 = int(input("Enter first side of triangle: "))
s2 = int(input("Enter second side of triangle: "))
s3 = int(input("Enter third side of triangle: "))
if s1 == s2 and s2 == s3:
    print("Equilateral triangle")
if (s1 == s2 and s2 != s3) or (s2 == s3 and s2 != s1) or (s1 == s3 and s1 != s2):
    print("Isosceles Triangle")
if s1 != s2 and s1 != s3 and s2 != s3:
    print("Scalene Triangle")
				
			

Problem(Nesting)

Write a program to check if the number entered by the user is Even and Greater than 10.

Solution

				
					num = int(input("Enter number: "))

if num > 10:
    print("Number is greater than 10")
    if num % 2 == 0:  # num is even and greater than 10
        print("Number is even")  # Inside both if
    else:  # num is odd and greater than 10
        print("Number is odd")  # Inside both if
else:
    print("Number is not greater than 10")
    if num % 2 == 0:  # num is even and not greater than 10
        print("Number is even")  # Inside if and outer else
    else:  # num is odd and not greater than 10
        print("Number is odd")  # Inside if and outer else

				
			

Problem(Nesting)

Write a program to take three integer inputs from the user and print the largest integer using nesting.

Solution

				
					a = int(input("Enter first Number: "))
b = int(input("Enter second Number: "))
c = int(input("Enter third Number: "))
if(a > b):
    if(a > c):
        print("Maximum =", a)
    else:
        print("Maximum =", c)
else:
    if(b > c):
        print("Maximum =", b)
    else:
        print("Maximum =", c)
				
			

Problem(Nesting)

Write a program to allow student to sit in exam if he/she has medical cause. Otherwise, a student shall be allowed to sit in exam only if he/she has a minimum attendance of 75.

Solution

				
					# use earlier written code here
if medical_cause == 'Y':
  print("You are allowed")
else:
  if atten>=75:
    print("Allowed")
  else:
    print("Not allowed")
				
			

Problem(Nesting)

Write a program to check whether the year entered by user is a leap year or not.

Solution

				
					year = int(input("Enter the year: "))
if(year % 4 == 0):
    if(year % 100 == 0):
        if(year % 400 == 0):
            print("Leap Year")
        else:
            print("Not Leap Year")
    else:
        print("Leap Year")
        
else:
    print("Not Leap Year")
				
			
flowchart.js · Playground

Flowchart

flowchart.js · Playground

Flowchart



            
0% Complete
Scroll to Top