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.
if statement
if - else statement
elif statement
while loop
for loop
break
continue
if (condition):
code block
# 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 ?
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(condition):
code block if condition is satisfied
else:
code block if condition is not satisifed
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 condition is checked only if all of the previous conditions are evaluated to be False.elif is followed by elif or else if.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
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 (condition):
code block
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 statement is used to exit a while loopbreak is used along with a condition to exit from an iterative blocknum = 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!
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 num in range(1,30,3):
print(num, end=' ')
1 4 7 10 13 16 19 22 25 28
name = "VIT Chennai"
for char in name :
print(char.upper(), end = '')
VIT CHENNAI
dir(str)
['__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']
dir(int)
['__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']
x=10
dir(x)
['__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']
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.