Programming for Data Science¶

Flow Control¶

Dr. Bhargavi R

SCOPE, VIT Chennai

Flow Control¶

Okay! Now that we have learned the basics and written a simple python code which can execute sequentially, let's move on to learn how to bring some flexibility to the program execution.

Conditional Control¶

if statement
if - else statement
elif statement

Iterative Control¶

while loop
for loop
break
continue

if - Statement¶

  • if block is executed if the conditional expression evaluates to be True
  • if block is skipped if the conditional expression evaluates to be False

Syntax¶

if (condition):
    code block
In [1]:
# let's now see an example for if  statement
# This code checks if the name of a person has the letter 'a' 

name           = "Bhargavi"
char_to_search = 'a'

if (char_to_search in name):
    print(name, "contains the character -", char_to_search)

print("Any thing else ?")
Bhargavi contains the character - a
Any thing else ?
In [2]:
name           = "Bhargavi"
char_to_search = 'H'

if (char_to_search in name):
    print(name, "contains the character", char_to_search)
    
print("Any thing else ?")
Any thing else ?

if - else Statement¶

  • if block is executed if the condition expression evaluates to be True
  • else block is executed if the condition expression evaluates to be False

Syntax¶

if(condition):
    code block if condition is satisfied
else:
    code block if condition is not satisifed
In [3]:
print("Enter the marks ")
marks = input()
marks = int(marks)

if (marks >= 0 and marks <= 50):
    percentage = (marks/50) *  100
    print("Percentage  = ", percentage)
else: 
    print("Invalid marks")
print("We are done")
Enter the marks 
67
Invalid marks
We are done

elif Statement¶

  • An elif condition is checked only if all of the previous conditions are evaluated to be False.
  • Useful when one of many possible clauses needs to be executed.
  • elif is followed by elif or else if.
  • Yes, elif == else if !

Syntax¶

if (condition 1):
    code block if condition 1 is satisfied
elif (condition 2): 
    code block if condition 2 is satisfied
elif (condition 3): 
    code block if condition 3 is satisfied
In [4]:
marks = int(input("Enter the marks "))

if ((marks > 0) and (marks < 50)):
    percentage = (marks/50) *  100
    print("Percentage  = ", percentage)
elif (marks == 50 ) :
    print("You score 100%. Congrats!")
elif (marks == 0):
    print("You scored a perfect circle. Next time beter luck!")
else:
    print("Invalid marks")
Enter the marks -12
Invalid marks

while statement¶

  • while is an iterative control construct
  • while block is executed as long as the condition is satisfied

Syntax¶

while (condition): 
    code block
In [6]:
score = total = count = 0

print("Enter a negative score to Exit.")
while (score >= 0):
    score = int(input("Enter the score of a student "))
    if(score >= 0):
        total += score
        count += 1

average = total / count

print("The average of {} students is {}".format(count, (total/count)))
Enter a negative score to Exit.
Enter the score of a student 78
Enter the score of a student 43
Enter the score of a student 56
Enter the score of a student -12
The average of 3 students is 59.0

break and continue statements¶

  • break statement is used to exit a while loop
  • break is used along with a condition to exit from an iterative block
In [7]:
num = 1

while (True):
    if ((num % 2) == 0):
        print("{} is even. ".format(num), end='\t')
    if(num == 20):
        break
    num += 1
    
print("\nWell done!")
2 is even. 	4 is even. 	6 is even. 	8 is even. 	10 is even. 	12 is even. 	14 is even. 	16 is even. 	18 is even. 	20 is even. 	
Well done!
In [8]:
while (True):
    user_id = input("Enter your User ID ") 
    if (user_id != "Bhargavi"):
        print("Incorrect User ID!")
        continue
    
    password = input("Hi Bhargavi ! Enter your password ")
    if (password == '111'):
        print("Welcome")
        break
        
    print("Wrong Password. Try again!")
Enter your User ID 
Incorrect User ID!
Enter your User ID 
Incorrect User ID!
Enter your User ID 111
Incorrect User ID!
Enter your User ID '111'
Incorrect User ID!
Enter your User ID Bhargavi
Hi Bhargavi ! Enter your password 111
Welcome

for - statement¶

In [9]:
for num in range(1,30,3):
    print(num, end=' ')
1 4 7 10 13 16 19 22 25 28 
In [10]:
name = "VIT Chennai"
for char in name :
    print(char.upper(), end = '')
VIT CHENNAI
In [11]:
dir(str)
Out[11]:
['__add__',
 '__class__',
 '__contains__',
 '__delattr__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__getnewargs__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__iter__',
 '__le__',
 '__len__',
 '__lt__',
 '__mod__',
 '__mul__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__rmod__',
 '__rmul__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 'capitalize',
 'casefold',
 'center',
 'count',
 'encode',
 'endswith',
 'expandtabs',
 'find',
 'format',
 'format_map',
 'index',
 'isalnum',
 'isalpha',
 'isascii',
 'isdecimal',
 'isdigit',
 'isidentifier',
 'islower',
 'isnumeric',
 'isprintable',
 'isspace',
 'istitle',
 'isupper',
 'join',
 'ljust',
 'lower',
 'lstrip',
 'maketrans',
 'partition',
 'removeprefix',
 'removesuffix',
 'replace',
 'rfind',
 'rindex',
 'rjust',
 'rpartition',
 'rsplit',
 'rstrip',
 'split',
 'splitlines',
 'startswith',
 'strip',
 'swapcase',
 'title',
 'translate',
 'upper',
 'zfill']
In [12]:
dir(int)
Out[12]:
['__abs__',
 '__add__',
 '__and__',
 '__bool__',
 '__ceil__',
 '__class__',
 '__delattr__',
 '__dir__',
 '__divmod__',
 '__doc__',
 '__eq__',
 '__float__',
 '__floor__',
 '__floordiv__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getnewargs__',
 '__gt__',
 '__hash__',
 '__index__',
 '__init__',
 '__init_subclass__',
 '__int__',
 '__invert__',
 '__le__',
 '__lshift__',
 '__lt__',
 '__mod__',
 '__mul__',
 '__ne__',
 '__neg__',
 '__new__',
 '__or__',
 '__pos__',
 '__pow__',
 '__radd__',
 '__rand__',
 '__rdivmod__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__rfloordiv__',
 '__rlshift__',
 '__rmod__',
 '__rmul__',
 '__ror__',
 '__round__',
 '__rpow__',
 '__rrshift__',
 '__rshift__',
 '__rsub__',
 '__rtruediv__',
 '__rxor__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__sub__',
 '__subclasshook__',
 '__truediv__',
 '__trunc__',
 '__xor__',
 'as_integer_ratio',
 'bit_count',
 'bit_length',
 'conjugate',
 'denominator',
 'from_bytes',
 'imag',
 'numerator',
 'real',
 'to_bytes']
In [13]:
x=10
dir(x)
Out[13]:
['__abs__',
 '__add__',
 '__and__',
 '__bool__',
 '__ceil__',
 '__class__',
 '__delattr__',
 '__dir__',
 '__divmod__',
 '__doc__',
 '__eq__',
 '__float__',
 '__floor__',
 '__floordiv__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getnewargs__',
 '__gt__',
 '__hash__',
 '__index__',
 '__init__',
 '__init_subclass__',
 '__int__',
 '__invert__',
 '__le__',
 '__lshift__',
 '__lt__',
 '__mod__',
 '__mul__',
 '__ne__',
 '__neg__',
 '__new__',
 '__or__',
 '__pos__',
 '__pow__',
 '__radd__',
 '__rand__',
 '__rdivmod__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__rfloordiv__',
 '__rlshift__',
 '__rmod__',
 '__rmul__',
 '__ror__',
 '__round__',
 '__rpow__',
 '__rrshift__',
 '__rshift__',
 '__rsub__',
 '__rtruediv__',
 '__rxor__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__sub__',
 '__subclasshook__',
 '__truediv__',
 '__trunc__',
 '__xor__',
 'as_integer_ratio',
 'bit_count',
 'bit_length',
 'conjugate',
 'denominator',
 'from_bytes',
 'imag',
 'numerator',
 'real',
 'to_bytes']
In [14]:
help(print)
Help on built-in function print in module builtins:

print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
    
    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.