Introduction to Python
Python – a mysterious name Python is a widely used general-purpose, high level programming language. It was initially designed by Dutch programmer Guido van Rossum in 1991. The name Python comes from an old BBC television comedy sketch series called Monty Python’s Flying Circus. When Guido van Rossum was creating Python, he was also reading the scripts of Monty Python. He thought the name Python was appropriately short and slightly mysterious.
Why should we learn Python?  Python is a higher level programming language.  Its syntax allows programmers to express concepts in fewer lines of code.  Python is a programming language that lets you work quickly and integrate systems more efficiently.  One can plot figures using Python.  One can perform symbolic mathematics easily using Python.  It is available freely online.
Python versions Python was first released on February 20, 1991 and later on developed by Python Software Foundation. Major Python versions are – Python 1, Python 2 and Python 3. • On 26th January 1994, Python 1.0 was released. • On 16th October 2000, Python 2.0 was released with many new features. • On 3rd December 2008, Python 3.0 was released with more testing and includes new features. Latest version - On 2nd October 2023, Python 3.12 was released. To check your Python version i) For Linux OS type python -V in the terminal window. ii) For Windows and MacOS type import sys print(sys.version) in the interactive shell.
Searching for Python
Downloading Python
Python Interpreter The program that translates Python instructions and then executes them is the Python interpreter. When we write a Python program, the program is executed by the Python interpreter. This interpreter is written in the C language. There are certain online interpreters like https://ide.geeksforgeeks.org/, http://ideone.com/ , http://codepad.org/ that can be used to start Python without installing an interpreter.
Python IDLE Python interpreter is embedded in a number of larger programs that make it particularly easy to develop Python programs. Such a programming environment is IDLE ( Integrated Development and Learning Environment). It is available freely online. For Windows machine IDLE (Integrated Development and Learning Environment) is installed when you install Python.
Running Python There are two modes for using the Python interpreter: 1) Interactive Mode 2) Script Mode Options for running the program: • In Windows, you can display your folder contents, and double click on madlib.py to start the program. • In Linux or on a Mac you can open a terminal window, change into your python directory, and enter the command python madlib.py
Interactive shell
IDLE shell
Running Python 1) in interactive mode: >>> print("Hello Teachers") Hello Teachers >>> a=10 >>> print(a) 10 >>> x=10 >>> z=x+20 >>> z 30
Running Python 2) in script mode: Programmers can store Python script source code in a file with the .py extension, and use the interpreter to execute the contents of the file. For UNIX OS to run a script file MyFile.py you have to type: python MyFile.py
Data Types Python has various standard data types:  Integer [ class ‘int’ ]  Float [ class ‘float’ ]  Boolean [ class ‘bool’ ]  String [ class ‘str’ ]
Integer Int: For integer or whole number, positive or negative, without decimals of unlimited length. >>> print(2465635468765) 2465635468765 >>> print(0b10) # 0b indicates binary number 2 >>> print(0x10) # 0x indicates hexadecimal number 16 >>> a=11 >>> print(type(a)) <class 'int'>
Float Float: Float, or "floating point number" is a number, positive or negative. Float can also be scientific numbers with an "e" to indicate the power of 10. >>> y=2.8 >>> y 2.8 >>> print(0.00000045) 4.5e-07 >>> y=2.8 >>> print(type(y)) <class 'float'>
Boolean and String Boolean: Objects of Boolean type may have one of two values, True or False: >>> type(True) <class 'bool'> >>> type(False) <class 'bool'> String: >>> print(‘Science college’) Science college >>> type("My college") <class 'str'>
Variables One can store integers, decimals or characters in variables. Rules for Python variables: • A variable name must start with a letter or the underscore character • A variable name cannot start with a number • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ) • Variable names are case-sensitive (age, Age and AGE are three different variables) a= 100 # An integer assignment b = 1040.23 # A floating point c = "John" # A string
Working with lists,list of lists, work tuples, work with dates and times ,and get started with dictionaries
List, Tuple, Set, Dictionary Four built-in data structures in Python:- list, tuple, set, dictionary - each having qualities and usage different from the other three. List is a collection of items that is written with square brackets. It is mutable, ordered and allows duplicate members. Example: list = [1,2,3,'A','B',7,8,[10,11]] Tuple is a collection of objects that is written with first brackets. It is immutable. Example: tuple = (2, 1, 10, 4, 7) Set is a collection of elements that is written with curly brackets. It is unindexed and unordered. Example: S = {x for x in 'abracadabra' if x not in 'abc'} Dictionary is a collection which is ordered, changeable and does not allow duplicates. It is written with curly brackets and objects are stored in key: value format. Example: X = {1:’A’, 2:’B’, 3:’c’}
Python functions and Boolean expressions
print function >>>type(print) Output: builtin_function_or_method >>>print( ‘Good morning’ ) or print(“Good morning”) Output: Good morning >>>print(“Workshop”, “on”, “Python”) or print(“Workshop on Python”) Output: Workshop on Python
print function >>>print(‘Workshop’, ‘on’, ‘Python’, sep=’n’) # sep=‘n’ will put each word in a new line Output: Workshop on Python >>>print(‘Workshop’, ‘on’, ‘Python’, sep=’, ’) # sep=‘, ’ will print words separated by , Output: Workshop, on, Python
print function %d is used as a placeholder for integer value. %f is used as a placeholder for decimal value. %s is used as a placeholder for string. a = 2 b = ‘tiger’ print(a, ‘is an integer while’, b, ‘is a string.’) Output: 2 is an integer while tiger is a string. Alternative way: print(“%d is an integer while %s is a string.”%(a, b)) Output: 2 is an integer while tiger is a string.
print function # printing a string name = “Rahul” print(“Hey ” + name) Output: Hey Rahul print(“Roll No: ” + str(34)) # “Roll No: ” + 34 is incorrect Output: Roll No: 34 # printing a bool True / False print(True) Output: True
print function int_list = [1, 2, 3, 4, 5] print(int_list) # printing a list Output: [1, 2, 3, 4, 5] my_tuple = (10, 20, 30) print(my_tuple) # printing a tuple Output: (10, 20, 30) my_dict = {“language”: “Python”, “field”: “data science”} print(my_dict) # printing a dictionary Output: {“language”: “Python”, “field”: “data science”} my_set = {“red”, “yellow”, “green”, “blue”} print(my_set) #printing a set Output: {“red”, “yellow”, “green”, “blue”}
print function str1 = ‘Python code’ str2 = ‘Matlab code’ print(str1) print(str2) Output: Python code Matlab code print(str1, end=’ ‘) print(str2) Output: Python code Matlab code print(str1, end=’, ‘) print(str2) Output: Python code, Matlab code
print function items = [ 1, 2, 3, 4, 5] for item in items: print(item) Output: 1 2 3 4 5 items = [ 1, 2, 3, 4, 5] for item in items: print(item, end=’ ‘) Output: 1 2 3 4 5
Operators Addition + Subtraction - Multiplication * Exponentiation ** Division / Integer division / / Remainder % Binary left shift << Binary right shift >> And & Or | Less than < Greater than > Less than or equal to <= Greater than or equal to >= Check equality == Check not equal !=
Precedence of operators Parenthesized expression ( ….. ) Exponentiation ** Positive, negative, bitwise not +n, -n, ~n Multiplication, float division, int division, remainder *, /, //, % Addition, subtraction +, - Bitwise left, right shifts <<, >> Bitwise and & Bitwise or | Membership and equality tests in, not in, is, is not, <, <=, >, >=, !=, == Boolean (logical) not not x Boolean and and Boolean or or Conditional expression if ….. else
Precedence of Operators Examples: a = 20 b = 10 c = 15 d = 5 e = 2 f = (a + b) * c / d print( f) g = a + (b * c) / d - e print(g) h = a + b*c**e print(h)
Multiple Assignment Python allows you to assign a single value to several variables simultaneously. a = b = c = 1.5 a, b, c = 1, 2, " Red“ Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively and one string object with the value "Red" is assigned to the variable c.
Special Use of + and * Examples: x = "Python is " y = "awesome." z = x + y print(z) Output: Python is awesome. print(‘It is’ + 2*’very ’ + ’hot.’) Output: It is very very hot.
Use of ”, n, t Specifying a backslash () in front of the quote character in a string “escapes” it and causes Python to suppress its usual special meaning. It is then interpreted simply as a literal single quote character: >>> print(" ”Beauty of Flower” ") ”Beauty of Flower” >>> print('Red n Blue n Green ') Red Blue Green >>> print("a t b t c t d") a b c d
Comments Single-line comments begins with a hash ( # ) symbol and is useful in mentioning that the whole line should be considered as a comment until the end of line. A Multi line comment is useful when we need to comment on many lines. In python, triple double quote(“ “ “) and single quote(‘ ‘ ‘)are used for multi-line commenting. Example: “““ My Program to find Average of three numbers ””” a = 29 # Assigning value of a b = 17 # Assigning value of b c = 36 # Assigning value of c average = ( a + b + c)/3 print(“Average value is ”, average)
id( ) function, ord( ) function id( ) function: It is a built-in function that returns the unique identifier of an object. The identifier is an integer, which represents the memory address of the object. The id( ) function is commonly used to check if two variables or objects refer to the same memory location. >>> a=5 >>> id(a) 1403804521000552 ord( ) function: It is used to convert a single unicode character into its integer representation. >>> ord(‘A’) 65 >>> chr(65) ‘A’
Selection and iteration structure
Control Flow Structures 1. Conditional if ( if ) 2. Alternative if ( if else ) 3. Chained Conditional if ( if elif else ) 4. While loop 5. For loop
Conditional if Example: a=10 if a > 9 : print("a is greater than 9") Output: a is greater than 9
Alternative if Example: A = int(input(‘Enter the marks ')) if A >= 40: print("PASS") else: print("FAIL") Output: Enter the marks 65 PASS
# Test if the given letter is vowel or not letter = ‘o’ if letter == ‘a’ or letter == ‘e’ or letter == ‘i’ or letter == ‘o’ or letter == ‘u’ : print(letter, ‘is a vowel.’) else: print(letter, ‘is not a vowel.’) Output: o is a vowel.
# Program to find the greatest of three different numbers a = int(input('Enter 1st no’)) b = int(input('Enter 2nd no')) c= int(input('Enter 3rd no')) if a > b: if a>c: print('The greatest no is ', a) else: print('The greatest no is ', c) else: if b>c: print('The greatest no is ', b) else: print('The greatest no is ', c) Output: Enter 1st no 12 Enter 2nd no 31 Enter 3rd no 9 The greatest no is 31
Chained conditional if # Program to guess the vegetable color = “green” if color == “red”: print(‘It is a tomato.’) elif color == “purple”: print(‘It is a brinjal.') elif color == “green”: print(‘It is a papaya. ') else: print(‘There is no such vegetable.’) Output: It is a papaya.
# Program to find out the greatest of four different numbers a=int(input('Enter 1st no ‘)) b=int(input('Enter 2nd no ‘)) c=int(input('Enter 3rd no ‘)) d=int(input('Enter 4th no ‘)) if (a>b and a>c and a>d): print('The greatest no is ', a) elif (b>c and b>d): print('The greatest no is ', b) elif (c>d): print('The greatest no is ', c) elif d>c : print('The greatest no is ', d) else: print('At least two values are equal') Output: Enter 1st no 23 Enter 2nd no 10 Enter 3rd no 34 Enter 4th no 7 The greatest no is 34
# Program to find out Grade marks = int(input('Enter total marks ‘)) total = 500 # Total marks percentage=(marks/total)*100 if percentage >= 80: print('Grade O') elif percentage >=70: print('Grade A') elif percentage >=60: print('Grade B') elif percentage >=40: print('Grade C') else: print('Fail‘) Output: Enter total marks 312 Grade B
While loop # Python program to find first ten Fibonacci numbers a=1 print(a) b=1 print(b) i=3 while i<= 10: c=a+b print(c) a=b b=c i=i+1
For loop # Program to find the sum of squares of first n natural numbers n = int(input('Enter the last number ')) sum = 0 for i in range(1, n+1): sum = sum + i*i print('The sum is ', sum) Output: Enter the last number 8 The sum is 204
For loop # Program to find the sum of a given set of numbers numbers = [11, 17, 24, 65, 32, 69] sum = 0 for no in numbers: sum = sum + no print('The sum is ', sum) Output: The sum is 218
# Program to print 1, 22, 333, 444, .... in triangular form n = int(input('Enter the number of rows ')) for i in range(1, n+1): for j in range(1, i+1): print(i, end='') print() Output: Enter the number of rows 5 1 22
# Program to print opposite right triangle n = int(input('Enter the number of rows ')) for i in range(n, 0, -1): for j in range(1, i+1): print('*', end='') print() Output: ***** **** ***
# Program to print opposite star pattern n = int(input('Enter the number of rows ')) for i in range(0, n): for j in range(0, n-i): print(' ', end='') for k in range(0, i+1): print('*’, end='') print('') Output: * ** *** **** *****
# Program to print A, AB, ABC, ABCD, ...... ch = str(input('Enter a character ')) val=ord(ch) for i in range(65, val+1): for j in range(65, i+1): print(chr(j), end='') print() Output: A AB ABC
# Program to test Palindrome numbers n=int(input('Enter an integer ')) x=n r=0 while n>0: d=n%10 r=r*10+d n=n//10 if x==r: print(x,' is Palindrome number’) else: print(x, ' is not Palindrome number')
# Program to print Pascal Triangle n=int(input('Enter number of rows ')) for i in range(0, n): for j in range(0, n-i-1): print(end=' ') for j in range(0, i+1): print('*', end=' ') print() Output: Enter number of rows 6 * * * * * * * * * * * * * * * * * * * * *
Break and Continue In Python, break and continue statements can alter the flow of a normal loop. # Searching for a given number numbers = [11, 9, 88, 10, 90, 3, 19] for num in numbers: if(num==88): print("The number 88 is found") break Output: The number 88 is found
Break and Continue # program to display only odd numbers for num in [20, 11, 9, 66, 4, 89, 44]: # Skipping the iteration when number is even if num%2 == 0: continue # This statement will be skipped for all even numbers else: print(num)
References [1] Kenneth A Lambert, Fundamentals of Python: First programs, 2nd edition – Cengage Learning India, 2019. [2] Saha Amit, Doing Math with Python - No starch press, San Francisco, 2015. [3] E. Balgurusamy, Problem solving and Python programming- Tata McGraw Hill, 2017. [4] Bill Lubanovic, Introducing Python, Shroff Publishers & Distributors Pvt. Ltd., 2nd Edition, 2020.
Thank You

Chapter1 python introduction syntax general

  • 1.
  • 2.
    Python – amysterious name Python is a widely used general-purpose, high level programming language. It was initially designed by Dutch programmer Guido van Rossum in 1991. The name Python comes from an old BBC television comedy sketch series called Monty Python’s Flying Circus. When Guido van Rossum was creating Python, he was also reading the scripts of Monty Python. He thought the name Python was appropriately short and slightly mysterious.
  • 3.
    Why should welearn Python?  Python is a higher level programming language.  Its syntax allows programmers to express concepts in fewer lines of code.  Python is a programming language that lets you work quickly and integrate systems more efficiently.  One can plot figures using Python.  One can perform symbolic mathematics easily using Python.  It is available freely online.
  • 4.
    Python versions Python wasfirst released on February 20, 1991 and later on developed by Python Software Foundation. Major Python versions are – Python 1, Python 2 and Python 3. • On 26th January 1994, Python 1.0 was released. • On 16th October 2000, Python 2.0 was released with many new features. • On 3rd December 2008, Python 3.0 was released with more testing and includes new features. Latest version - On 2nd October 2023, Python 3.12 was released. To check your Python version i) For Linux OS type python -V in the terminal window. ii) For Windows and MacOS type import sys print(sys.version) in the interactive shell.
  • 5.
  • 6.
  • 7.
    Python Interpreter The programthat translates Python instructions and then executes them is the Python interpreter. When we write a Python program, the program is executed by the Python interpreter. This interpreter is written in the C language. There are certain online interpreters like https://ide.geeksforgeeks.org/, http://ideone.com/ , http://codepad.org/ that can be used to start Python without installing an interpreter.
  • 8.
    Python IDLE Python interpreteris embedded in a number of larger programs that make it particularly easy to develop Python programs. Such a programming environment is IDLE ( Integrated Development and Learning Environment). It is available freely online. For Windows machine IDLE (Integrated Development and Learning Environment) is installed when you install Python.
  • 9.
    Running Python There aretwo modes for using the Python interpreter: 1) Interactive Mode 2) Script Mode Options for running the program: • In Windows, you can display your folder contents, and double click on madlib.py to start the program. • In Linux or on a Mac you can open a terminal window, change into your python directory, and enter the command python madlib.py
  • 10.
  • 11.
  • 12.
    Running Python 1) ininteractive mode: >>> print("Hello Teachers") Hello Teachers >>> a=10 >>> print(a) 10 >>> x=10 >>> z=x+20 >>> z 30
  • 13.
    Running Python 2) inscript mode: Programmers can store Python script source code in a file with the .py extension, and use the interpreter to execute the contents of the file. For UNIX OS to run a script file MyFile.py you have to type: python MyFile.py
  • 14.
    Data Types Python hasvarious standard data types:  Integer [ class ‘int’ ]  Float [ class ‘float’ ]  Boolean [ class ‘bool’ ]  String [ class ‘str’ ]
  • 15.
    Integer Int: For integer orwhole number, positive or negative, without decimals of unlimited length. >>> print(2465635468765) 2465635468765 >>> print(0b10) # 0b indicates binary number 2 >>> print(0x10) # 0x indicates hexadecimal number 16 >>> a=11 >>> print(type(a)) <class 'int'>
  • 16.
    Float Float: Float, or "floatingpoint number" is a number, positive or negative. Float can also be scientific numbers with an "e" to indicate the power of 10. >>> y=2.8 >>> y 2.8 >>> print(0.00000045) 4.5e-07 >>> y=2.8 >>> print(type(y)) <class 'float'>
  • 17.
    Boolean and String Boolean: Objectsof Boolean type may have one of two values, True or False: >>> type(True) <class 'bool'> >>> type(False) <class 'bool'> String: >>> print(‘Science college’) Science college >>> type("My college") <class 'str'>
  • 18.
    Variables One can storeintegers, decimals or characters in variables. Rules for Python variables: • A variable name must start with a letter or the underscore character • A variable name cannot start with a number • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ) • Variable names are case-sensitive (age, Age and AGE are three different variables) a= 100 # An integer assignment b = 1040.23 # A floating point c = "John" # A string
  • 19.
    Working with lists,listof lists, work tuples, work with dates and times ,and get started with dictionaries
  • 20.
    List, Tuple, Set,Dictionary Four built-in data structures in Python:- list, tuple, set, dictionary - each having qualities and usage different from the other three. List is a collection of items that is written with square brackets. It is mutable, ordered and allows duplicate members. Example: list = [1,2,3,'A','B',7,8,[10,11]] Tuple is a collection of objects that is written with first brackets. It is immutable. Example: tuple = (2, 1, 10, 4, 7) Set is a collection of elements that is written with curly brackets. It is unindexed and unordered. Example: S = {x for x in 'abracadabra' if x not in 'abc'} Dictionary is a collection which is ordered, changeable and does not allow duplicates. It is written with curly brackets and objects are stored in key: value format. Example: X = {1:’A’, 2:’B’, 3:’c’}
  • 21.
    Python functions andBoolean expressions
  • 22.
    print function >>>type(print) Output: builtin_function_or_method >>>print( ‘Goodmorning’ ) or print(“Good morning”) Output: Good morning >>>print(“Workshop”, “on”, “Python”) or print(“Workshop on Python”) Output: Workshop on Python
  • 23.
    print function >>>print(‘Workshop’, ‘on’,‘Python’, sep=’n’) # sep=‘n’ will put each word in a new line Output: Workshop on Python >>>print(‘Workshop’, ‘on’, ‘Python’, sep=’, ’) # sep=‘, ’ will print words separated by , Output: Workshop, on, Python
  • 24.
    print function %d isused as a placeholder for integer value. %f is used as a placeholder for decimal value. %s is used as a placeholder for string. a = 2 b = ‘tiger’ print(a, ‘is an integer while’, b, ‘is a string.’) Output: 2 is an integer while tiger is a string. Alternative way: print(“%d is an integer while %s is a string.”%(a, b)) Output: 2 is an integer while tiger is a string.
  • 25.
    print function # printinga string name = “Rahul” print(“Hey ” + name) Output: Hey Rahul print(“Roll No: ” + str(34)) # “Roll No: ” + 34 is incorrect Output: Roll No: 34 # printing a bool True / False print(True) Output: True
  • 26.
    print function int_list =[1, 2, 3, 4, 5] print(int_list) # printing a list Output: [1, 2, 3, 4, 5] my_tuple = (10, 20, 30) print(my_tuple) # printing a tuple Output: (10, 20, 30) my_dict = {“language”: “Python”, “field”: “data science”} print(my_dict) # printing a dictionary Output: {“language”: “Python”, “field”: “data science”} my_set = {“red”, “yellow”, “green”, “blue”} print(my_set) #printing a set Output: {“red”, “yellow”, “green”, “blue”}
  • 27.
    print function str1 =‘Python code’ str2 = ‘Matlab code’ print(str1) print(str2) Output: Python code Matlab code print(str1, end=’ ‘) print(str2) Output: Python code Matlab code print(str1, end=’, ‘) print(str2) Output: Python code, Matlab code
  • 28.
    print function items =[ 1, 2, 3, 4, 5] for item in items: print(item) Output: 1 2 3 4 5 items = [ 1, 2, 3, 4, 5] for item in items: print(item, end=’ ‘) Output: 1 2 3 4 5
  • 29.
    Operators Addition + Subtraction- Multiplication * Exponentiation ** Division / Integer division / / Remainder % Binary left shift << Binary right shift >> And & Or | Less than < Greater than > Less than or equal to <= Greater than or equal to >= Check equality == Check not equal !=
  • 30.
    Precedence of operators Parenthesizedexpression ( ….. ) Exponentiation ** Positive, negative, bitwise not +n, -n, ~n Multiplication, float division, int division, remainder *, /, //, % Addition, subtraction +, - Bitwise left, right shifts <<, >> Bitwise and & Bitwise or | Membership and equality tests in, not in, is, is not, <, <=, >, >=, !=, == Boolean (logical) not not x Boolean and and Boolean or or Conditional expression if ….. else
  • 31.
    Precedence of Operators Examples: a= 20 b = 10 c = 15 d = 5 e = 2 f = (a + b) * c / d print( f) g = a + (b * c) / d - e print(g) h = a + b*c**e print(h)
  • 32.
    Multiple Assignment Python allowsyou to assign a single value to several variables simultaneously. a = b = c = 1.5 a, b, c = 1, 2, " Red“ Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively and one string object with the value "Red" is assigned to the variable c.
  • 33.
    Special Use of+ and * Examples: x = "Python is " y = "awesome." z = x + y print(z) Output: Python is awesome. print(‘It is’ + 2*’very ’ + ’hot.’) Output: It is very very hot.
  • 34.
    Use of ”,n, t Specifying a backslash () in front of the quote character in a string “escapes” it and causes Python to suppress its usual special meaning. It is then interpreted simply as a literal single quote character: >>> print(" ”Beauty of Flower” ") ”Beauty of Flower” >>> print('Red n Blue n Green ') Red Blue Green >>> print("a t b t c t d") a b c d
  • 35.
    Comments Single-line comments beginswith a hash ( # ) symbol and is useful in mentioning that the whole line should be considered as a comment until the end of line. A Multi line comment is useful when we need to comment on many lines. In python, triple double quote(“ “ “) and single quote(‘ ‘ ‘)are used for multi-line commenting. Example: “““ My Program to find Average of three numbers ””” a = 29 # Assigning value of a b = 17 # Assigning value of b c = 36 # Assigning value of c average = ( a + b + c)/3 print(“Average value is ”, average)
  • 36.
    id( ) function,ord( ) function id( ) function: It is a built-in function that returns the unique identifier of an object. The identifier is an integer, which represents the memory address of the object. The id( ) function is commonly used to check if two variables or objects refer to the same memory location. >>> a=5 >>> id(a) 1403804521000552 ord( ) function: It is used to convert a single unicode character into its integer representation. >>> ord(‘A’) 65 >>> chr(65) ‘A’
  • 37.
  • 38.
    Control Flow Structures 1.Conditional if ( if ) 2. Alternative if ( if else ) 3. Chained Conditional if ( if elif else ) 4. While loop 5. For loop
  • 39.
    Conditional if Example: a=10 if a> 9 : print("a is greater than 9") Output: a is greater than 9
  • 40.
    Alternative if Example: A =int(input(‘Enter the marks ')) if A >= 40: print("PASS") else: print("FAIL") Output: Enter the marks 65 PASS
  • 41.
    # Test ifthe given letter is vowel or not letter = ‘o’ if letter == ‘a’ or letter == ‘e’ or letter == ‘i’ or letter == ‘o’ or letter == ‘u’ : print(letter, ‘is a vowel.’) else: print(letter, ‘is not a vowel.’) Output: o is a vowel.
  • 42.
    # Program tofind the greatest of three different numbers a = int(input('Enter 1st no’)) b = int(input('Enter 2nd no')) c= int(input('Enter 3rd no')) if a > b: if a>c: print('The greatest no is ', a) else: print('The greatest no is ', c) else: if b>c: print('The greatest no is ', b) else: print('The greatest no is ', c) Output: Enter 1st no 12 Enter 2nd no 31 Enter 3rd no 9 The greatest no is 31
  • 43.
    Chained conditional if #Program to guess the vegetable color = “green” if color == “red”: print(‘It is a tomato.’) elif color == “purple”: print(‘It is a brinjal.') elif color == “green”: print(‘It is a papaya. ') else: print(‘There is no such vegetable.’) Output: It is a papaya.
  • 44.
    # Program tofind out the greatest of four different numbers a=int(input('Enter 1st no ‘)) b=int(input('Enter 2nd no ‘)) c=int(input('Enter 3rd no ‘)) d=int(input('Enter 4th no ‘)) if (a>b and a>c and a>d): print('The greatest no is ', a) elif (b>c and b>d): print('The greatest no is ', b) elif (c>d): print('The greatest no is ', c) elif d>c : print('The greatest no is ', d) else: print('At least two values are equal') Output: Enter 1st no 23 Enter 2nd no 10 Enter 3rd no 34 Enter 4th no 7 The greatest no is 34
  • 45.
    # Program tofind out Grade marks = int(input('Enter total marks ‘)) total = 500 # Total marks percentage=(marks/total)*100 if percentage >= 80: print('Grade O') elif percentage >=70: print('Grade A') elif percentage >=60: print('Grade B') elif percentage >=40: print('Grade C') else: print('Fail‘) Output: Enter total marks 312 Grade B
  • 46.
    While loop # Pythonprogram to find first ten Fibonacci numbers a=1 print(a) b=1 print(b) i=3 while i<= 10: c=a+b print(c) a=b b=c i=i+1
  • 47.
    For loop # Programto find the sum of squares of first n natural numbers n = int(input('Enter the last number ')) sum = 0 for i in range(1, n+1): sum = sum + i*i print('The sum is ', sum) Output: Enter the last number 8 The sum is 204
  • 48.
    For loop # Programto find the sum of a given set of numbers numbers = [11, 17, 24, 65, 32, 69] sum = 0 for no in numbers: sum = sum + no print('The sum is ', sum) Output: The sum is 218
  • 49.
    # Program toprint 1, 22, 333, 444, .... in triangular form n = int(input('Enter the number of rows ')) for i in range(1, n+1): for j in range(1, i+1): print(i, end='') print() Output: Enter the number of rows 5 1 22
  • 50.
    # Program toprint opposite right triangle n = int(input('Enter the number of rows ')) for i in range(n, 0, -1): for j in range(1, i+1): print('*', end='') print() Output: ***** **** ***
  • 51.
    # Program toprint opposite star pattern n = int(input('Enter the number of rows ')) for i in range(0, n): for j in range(0, n-i): print(' ', end='') for k in range(0, i+1): print('*’, end='') print('') Output: * ** *** **** *****
  • 52.
    # Program toprint A, AB, ABC, ABCD, ...... ch = str(input('Enter a character ')) val=ord(ch) for i in range(65, val+1): for j in range(65, i+1): print(chr(j), end='') print() Output: A AB ABC
  • 53.
    # Program totest Palindrome numbers n=int(input('Enter an integer ')) x=n r=0 while n>0: d=n%10 r=r*10+d n=n//10 if x==r: print(x,' is Palindrome number’) else: print(x, ' is not Palindrome number')
  • 54.
    # Program toprint Pascal Triangle n=int(input('Enter number of rows ')) for i in range(0, n): for j in range(0, n-i-1): print(end=' ') for j in range(0, i+1): print('*', end=' ') print() Output: Enter number of rows 6 * * * * * * * * * * * * * * * * * * * * *
  • 55.
    Break and Continue InPython, break and continue statements can alter the flow of a normal loop. # Searching for a given number numbers = [11, 9, 88, 10, 90, 3, 19] for num in numbers: if(num==88): print("The number 88 is found") break Output: The number 88 is found
  • 56.
    Break and Continue #program to display only odd numbers for num in [20, 11, 9, 66, 4, 89, 44]: # Skipping the iteration when number is even if num%2 == 0: continue # This statement will be skipped for all even numbers else: print(num)
  • 57.
    References [1] Kenneth ALambert, Fundamentals of Python: First programs, 2nd edition – Cengage Learning India, 2019. [2] Saha Amit, Doing Math with Python - No starch press, San Francisco, 2015. [3] E. Balgurusamy, Problem solving and Python programming- Tata McGraw Hill, 2017. [4] Bill Lubanovic, Introducing Python, Shroff Publishers & Distributors Pvt. Ltd., 2nd Edition, 2020.
  • 58.