Unit 1: Introduction To Python And Jupyter Notebooks
Overview Of Languages
Procedure Oriented Language:
❖ Procedural programming uses a list of instructions to tell the computer what to do step-by-
step.
❖ Procedures, also known as routines, or functions.
❖ If you want a computer to do something, you should provide step-by-step instructions to
computer, how to do it.
❖ Examples of procedural languages include FORTRAN, COBOL, C and PASCAL.
Object Oriented Language:
❖ Object Oriented programming (OOP) is a programming language that relies on the concept of
classes and objects.
❖ A Class in object-oriented programming is a blueprint or prototype that defines the variables
and the methods (functions) common to Objects of a certain kind.
❖ An object in OOPS is a specimen of a class.
❖ Example:
❖ Class: Car (Attributes: Color, Brand, Model and Methods: repaint())
❖ Object: My Car (Attributes: Color = Blue, Brand = Alto, Model = Charger
Methods: repaint())
❖ Object: My Friend’s Car (Attributes: Color = Red, Brand = Nissan, Model = Ultima
Methods:repaint())
❖ There are many object-oriented programming languages including JavaScript, C++, Java.
Machine Level Language:
❖ The machine-level language is a language that consists of a set of instructions that are in the
binary form 0 or 1 which is also known as binary language or low level language.
❖ As we know that computers can understand only machine instructions, which are in binary
digits, i.e., 0 and 1, so the instructions given to the computer can be only in binary codes.
❖ Creating a program in a machine-level language is a very difficult task as it is not easy for the
programmers to write the program in machine instructions.
❖ It is error-prone as it is not easy to understand, and its maintenance is also very high.
Interpreter:
❖ Python interpreter is software logic between code and computer hardware. It takes a python
program (like *.py file ) and run the program line by line from start to bottom.
Compiler:
❖ A compiler is a computer program which helps you transform source code written in a high-
level language into low-level machine language.
Unit 1: Introduction To Python And Jupyter Notebooks
Difference between Compiler and Interpreter:
Compiler Interpreter
Compiler takes an entire program at a time. Interpreter takes a single line of code at a time.
Compiler works fast. Interpreter works slower comparatively.
Compiler display all errors after compilation, all at the Interpreter displays errors of each line one by
same time. one.
Error Detection is easy compared to the
Error Detection is difficult compared to Interpreter.
Compiler.
Generates intermediate object code which further No intermediate object code is generated,
requires linking, hence requires more memory. hence are memory efficient.
Example: C, C++, uses a compiler. Example: PHP, Pearl, Python uses Interpreter.
Introduction to Python:
❖ Python is a general-purpose high-level programming language.
❖ Python was developed by Guido Van Rossam in 1989 while working at National Research
Institute at Netherlands.
❖ But officially Python was made available to public in 1991. The official Date of Birth for
Python is : Feb 20th 1991.
❖ Python is recommended as first programming language for beginners.
Example1: To print Hello world
❖ C:
❖ #include<stdio.h>
❖ void main()
❖ {
❖ printf("Hello world");
❖ }
❖ Python:
❖ print("Hello World")
❖ The name Python was selected from the TV Show "The Complete Monty Python's Circus",
which was broadcasted in BBC from 1969 to 1974.
❖ Guido developed Python language by taking almost all programming features from different
languages
❖ (1) Functional Programming Features from C
❖ (2) Object Oriented Programming Features from C++
❖ (3) Scripting Language Features from Perl and Shell Script
Unit 1: Introduction To Python And Jupyter Notebooks
❖ (4) Modular Programming Features from Modula-3
❖ Most of syntax in Python Derived from C and ABC languages.
Where we can use Python?
We can use everywhere. The most common important application areas are
❖ Desktop Applications
❖ Web Applications
❖ Database Applications
❖ Network Programming
❖ Developing games
❖ Data Analysis Applications
❖ Machine Learning
❖ Artificial Intelligence Applications
❖ IoT
Features of Python:
❖ Simple and easy to learn: Python is a simple programming language.
❖ When we read Python program, we can feel like reading English statements.
❖ The syntaxes are very simple and only 30+ keywords are available.
❖ When compared with other languages, we can write programs with very a smaller number of
lines. Hence more readability and simplicity.
❖ Freeware and Open Source: We can use Python software without any license and it is open
source.
❖ High Level Programming language: Python is high level programming language and hence
it is programmer friendly language.
❖ Being a programmer, we are not required to concentrate low level activities like memory
management and security etc.
❖ Platform Independent: Once we write a Python program, it can run on any platform
without rewriting once again.
❖ Internally PVM is responsible to convert into machine understandable form.
❖ Portability: Python programs are portable. ie we can migrate from one platform to another
platform very easily.
❖ Python programs will provide same results on any platform.
❖ Dynamically Typed: In Python we are not required to declare type for variables.
Unit 1: Introduction To Python And Jupyter Notebooks
❖ Whenever we are assigning the value, based on value, type will be allocated automatically.
❖ Both Procedure Oriented and Object Oriented: Python language supports both Procedure
oriented (like C, pascal etc) and object oriented (like C++, Java) features.
❖ Hence, we can get benefits of both like security and reusability etc.
❖ Interpreted: We are not required to compile Python programs explicitly.
❖ Internally Python interpreter will take care that compilation. If compilation fails interpreter
raised syntax errors.
❖ Once compilation success then PVM (Python Virtual Machine) is responsible to execute.
❖ Extensible: We can use other language programs in Python.
❖ Embedded: We can use Python programs in any other language programs. i.e. we can embed
Python programs anywhere.
❖ Extensive Library: Python has a rich inbuilt library.
❖ Being a programmer, we can use this library directly and we are not responsible to implement
the functionality.
Jupyter Notebook:
❖ A Jupyter notebook is a file that contains both programming code and text descriptions.
❖ Jupyter notebooks can also contain embedded charts, plots, images, videos, and links.
❖ Jupyter notebooks run in a web browser like Firefox or Google Chrome.
❖ A Jupyter notebook is an application that can run Python code, display plots, show equations
and contain formatted text.
Installing Jupyter Notebook:
❖ Jupyter installation requires Python 3.3 or greater, or Python 2.7.
❖ As an existing Python user, you may wish to install Jupyter using Python’s package manager,
pip.
❖ First, ensure that you have the latest pip; older versions may have trouble with some
dependencies:
❖ pip3 install --upgrade pip
❖ Then install the Jupyter Notebook using: pip3 install jupyter
Opening and Creating Jupyter Notebook:
❖ Follow the steps given below to open the Jupyter notebook:
❖ Open the juputer on Windows start menu and select --> [Jupyter]
❖ This action opens the Jupyter file browser in a web browser tab.
Unit 1: Introduction To Python And Jupyter Notebooks
❖ In the upper right select [New] --> [Python 3]
❖ A new notebook will open as a new tab in your web browser.
❖ Try typing the code below in the first cell in the notebook to the right of the In [ ]: prompt:
❖ Then click the run button in the middle of the menu at the top of the notebook.
Saving and downloading Jupyter Notebook:
❖ Jupyter notebooks can be saved using the save icon in the upper menu or by pressing [Ctrl] +
[s].
❖ Jupyter notebooks can also be saved as a copy, similar to the Save As command common in
many programs. To make a copy of a Jupyter notebook use File --> Make a Copy.
❖ Jupyter notebooks can be downloaded and saved using File --> Download As --> Notebook
(.ipynb). Selecting this menu option will download the notebook as a .ipynb file.
❖ Jupyter notebooks can be saved in other formats besides the native .ipynb format.
❖ These formats can be accessed using the [File] --> [Download As] menu.
❖ The available file download types are:
❖ Notebook (.ipynb) - The native jupyter notebook format
❖ Python (.py) - The native Python code file type.
❖ HTML (.html) - A web page
❖ Markdown (.md) - Markdown format
❖ reST (.rst) - Restructured text format
❖ LaTeX (.tex) - LaTeX Article format
❖ PDF via LaTeX (.pdf) - a pdf exported from LaTeX, requires a converter
Python - Shell:
❖ Python is an interpreter language. It means it executes the code line by line. Python provides a
Python Shell, which is used to execute a single Python command and display the result.
❖ It is also known as REPL (Read, Evaluate, Print, Loop), where it reads the command,
evaluates the command, prints the result, and loop it back to read the command again.
❖ To run the Python Shell, open the command prompt or power shell on Windows write python
and press enter. A Python Prompt comprising of three greater-than symbols >>> appears.
❖ Now, you can enter a single statement and get the result. For example, enter a simple
expression like 3 + 2 press enter and it will display the result in the next line.
❖ Execute Python Script:
Unit 1: Introduction To Python And Jupyter Notebooks
❖ As you have seen above, Python Shell executes a single statement. To execute multiple
statements, create a Python file with extension .py, and write Python scripts (multiple
statements).
❖ For example, enter the following statement in a text editor such as Notepad.
❖ print ("This is Python Script.")
❖ print ("Welcome to Python Tutorial")
❖ Save it as myPythonScript.py, navigate the command prompt to the folder where you have
saved this file and execute the python myPythonScript.py command. It will display the result.
Python - IDLE:
❖ IDLE (Integrated Development and Learning Environment) is an integrated development
environment (IDE) for Python.
❖ The Python installer for Windows contains the IDLE module by default.
❖ To start an IDLE interactive shell, search for the IDLE icon in the start menu and double click
on it.
❖ This will open IDLE, where you can write and execute the Python scripts.
❖ You can execute Python statements same as in Python Shell.
❖ To execute a Python script, create a new file by selecting File -> New File from the menu.
❖ Enter multiple statements and save the file with extension .py using File -> Save. For
example, save the following code as MyProgram.py.
❖ print (“Hello World")
❖ print ("Welcome to Python Tutorial")
❖ Press F5 to run the script in the editor window. The IDLE shell will show the output.
Python - IDEs:
❖ There are many free and commercial IDEs available for Python.
❖ Jupyter Notebook
❖ Visual Studio Code
❖ Spyder
❖ PyCharm
PyCharm- IDE:
❖ PyCharm is the most popular IDE used for Python scripting language.
❖ Follow the steps given below to install PyCharm on your system.
Unit 1: Introduction To Python And Jupyter Notebooks
❖ Download the required package from the official website of PyCharm
https://www.jetbrains.com/pycharm/download/#section=windows. Here you will observe two
versions of package for Windows: (a) Professional (b) Community
❖ The professional package involves all the advanced features and comes with free trial for few
days and the user has to buy a licensed key for activation beyond the trial period.
❖ Community package is for free and can be downloaded and installed as and when required. It
includes all the basic features needed for installation. Note that we will continue with
community package throughout this tutorial.
❖ Download the community package (executable file) onto your system and mention a
destination folder.
❖ Now, begin the installation procedure similar to any other software package.
IDENTIFIERS:
❖ A Name in Python Program is called Identifier.
❖ It can be Class Name OR Function Name OR Module Name OR Variable Name.
Rules to define Identifiers in Python:
(1) The only allowed characters in Python are:
❖ alphabet symbols (either lower case or upper case)
❖ digits (0 to 9)
❖ underscore symbol (_)
❖ By mistake if we are using any other symbol like $ then we will get syntax error.
❖ cash = 10 → Valid
❖ ca$h =20 → Invalid
(2) Identifier should not starts with digit.
❖ 123total → Invalid
❖ total123 → Valid
(3) Identifiers are case sensitive. Of course, Python language is case sensitive language.
❖ total=10
❖ TOTAL=999
❖ print(total) #10
❖ print(TOTAL) #999
(4) We cannot use reserved words as identifiers
❖ def = 10 → Invalid
(5) There is no length limit for Python identifiers. But not recommended to use too lengthy
identifiers.
(6) If Identifier is start with Underscore (_) then it indicates it is private.
(7) If identifier starts with (Two Under Score Symbols) indicating that strongly private
identifier.
(8) If the identifier starts and ends with two underscore symbols then the identifier is
language defined special name, which is also known as magic methods.
❖ Eg: add
Data Types:
❖ Python has the following data types built-in by default, in these categories:
❖ Text Type: str
❖ Numeric Types: int, float
❖ Sequence Types: list, tuple, range
❖ Boolean Type: bool
Text Type (str):
❖ str represents String data type.
❖ A String is a sequence of characters enclosed within single quotes or double quotes.
❖ s1=‘Arman’ or s1=“Arman"
❖ By using single quotes or double quotes we cannot represent multi line string literals.
❖ For this requirement we should go for triple single quotes (''') or triple double quotes
(""")
❖ s1=′′′Arman
❖ soft'''
❖ s1="""Arman
❖ soft"""
❖ We can display a string literal with the print() function:
❖ print("Hello") # Hello
❖ print('Hello’) # Hello
❖ Assigning a string to a variable is done with the variable name followed by an equal
sign and the string:
❖ a = ′′Arman′′
❖ print(a) # Arman
Numeric Type:
❖ There are three numeric types in Python:
(1) int: Int, or integer, is a whole number, positive or negative, without decimals, of
unlimited length.
❖ Example:
❖ x=1
❖ y = 35656333554887711
❖ z = -3255544
❖ print(type(x)) # <class ‘int’>
❖ print(type(y)) # <class ‘int’>
❖ print(type(z)) # <class ‘int’>
(2) float: Float, or "floating point number" is a number, positive or negative, containing one
or more decimals.
❖ Example:
❖ x = 1.20
❖ y = 1.00
❖ z = -34.58
❖ print(type(x)) <class ‘float’>
❖ print(type(y)) <class ‘float’>
❖ print(type(z)) <class ‘float’>
❖ Float can also be scientific numbers with an "e" to indicate the power of 10.
Boolean Type (bool):
Booleans represent one of two values: True or False.
❖ In programming you often need to know if an expression is True or False.
❖ You can evaluate any expression in Python, and get one of two answers, True or
False.
❖ When you compare two values, the expression is evaluated and Python returns the
Boolean answer.
❖ When you run a condition in an if statement, Python returns True or False.
❖ Almost any value is evaluated to True if it has some sort of content.
❖ Any string is True, except empty strings.
❖ Any number is True, except 0.
❖ Any list, tuple, set, and dictionary are True, except empty ones.
❖ Example:
❖ print(20 > 8) # True
❖ print(20 == 8) # False
❖ print(20 < 8) # False
❖ print(bool("abc")) # True
❖ print(bool("")) # False
Reserved Words or Keywords:
❖ In Python some words are reserved to represent some meaning or functionality. Such
types of words are called reserved words.
❖ There are 33 reserved words available in Python.
❖ True, False, None, and, or ,not,is,if, elif, else, while, for, break, continue, return, in,
yield, try, except, finally, raise, assert, import, from, as, class, def, pass, global,
nonlocal, lambda, del, with.
❖ All Reserved words in Python contain only alphabet symbols.
❖ Except the following 3 reserved words, all contain only lower case alphabet symbols.
❖ True
❖ False
❖ None
❖ Example:
❖ a= true ×
❖ a=True √
Variables:
❖ Variables are containers for storing data values.
❖ A variable name can only contain alpha-numeric characters and underscores (A-z, 0-
9, and _ )
❖ A variable is created the moment you first assign a value to it.
❖ A variable name must start with a letter or the underscore character.
❖ Example:
❖ x=5
❖ print(x) # 5
❖ _y = “Sai"
❖ print(_y) # Sai
❖ A variable name cannot start with a number.
❖ Example:
❖ 123z=6 # Invalid
❖ Variable names are case-sensitive (age, Age and AGE are three different variables).
❖ Example:
❖ x=1
❖ print(x) # 1
❖ X = "Sumit“
❖ print(X) # Sumit ( Here X will not overwrite x)
❖ Variables do not need to be declared with any particular type, and can even change
type after they have been set.
❖ Example:
❖ x = 2 # x is of type int
❖ x = "Sai“ # x is now of type str
❖ print(x) #Sai
❖ If you want to specify the data type of a variable, this can be done with casting.
❖ Example:
❖ x = str(7)
❖ print(x) # x will be ‘7’
❖ y = int(7)
❖ print(y) # y will be 7
❖ z = float(7)
❖ print(z) # z will be 7.0
❖ You can get the data type of a variable with the type() function.
❖ Example:
❖ x=3
❖ print(type(x)) #<class 'int’>
❖ y = “Sai"
❖ print(type(y)) #<class 'str'>
❖ String variables can be declared either by using single or double quotes.
❖ Example:
❖ a = "Johny"
❖ print(a) # Johny
❖ #double quotes are the same as single quotes:
❖ a = 'Johny’
❖ print(a) # Johny
❖ Python allows you to assign values to multiple variables in one line. It is called
assignment of many values to multiple variables.
❖ Example:
❖ a, b, c = "Orange", "Banana", "Cherry"
❖ print(a) # Orange
❖ print(b) # Banana
❖ print(c) # Cherry
❖ Python allows you to assign the same value to multiple variables in one line. It is
called assignment of one value to multiple variable.
❖ Example:
❖ a=b=c= “Apple"
❖ print(a) # Apple
❖ print(b) # Apple
❖ print(c) # Apple
❖ Python allows you to combine both text and a variable, Python uses the + character
for this purpose.
❖ Example:
❖ a ="awesome"
❖ print("Python is "+ a) # Python is awesome.
❖ For numbers, the + character works as a mathematical operator.
❖ Example:
❖ a=20
❖ b=30
❖ print(a+b) # 50
❖ Python will give you an error, if you will combine string and a number.
❖ Example:
❖ x=30
❖ y="𝐴𝑟𝑚𝑎𝑛"
❖ print(x+y) # TypeError: unsupported operand type(s) for +: 'int' and 'str'
❖ Python supports 2 types of variables.
❖ Global Variables
❖ Local Variables
❖ The variables which are declared outside of function are called global variables.
❖ These variables can be accessed in all functions of that module.
❖ The variables which are declared inside a function are called local variables.
❖ Local variables are available only for the function in which we declared it. i.e from
outside of function we cannot access.
Comments:
❖ Comments can be used to explain Python code.
❖ Comments can be used to make the code more readable.
❖ Comments starts with a # , and Python will ignore them.
❖ Example:
❖ #This is a comment
❖ print("Hello, Aayush") # Hello, Aayush
❖ Comments can be placed at the end of a line, and Python will ignore the rest of the
line.
❖ Example:
❖ print("Hello, Aayush") #This is a comment
❖ A comment does not have to be text that explains the code, it can also be used to
prevent Python from executing code
❖ Example:
❖ #print("Hello, Aayush")
❖ print("Hello, World") # Hello, World
❖ Python does not really have a syntax for multi line comments.
❖ To add a multiline comment you could insert a # for each line
❖ Example:
❖ #This is a comment
❖ #written in
❖ #more than just one line
❖ print("Hello, Aayush!") # Hello, Aayush
❖ Since Python will ignore string literals that are not assigned to a variable, you can add
a multiline string (triple quotes) in your code, and place your comment inside it.
❖ Example:
❖ """
❖ This is a comment
❖ written in
❖ more than just one line
❖ """
❖ print("Hello, Aayush") # Hello, Aayush
Reading Input from Users:
❖ Python allows for user input.
❖ That means we are able to ask the user for input.
❖ Python 3.6 uses the input() method.
❖ Example:
❖ username = input("Enter username:") # Enter username: Arman
❖ print("Username is: " + username) # Username is: Arman
TYPE CASTING:
❖ We can convert one type value to another type. This conversion is called Typecasting
or Type conversion.
❖ The following are various inbuilt functions for type casting.
❖ 1) int() 2) float() 4) bool() 5) str()
1) int(): We can use this function to convert values from other types to int.
❖ >>> int(123.987) # 123
❖ >>> int(True) #1
❖ >>> int(False) # 0
❖ >>> int("10") #10
❖ >>> int("10.5") #ValueError: invalid literal for int() with base 10: '10.5'
❖ >>> int("ten") #ValueError: invalid literal for int() with base 10: 'ten'
2) float(): We can use float() function to convert other type values to float type.
❖ >>> float(10) #10.0
❖ >>> float(True) #1.0
❖ >>> float(False) #0.0
❖ >>> float("10") #10.0
❖ >>>float("10.5") #10.5
❖ >>> float("ten") # ValueError: could not convert string to float: 'ten'
3) bool(): We can use this function to convert other type values to bool type.
❖ bool(0) # False
❖ bool(1) #True
❖ bool(10) #True
❖ bool(10.5) #True
❖ bool(0.178) #True
❖ bool(0.0) #False
4) str(): We can use this method to convert other type values to str type.
❖ >>> str(10) # '10'
❖ >>> str(10.5) #'10.5'
❖ >>> str(True) #'True'
Python Operators:
❖ Operator is a symbol that performs certain operations.
❖ Python provides the following set of operators:
❖ Arithmetic Operators
❖ Relational Operators OR Comparison Operators
❖ Logical operators
❖ Ternary Operators OR Conditional Operators
❖ Bitwise operators
❖ Assignment operators
❖ Identity Operators
❖ Membership Operators
Arithmetic Operators:
❖+ → Addition (It is also used for string concatenation)
❖ - → Subtraction
❖ * → Multiplication (It is also used for string multiplication)
❖ / → Division
❖ % → Modulus
❖ // → Floor Division
❖ ** → Exponent OR Power
❖ Example:
❖ a=10
❖ b=2
❖ print('a+b=',a+b) # a+b = 12
❖ print('a-b=',a-b) # a-b= 8
❖ print('a*b=',a*b) # a*b= 20
❖ print('a/b=',a/b) # a/b= 5.0
❖ print('a//b=',a//b) # a//b= 5
❖ print('a%b=',a%b) # a%b= 0
❖ print('a**b=',a**b) # a**b= 100
❖ / operator always performs floating point arithmetic. Hence it will always returns float
value.
❖ But Floor division (//) can perform both floating point and integral arithmetic. If
arguments are int type then result is int type. If at least one argument is float type then
result is float type.
❖ We can use +,* operators for str type also.
❖ If we want to use + operator for str type then compulsory both arguments should be
str type only otherwise we will get error.
❖ Example:
❖ “Arman"+10 # TypeError: must be str, not int
❖ “Arman"+"10" # ‘Arman10’
❖ If we use * operator for str type then compulsory one argument should be int and
other argument should be str type.
❖ Example:
❖ 2*“Arman" OR # ArmanArman
❖ “Arman"*2 # ArmanArman
❖ 2.5*“Arman" # TypeError: can't multiply sequence by non-int of type 'float’
❖ “Arman"*“Arman" # TypeError: can't multiply sequence by non-int of type 'str'
Relational Operators:
❖ > → Greater than
❖ < → Less than
❖ >= → Greater than or equal to
❖ <= → Less than or equal to
❖ == → Equal to
❖ != → Not equal to
❖ Example:
❖ a=10
❖ b=20
❖ print("a > b is ",a>b) # a > b is False
❖ print("a >= b is ",a>=b) # a >= b is False
❖ print("a < b is ",a<b) # a < b is True
❖ print("a <= b is ",a<=b) # a <= b is True
❖ We can apply relational operators for str and bool types also.
❖ Example:
❖ a=“Arman"
❖ b=“Arman"
❖ print("a > b is ",a>b) # a > b is False
❖ print("a <= b is ",a<=b) # a <= b is True
❖ print(True>=True) # True
❖ print(10 >True) # True
❖ print(False > True) # False
❖ Chaining of relational operators is possible. In the chaining, if all comparisons returns
True then only result is True. If atleast one comparison returns False then the result is
False
❖ 10<20 # True
❖ 10<20<30 # True
❖ 10<20<30<40 # True
❖ 10<20<30<40>50 # False
❖ We can apply == and != operators for any type even for incompatible types also.
❖ 10==20 # False
❖ 10!= 20 # True
❖ 10==True # False
❖ False==False # True
❖ “Arman"==“Arman" # True
❖ Chaining concept is applicable for equality operators. If atleast one comparison
returns False then the result is False. Otherwise the result is True.
❖ 10==20==30==40 # False
❖ 10==10==10==10 # True
Logical Operators :
❖ We can apply logical operators (and,or,not) for all types.
❖ For Boolean Types Behaviour:
❖ and : If both arguments are True then only result is True.
❖ or: If atleast one arugemnt is True then result is True.
❖ not: Complement
❖ Example:
❖ True and False #False
❖ True or False #True
❖ not False #True
❖ For Non-Boolean Types Behaviour:
❖ 0 means False
❖ non-zero means True
❖ Empty string is always treated as False
❖ x and y: If x is evaluates to false return x otherwise return y
❖ Example:
❖ 10 and 20 # 20
❖ 0 and 20 # 0
❖ If first argument is zero then result is zero otherwise result is y
❖ x or y: If x evaluates to True then result is x otherwise result is y
❖ Example:
❖ 10 or 20 # 10
❖ 0 or 20 # 20
❖ not x: If x is evaluates to False then result is True otherwise False
❖ Example:
❖ not 10 # False
❖ not 0 # True
Ternary OR Conditional Operators :
❖ Syntax: x = first Value if condition else second Value
❖ If condition is True then first Value will be considered else second Value will be
considered.
❖ Example:
❖ a,b=10,20
❖ x=30 if a<b else 40
❖ print(x) # 30
Assignment Operators:
❖ We can use assignment operator to assign value to the variable.
❖ Example:
❖ x = 10
❖ We can combine assignment operator with some other operator to form compound
assignment operator.
❖ Example:
❖ x += 10 → x = x+10
❖ The following is the list of all possible compound assignment operators in Python.
❖ +=
❖ -=
❖ *=
❖ /=
❖ %=
❖ //=
❖ **=
❖ &=
❖ |=
❖ ^=
❖ >>=
❖ <<=
❖ Example:
❖ x=10
❖ x+=20
❖ print(x) # 30
Membership Operators:
❖ We can use Membership operators to check whether the given object present in the
given collection. (It may be String, List, Set, Tuple OR Dict)
❖ in → Returns True if the given object present in the specified Collection.
❖ not in → Returns True if the given object is not present in the specified Collection.
❖ Example:
❖ x="hello learning Python is very easy!!!"
❖ print('h' in x) # True
❖ print('d' in x) # False
❖ print('d' not in x) # True
❖ print('Python' in x) # True
PROGRAMS ON BASIC ELEMENTS OF PYTHON
1. Write a Python program to add 2 Numbers with user input.
❖ Solution:
❖ x = int(input("Enter First Number:"))
❖ y = int(input("Enter Second Number:"))
❖ print("The Sum of First number and Second Number is", x+y)
❖ Output:
❖ Enter First Number: 10
❖ Enter Second Number: 20
❖ The Sum of First number and Second Number is 30
2. Write a Python program to find the area of Triangle.
❖ Solution:
❖ b= int(input("Enter the value of base of Triangle:"))
❖ h= int(input("Enter the value of height of Triangle:"))
❖ print("The Area of the Triangle is",0.5*(b*h), "unit")
❖ Output:
❖ Enter the value of base of Triangle : 10
❖ Enter the value of height of Triangle : 20
❖ The Area of the Triangle is 100.0 unit
3. Write a Python program to find the area of Circle.
❖ Solution:
❖ import math
❖ r = int(input("Enter the radius of the Circle:"))
❖ y = math.pi
❖ print("The Value of pi is",y)
❖ print("The Area of the circle is",y*(r*r))
❖ Output:
❖ Enter the radius of the Circle: 10
❖ The Value of pi is : 3.141592653589793
❖ The Area of the circle is 314.1592653589793
4. Write a Python program to calculate the area of a trapezoid.
❖ Solution:
❖ a = int(input("Enter the value of one parallel side of Trapezoid"))
❖ b = int(input("Enter the value of second parallel side of Trapezoid"))
❖ h = int(input("Enter the value of height of Trapezoid"))
❖ print("The Area of the Trapezoid is",0.5*h*(a+b), "unit")
❖ Output:
❖ Enter the value of one parallel side of Trapezoid 2
❖ Enter the value of second parallel side of Trapezoid 3
❖ Enter the value of height of Trapezoid 2
❖ The Area of the Trapezoid is 5.0 unit
5. Write a Python program to calculate volume and Total area of a cylinder.
❖ Solution:
❖ import math
❖ r = int(input("Enter the radius of Cylinder"))
❖ h = int(input("Enter the heght Cylinder"))
❖ x =math.pi
❖ print("The Total Surface Area of the Cylinder is",(2*x*r*h)+(2*x*r*r), "unit")
❖ print("The Volume of the Cylinder is",(x*r*r*h), "unit")
❖ Output:
❖ Enter the radius of Cylinder 4
❖ Enter the heght Cylinder 5
❖ The Total Surface Area of the Cylinder is 226.1946710584651 unit
❖ The Volume of the Cylinder is 251.32741228718345 unit
6. Write a Python program to convert Fahrenheit to Celsius and vice versa.
❖ Solution:
❖ F=float(input("Enter the temperature in Fahrenheit"))
❖ print("The temperature in Celsius corresponds to given temperature in Fahrenheit is",
(F-32)*(5/9))
❖ C=float(input("Enter the temperature in Celsius"))
❖ print("The temperature in Fahrenheit corresponds to given temperature in Celsius is",
((9/5)*C)+32)
❖ Output:
❖ Enter the temperature in Fahrenheit -40
❖ The temperature in Celsius corresponds to given temperature in Fahrenheit is -40.0
❖ Enter the temperature in Celsius 36.6
❖ The temperature in Fahrenheit corresponds to given temperature in Celsius is
97.88000000000001
7. Write a Python program to convert hours into minutes and seconds.
❖ Solution:
❖ H= int(input("Enter the number of hours you want to convert in minutes and
seconds"))
❖ print("The minutes corresponds to given number of hours are, Minutes=",H*60)
❖ print("The seconds corresponds to given number of hours are, seconds=", H*60*60)
❖ Output:
❖ Enter the number of hours you want to convert in minutes and seconds 3
❖ The minutes corresponds to given number of hours are, Minutes= 180
❖ The seconds corresponds to given number of hours are, seconds= 10800
8. Write a Python program to calculate the square root of a positive number.
❖ Solution:
❖ import math
❖ a = float(input("Enter the positive number"))
❖ x =math.sqrt(a)
❖ print("The square root of entered number is",x)
❖ Output:
❖ Enter the positive number 9.89
❖ The square root of entered number is 3.144837038703278
9. Write a Python program to convert degree to radian.
❖ Solution:
❖ import math
❖ pie=math.pi
❖ d= int(input("Enter the value of degree measure which you want to convert in
radian"))
❖ r= (pie*d)/180
❖ print("The radian measure corresponds to degree measure is",r)
❖ Output:
❖ Enter the value of degree measure which you want to convert in radian
❖ 180
❖ The radian measure corresponds to degree measure is 3.141592653