You are on page 1of 33

UNIT 4

Introduction to Python

Guido van Rossum-The Python Creator


Python was released in 1991.

Van Rossum thought he needed a name that was short, unique, and slightly mysterious, so he
decided to call the language Python. When he began implementing Python, Guido van Rossum was
also reading the published scripts from “Monty Python's Flying Circus”, a BBC comedy series from
the 1970s.so he thought that naming his Language as Python would grab the attention of the all.
What is Python?
• Python is an object-oriented, high-level programming and interpreted language. First launched in 1992.
Why Python?
• Python works on different platforms like Windows, Mac, Linux etc
• Python has a simple syntax similar to the English language. It allows developers to write programs with
fewer lines than some other programming languages.
• Python runs on an interpreter system, meaning that code can be executed as soon as it is written.
• Can easily interact with the database systems and handle big data and perform complex mathematics
Features of Python programming Applications of Python:
▪ Python is a case-sensitive language.
▪ Web and Internet Development
▪ Easy To Learn & Use While Coding.
▪Desktop GUI Application
▪ Clear syntax and a simple keyword structure.
▪ Extensible Feature. ▪Software Development
▪ Interpreted Language.
▪Database Access
▪ Expressive Language.
▪Business Application
▪ Cross-Platform Portable Language.
▪ Dynamic Memory Allocation. ▪Games and 3D Graphics
▪ High-Level Interpreted Language.
▪ Graphical User Interface (GUI) Support:
Python Code Editors
• IDLE
• Replit
• PyCharm
• Visual Studio Code

Download: Pydroid 3 - IDE for Python 3 (Free, in-app purchases available)


Download: Pydroid repository plugin (Free)
Download: Pydroid permissions plugin (Free)
Quiz Time
1. Python is a ___object-oriented programming language.
a. Special purpose
b. General purpose General purpose
c. Medium level programming language
d. All of the mentioned above
2. Amongst the following, who is the developer of Python programming?
a.Guido van Rossum
b.Denis Ritchie
c.Y.C. Khenderakar
Guido van Rossum
d.None of the mentioned above
3. Amongst which of the following is / are the application areas of Python programming?
a.Web Development
b.Game Development All of the mentioned above
c.Artificial Intelligence and Machine Learning
d.All of the mentioned above
4. What is the name of the operator ** in Python?
a.Exponentiation
b.Modulus
c.Floor division Exponentiation
d.None of the mentioned above
Downloading and Setting up Python
Step 1 : Download Python from python.org using link python.org/downloads
Step 2 : Select appropriate download link as per Operating System [Windows 32 Bit/64 Bit, Apple iOS]
Step 3 : Click on Executable Installer
Step 4 : Install
Python IDLE installation
After installing Python, you’ll need an IDE to write Python programmes.
IDLE is a Python editor with a graphical user interface.
IDLE stands for Integrated Development and Learning Environment.
This IDLE is also known as the Python shell, and it has two modes of operation:
Interactive mode
Interactive Mode allows us to communicate with the operating system, Python IDLE Shell provides a
Python prompt, You can write single line python commands and execute them easily.
Script mode.
Script Mode allows you to add numerous lines of code. In script mode, we type a Python programme into a
file and then use the interpreter to run the code.
5. Which of the following is the valid Python file extension?
a. .python
b. .pl .py
c. .py
d. .p
6.The % operator returns the ___.
a. Quotient
b. Divisor Remainder
c. Remainder
d. None of the mentioned above
7. What is the output of the following code :
print 9//2
a.4.5
b.4.0
c.4
4
d.error
8. Conditional statements are also known as ___ statements.
a.Decision-making
b.Array
c.List Decision-making
d.None of the mentioned above
9. Which of the following is correct conditional statement in Python code
a.If x<=100
b.If(x<=100) if x<=100:
c.if x<=100:
d.If x<=100:
10. What will be the output of the following Python code
a=10
if a>5:
print("Greater")
Error [Expected Intended block]
a.Greater
b.Error [Expected Intended block]
c.10
d.5
11. What will be the output of the following Python code
a=10
if a>5 and a<15: Given Condition is Matched
print(“Given Condition is Matched”)
else:
print(“Given Condition is not Matched”)
a.Given Condition is Matched
b.Given Condition is not Matched
Quiz Time
13. Python is a _________ programming language, which means it runs on a variety of platforms including
Windows, MacOS, Linux etc
a. Cross-platform Cross-platform
b. Single-platform
c. Code-platform
d. None of the above
4. IDLE stands for ____________.
a. Integrated Development and Learning Environment Integrated Development and
b. Internal Develop and Learning Environment
c. Inside Development and Learning Environment Learning Environment
d. None of the above
Python Statement and Comments
Python Statement
A statement is a piece of code that can be executed by a Python interpreter. So, in simple words, anything
written in Python is a statement.
In The Python programming language, there are various types of statements, such as
▪ Assignment statements
▪ Conditional statements
▪ Looping statements etc.
Python Comments
• Comments can be used to explain Python code.
• Comments can be used to make the code more readable.
• Comments can be used to prevent execution when testing code.
Single line Comment # # Single line comment
Multiple Line Comment Starts and end with “””
# Multiple line comment 1 “”” # Multiple line comment 1
# Multiple line comment 2 # Multiple line comment 2 ”””
Python Keywords
Keywords are nothing but special names that are already present in python. We can use these keywords
for specific functionality while writing a python program. Reserved keywords means no object can have
the same name as one of these keywords. Keywords can’t be used as a variable name, function name, or
identifier.
Arithmetic Operators
Let X = 48 Y =5
Operator Name Example Output Comment
+ Addition x+y 53 Returns the sum of the variables
- Subtraction x-y 43 Returns the difference of the variables
* Multiplication x*y 240 Returns the product of the variables
/ Division x/y 9.6 Returns the quotient of the division
% Modulus x%y 3 Returns the remainder of the division
** Exponentiation x ** y 254803968 Returns the exponents of the variables
// Floor division x // y 9 Returns the integer part of quotient
after the division
Variables
One of the most powerful features of a programming language is the ability to manipulate variables. A
variable is a container used for storing data values.
An assignment statement creates new variables and gives them values:
Ex : pi = 3.1415
name = “Sanjay”
Assignment operator is used in Python to assign values to variables. For example, y = 42 is a simple
assignment operator that assigns the value 42 on the right to the variable y on the left.

Rules for naming the Python variables


• A variable name must start with a letter or the underscore character.
• Keywords cannot be used as variable name
• 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)
Constants
A constant is a kind of variable that has a fixed value. Constants are
like containers that carry information that cannot be modified later.
Declaring and assigning value to a constant
Name = “Kumar” Age =14
Datatype
Python has a number of different data types. The following are some of the basic datatypes.
1.Integer
2.Float
3.String

Number Datatype
Numerical Values are stored in the Number data type. There are four categories of number datatype –
1.Int – Int datatype is used to store the whole number values. Example : x=500
2.Float – Float datatype is used to store decimal number values. Example : x=50.5
Python Output Using print() function
Example Code Sample Output
a = 200
b = 100 500
print(a + b)
print(45 + 35) 80
print("My name is Kajal") My name is Kajal
a = “Nisha"
My name is : Nisha
print("My name is :",a)
x = 56.5 x=
print("x = \n", x) 56.5
m=6
I have 6 apples
print(" I have",m,"apples")
a="My"
b="India" MyIndia (Concatenation of string)
print(a+b)
1. The end parameter
The end parameter is used to append any string at the end of the output of the print statement in python.

By default, the print the method ends with a new line. This means there is no need to explicitly specify the parameter
end as '\n'. Programmers with a background in C/C++ may find this interesting.
Example with out end parameter
print(“Your Performance") # By default, the print the method ends with a new line.
print("is awesome")
Output:
Your Performance
is awesome
Example with end parameter
print(“Your Performance“, end=“ “ ) # end parameter indicates that the end character has to be identified by
whitespace and not a new line
print("is awesome")
Output:
Your Performance is awesome
2. The sep parameter
The sep parameter is primarily used to format the strings that need to be printed on the console and add a
separator between strings to be printed. This feature was newly introduced in Python 3 version.
Example with out sep parameter
print("Excellent","performance",sep="#")
print("Study","Score",sep="&")

Output:
Excellent#performance
Study & Score

The end parameter is used to specify a string that will be printed after the output. However, the
sep parameter is used as a separator between the items that you want to print.
Flow of control and conditions
Conditional Statement in Python perform different computations
or actions depending different situations. There are 3 control
flow statements in Python - if, for and while
Decision making statements in programming languages decide the direction of flow of
program execution. Decision making statements available in Python are:
● if statement ● if .. else statements ● if-elif ladder
If Statement
The if statement is used to check a condition: if the condition is
true, we run a block of statements (called the if-block).
Syntax Sample Output
Enter a Number -9
# To check if the entered Number is Positive try again
n = int(input("Enter a Number"))
if n>0: Enter a Number 5
print(n," is positive number") 5 is positive number
print("try again") try again
if...else Statement
The if..else statement evaluates test expression and will execute body of if only when test condition is True. If the condition is False,
body of else is executed. Indentation is used to separate the blocks.
Syntax Sample Output
#check if the student is pass or fail Enter the mark 89
n = int(input("Enter the mark")) Result :PASS
if n>=40:
print("Result :PASS") Enter the mark 35
else: Result :FAIL
print("Result :FAIL")
if..elif.. else Statement
The elif is short for else if. It allows us to check for multiple expressions. If the condition for if is
False, it checks the condition of the next elif block and so on. If all the conditions are False, body of
else is executed. The if block can have only one else block. But it can have multiple elif blocks.. But
only block among several if...elif...else blocks is executed based on the condition
#To check the discount for Entry for Global Village Enter the age 3
Syntax age=int(input("Enter the age")) Junior Discount
if age >= 60:
print('Senior Discount') Enter the age 65
elif 4 <= age < 60: Senior Discount
print('No Discount')
else: Enter the age 4
print('Junior Discount') No Discount
Find Errors in the following Python program
Find error(s) in the following code rewrite the code and output (answers are given in pink)

1. Print("Anuj") #print("Anuj")
2. age =Int(input(“Enter the age of the person”) # int(input(“Enter the age of the person”))
3. If i =< 5 # if i <= 5:
4. print(5,6,2030,Sep=‘/’) # print(5,6,2030,sep='/’)
5. print(“ Welcome to ”, End=“ “) # print(“ Welcome to ”, end=“ “)
6. x= int(“Enter value of x:”)
if x=y
print("They are equal")
else:
Print( "They are unequal")
7.
a = input("Enter any number")
if a%2=0: # if a%2==0:
print("Even number)
Else # else:
print("Odd number")
Find Errors in the following Python program
Find error(s) in the following code rewrite the code and output
8.
x = int(Input("Enter any number")) # x = int(input("Enter any number"))
y = int(input("Enter any number"))
If x>y # if x>y:
print("First number is greater"))
else:
Print("Second number is greater") # print("Second number is greater")

What will be the output of the below codes


1.
Output:
a,b,c=5,10,15
5***10***15
print(a,b,c,sep="***")

2.
x,y=25,50
Output:
print("Before Swapping x=",x,"y=",y)
Before Swapping x= 25 y= 50
x,y=y,x After Swapping x= 50 y= 25
print("After Swapping x=",x,"y=",y)
3.
print("Welcome to", end=" ") Output:
print("explore the world of Python") Welcome to explore the world of Python

4. Output:
print("*"*25)
print("I like Python programming") *************************
I like Python programming
print("*"*25)
*************************
Different types of Loop statements are :

3 types of loops are


there in Python :
The three types of
loops in Python
programming are
• while loop,
• for loop, and
• nested loops
What is a Loop statement
A loop in Python is a control flow statement that is used to repeatedly execute a group of statements as
long as the condition is satisfied.
General Syntax of For statement
for variable in sequencename:
Statements
...
Statements
• The first word of the statement starts with the keyword “for” which signifies the beginning of the for
loop.
• Then we have the variable which iterates over the sequence and can be used within the loop to perform
various functions
• The next is the “in” keyword in Python which tells the iterator variable to loop for elements within the
sequence
• Python For loop is used for sequential traversal i.e. it is used for iterating over an Seguena datatype
variable like String, or List
While Loop

# program to display numbers from 1 to 10

# initialize the variable


n = 10

# for loop from i = 1 to 10


For i in range(1,n+1)
print(i)
Syntax of Python range() function

For variable name in range(start, stop, step):

Parameter :
•start: [ optional ] start value of the sequence
Default the start value starts from 0
•stop: next value after the end value of the sequence. Should be integer only
• step: [ optional ] integer value, denoting the difference between any two numbers
in the sequence
Default the step count is 1

All three arguments of range can be positive or negative.


Output
#print the letters of a string one in a line b
test=“Believe in yourself" e
for x in test: l
e
print (x) i
Output v
#print the items of the given list e
i
cl = ["Red","Green","White" ,"Black"] n
print("The colors in the List are :") y
o
for i in cl: u
Output
print(i) r
s
e
#print the number in reverse order l
h=int(input("Enter the highest values")) f
print("The number in reverse order is:")
for i in range(h,0,-5):
print(i)
Output
#print the desired Table till the limit you enter
a=int(input("What table do you want to print? "))
l=int(input("What is the limit? "))
print(a,"Table is :")
for i in range(1,l+1):
print( i,'x',a,"=",i*a)

#print even numbers till the count mentioned Output

n = int(input("Enter the number of even terms to display"))


print(" The ",n,"number of even terms are")
for i in range(1,n+1):
print(i*2)
Sequence Datatype
A sequence is a collection of elements that are ordered and indexed.
String – String is are enclosed either by (‘ ‘) or (“ “) Quotes eg: “Welcome to learn Python”
List
List is one of built-in data types in Python used to store collections of data. Lists are used to
store multiple items in a single variable. List is collection of ordered, changeable items and it
allows duplicate members.
In Python, a list is created by placing elements inside square brackets [], separated by commas.
A list can have any number of items and they may be of different types (integer, float, string,
etc.).
mylist = [] # creates an empty list
mylist = [1, 2, 3] # list of integers
mylist = [1, "Hello", 3.14] # list with mixed data types
The index must be an integer. We can't use float or other types, this will result in TypeError.
How to access List Elements
A list is made up of various elements which need to be individually accessed on the basis
of the application it is used for. There are two ways to access an individual element of a
list:
1)List Index 2)Negative Indexing

List Index
A list index is the position at which any element is present in the list. Index in the list
starts from 0, so if a list has 5 elements the index will start from 0 and go on till 4. In
order to access an element in a list we need to use index operator [].
Negative Indexing
Python allows negative indexing for its sequences. The index of -1 refers to the last item,
-2 to the second last item and so on.
Trying to access indexes other than the given range will raise an IndexError.
Some of the Methods which can be used with lists are mentioned below:
Method Description
append() Adds an element at the end of the list. Syntax : Listname.append(value)
clear() Removes all the elements from the list. Syntax : Listname.clear()
len() Returns the number of items in the list. Syntax : len(listname)
count() Returns the number of elements with the specified value. listname.count(value)
extend() Add more than 1 element to the end of the list. lname.extend([list of values])
index() Returns the index of the first element with the specified value. ln.index(value)
insert() Adds an element at the specified position. Syntax : Listname.insert(position,value)
pop() Removes the element from the specified position. Syntax : Listname.pop(position)
remove() Removes the first item with the specified value. Syntax : Listname.remove(value)
reverse() Reverses the order of the list. Syntax : Listname.reverse()
sort() Sorts the list. Syntax : Listname.sort()
del() Deletes the Items from the list Syntax : del.listname or del.listname[start val:end val+1]
Find output of the following Python program
Program
color =["Violet","Indigo","Blue","Green","Yellow"]
print("***** List items are *****")
print(*color, sep="\n")

Output
***** List items are *****
Violet
Indigo
Blue
Green
Yellow

Program
numlist=[2,6,4,5,3,8,7,5]
print(numlist[-7:-2])
Output
[6, 4, 5, 3, 8]

You might also like