0% found this document useful (0 votes)
107 views79 pages

Introduction To Python - 1

Python is a popular programming language created by Guido van Rossum in 1991. It can be used for web development, software development, mathematics, and system scripting. Python code can be executed as soon as it is written due to its interpreter system. It works on many platforms and has a simple, English-like syntax.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
107 views79 pages

Introduction To Python - 1

Python is a popular programming language created by Guido van Rossum in 1991. It can be used for web development, software development, mathematics, and system scripting. Python code can be executed as soon as it is written due to its interpreter system. It works on many platforms and has a simple, English-like syntax.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 79

What is Python?

Python is a popular programming language. It was created by Guido van


Rossum, and released in 1991.
It is used for:
• web development (server-side),
• software development,
• mathematics,
• system scripting.
What can Python do?
Python can be used on a server to create web applications.
Python can be used alongside software to create workflows.
Python can connect to database systems. It can also read and modify
files.
Python can be used to handle big data and perform complex
mathematics.
Python can be used for rapid prototyping, or for production-ready
software development.
Why Python?
• Python works on different platforms (Windows, Mac, Linux,
Raspberry Pi, etc).
• Python has a simple syntax similar to the English language.
• Python has syntax that 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.
Python Statement

Multi-line statement
Example-1
a=1+2+3+\
4+5+6+\
7+8+9
print(a)

Example-2
a = (1 + 2 + 3 +
4+5+6+
7 + 8 + 9)
print(a)

Example-3
colors = ['red',
'blue',
'green']
print(colors)
Python Indentation
• if 5 > 2:
print("Five is greater than two!")

Output :Five is greater than two!

• if 5 > 2:
print("Five is greater than two!")

• Output :
print("Five is greater than two!")
^
IndentationError: expected an indented block
Python has no command for declaring a variable.

x=5
y = "Hello, World!"
print(x)
print(y)

Output:
5
"Hello, World!"
Python Indentation

Most of the programming languages like C, C++, Java use braces { } to


define a block of code. Python uses indentation.

for i in range(1,11):
print(i)
if i == 5:
break
Python Output Using print() function
Output formatting

x = 12.3456789
print('The value of x is %.2f' %x)
print('The value of x is %.4f' %x)
Python Input
num = input('Enter a number: ')
print(num)

Python Import
1.
import math
print(math.pi)

2.
from math import pi
print(pi)
Python Comments
• Example
#This is a comment
print("Hello, World!")

print("Hello, World!") #This is a comment

#This is a comment
#written in
#more than just one line
print("Hello, World!")
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
Creating Variables
Variables do not need to be declared with any particular type and can
even change type after they have been set.

x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)

Output
Sally
String variables can be declared either by using single or double quotes:

Example

x = "John"
print(x)
#double quotes are the same as single quotes:
x = 'John'
print(x)

Output:
John
John
Variable Names

• A variable can have a short name (like x and y) or a more descriptive


name (age, carname, total_volume). 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)
• And you can assign the same value to multiple variables in one line:
x = y = z = "Orange"
print(x)
print(y)
print(z)

Output:
Orange
Orange
Orange

x, y, z = "Orange", "Banana", "Cherry"

print(x)
print(y)
print(z)

Output:
Orange
Banana
Cherry
Output Variables

x = "awesome"
print("Python is " + x)

Output: Python is awesome

x = "Python is "
y = "awesome"
z= x+y
print(z)

Output: Python is awesome

• The python print statement is often used to output variables.


• + character used to add variable to another variable .
x=5
y = 10
print(x + y)
Output: 15

x=5
y = "John"
print(x + y)
Output:
unsupported operand type(s) for +: 'int' and 'str'
Global Variables
Create a variable outside of a function, and use it inside the function

x = "awesome"
def myfunc():
print("Python is " + x)
myfunc()
Output: Python is awesome

x = "awesome"
def myfunc():
x = "fantastic"
print("Python is " + x)
myfunc()
print("Python is " + x)

Output:
Python is fantastic
Python is awesome
Built-in Data Types
Text Type: str

Numeric Types: int, float, complex

Sequence Types: list, tuple, range

Mapping Type: dict

Set Types: set, frozenset

Boolean Type: bool

Binary Types: bytes, bytearray, memoryview


Print the data type of the variable x

x=5
print(type(x))
Output: <class 'int'>
x = "Hello World“ str Hello World
#display x: <class 'str'>
print(x)
#display the data type of x:
print(type(x))

x = 20 int 20
#display x: <class 'int'>
print(x)
#display the data type of x:
print(type(x))

x = 20.5 float 20.5


#display x: <class 'float'>
print(x)
#display the data type of x:
print(type(x))

x = 1j complex lj
<class 'complex'>
x = ["apple", "banana", "cherry"] list ['apple', 'banana', 'cherry']
<class 'list'>
x = ("apple", "banana", "cherry") tuple ('apple', 'banana', 'cherry')
<class 'tuple'>
x = range(6) range range(0, 6)
#display x: <class 'range'>
print(x)
#display the data type of x:
print(type(x))

x = {"name" : "John", "age" : dict {'name': 'John', 'age': 36}


36} <class 'dict'>

x = {"apple", "banana", set {'banana', 'apple', 'cherry'}


"cherry"} <class 'set'>

x = frozenset({"apple", frozenset frozenset({'apple', 'banana', 'cherry'})


"banana", "cherry"}) <class 'frozenset'>

x = True bool True


<class 'bool'>
Python Numbers
There are three numeric types in Python
• int
• float
• complex

x = 1 # int
y = 2.8 # float
z = 1j # complex
print(type(x))
print(type(y))
print(type(z))
Output:
<class 'int'>
<class 'float'>
<class 'complex'>
x=1
y = 35656222554887711
z = -3255522

print(type(x))
print(type(y))
print(type(z))

Output:
<class 'int'>
<class 'int'>
<class 'int'>
x = 1.10
y = 1.0
z = -35.59
print(type(x))
print(type(y))
print (type(z))

Output
<class 'float'>
<class 'float'>
<class 'float'>
COMPLEX NUMBER
x = 3+5j
y = 5j
z = -5j
print(type(x))
print(type(y))
print(type(z))
Output
<class 'complex'>
<class 'complex'>
<class 'complex'>
Type Conversion
x = 1 # int
y = 2.8 # float
z = 1j # complex
#convert from int to float:
a = float(x)
#convert from float to int:
b = int(y)
#convert from int to complex:
c = complex(x)
print(a)
print(b)
print(c)
print(type(a))
print(type(b))
print(type(c))
Output:
1.0
2
(1+0j)
<class 'float'> <class 'int'> <class 'complex'>
Python does not have a random() function to make a random number, but Python has a built-in module called random that can be used to make random numbers:

import random
print(random.randrange(1,10))

Output
Any random number from 1 to 10.
Python Casting
x = int(1)
y = int(2.8)
z = int("3")
print(x)
print(y)
print(z)
Output:
1
2
3

x = float(1) # x will be 1.0


y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2
Python Keywords
Keywords in Python
False class finally is return
None continue for lambda try
True def from nonlocal while
and del global not with
as elif if or yield
assert else import pass
break except in raise
Introduction to Python Operator

Python Operator falls into 7 categories:


• Python Arithmetic Operator
• Python Relational Operator
• Python Logical Operator
• Python Assignment Operator
• Python Membership Operator
• Python Identity Operator
• Python Bitwise Operator
Arithmetic operators

Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication etc .
Operator Meaning Example

x+y
+ Add two operands or unary plus
+2

Subtract right operand from the left or unary x-y


-
minus -2

* Multiply two operands x*y

Divide left operand by the right one (always


/ x/y
results into float)

Modulus - remainder of the division of left


% x % y (remainder of x/y)
operand by the right

Floor division - division that results into whole


// x // y
number adjusted to the left in the number line

Exponent - left operand raised to the power of


** x**y (x to the power y)
right
Relational operators
Logical operators
Assignment Operators
Special operators

• Identity operators
• Membership operators
Identity operators
‘is’ operator
# Python program to illustrate the use
# of 'is' identity operator
x=5
if (type(x) is int):
print ("true")
else:
print ("false")
‘is not’ operator
# Python program to illustrate the
# use of 'is not' identity operator
x = 5.2
if (type(x) is not int):
print ("true")
else:
print ("false")
Membership operators
Binary Bitwise operator
A while loop in python iterates till its condition becomes False. In other words, it executes the statements
under itself while the condition it takes is True.
When the program control reaches the while loop, the condition is checked. If the condition is true, the
block of code under it is executed. Remember to indent all statements under the loop equally. After
that, the condition is checked again. This continues until the condition becomes false. Then, the first
statement, if any, after the loop is executed.
Python While Loop
a=3
while(a>0):
print(a)
a-=1

output:
3
2
1

Example 2:
a=3
while a>0: print(a); a-=1;
b. The else statement for while loop

a=3
while(a>0):
print(a)
a-=1
else:
print("Reached 0")

Output: ?

if a==1: break; give in while block and check the o/p

Q. Sum of natural numbers up to given number using while loop.


Python For Loop
Python for loop can iterate over a sequence of items. The structure of a for loop
in Python is different than that in C++ or Java. That is, for(int i=0;i<n;i++) won’t
work here. In Python, we use the ‘in’ keyword. Lets see a Python for loop
Example
for a in range(3):
print(a)

Output:?

for a in range(3):
print(a+1)
Output:?
The range() function
list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] We use the list function to convert the range object into a list object.

list(range(2,7))
[2, 3, 4, 5, 6]

You can also pass three arguments. The third argument is the interval.
list(range(2,12,2))
[2, 4, 6, 8, 10]

Remember, the interval can also be negative.


list(range(12,2,-2))
[12, 10, 8, 6, 4]
Iterating on lists or similar constructs
for a in [1,2,3]:
print(a)
Output:?

for i in {2,3,3,4}:
print(i)
Output:?

for i in 'wisdom':
print(i)
Output:?
Iterating on indices of a list or a similar construct
list=['Romanian','Spanish','Gujarati']
for i in range(len(list)):
print(list[i])
----------------------------------------------------------------------------------------------
Output:
The else statement for for-loop

for i in range(10):
print(i)
else:
print("Reached else")
-----------------------------------------------------------------------------

for i in range(10):
print(i)
if(i==7): break
else: print("Reached else")
Nested for Loops Python

for i in range(1,6):
for j in range(i):
print("*",end=' ')
print()

Nested While Loops Python

i=6
while(i>0):
j=6
while(j>i):
print("*",end=' ')
j-=1
i-=1
print()
Loop Control Statements in Python
break statement

When you put a break statement in the body of a loop, the loop stops
executing, and control shifts to the first statement outside it. You can put it in
a for or while loop.

for i in 'break':
print(i)

if i=='a': break;
Output:
b
r
e
a
continue statement
When the program control reaches the continue statement, it skips the statements after
‘continue’. It then shifts to the next item in the sequence and executes the block of code
for it. You can use it with both for and while loops.

i=0
while(i<8):
i+=1
if(i==6): continue
print(i)
• o/p:
1
2
3
4
5
7
8
Pass statement

Pass Statement: We use pass statement to write empty loops. Pass is


also used for empty control statement, function and classes.

for letter in ‘pythoncourse':


pass
print(letter)
Python Collections (Arrays)
There are four collection data types in the Python programming
language:

• List
• Tuple
• Set
• Dictionary
Looping Techniques in Python
Using enumerate(): enumerate() is used to loop through the containers
printing the index number along with the value present in that particular
index.

# python code to demonstrate working of enumerate()

for key,value in enumerate(['The', 'Big', 'Bang', 'Theory']):


print(key, value)
Output:
0 The
1 Big
2 Bang
3 Theory
Using zip(): zip() is used to combine 2 similar containers(list-list or dict-
dict) printing the values sequentially. The loop exists only till the smaller
container ends.

questions = ['name', 'colour', 'shape']


answers = ['apple', 'red', 'a circle']
# using zip() to combine two containers and print values
for question, answer in zip(questions, answers):
print('What is your {0}? I am {1}.'.format(question, answer))
Output:?
Looping Techniques in Python Continue….
• Using items(): items() is used to loop through the dictionary printing
the dictionary key-value pair sequentially.

king = {'Akbar': 'The Great', 'Chandragupta': 'The Maurya',


'Modi' : 'The Changer'}

# using items to print the dictionary key-value pair


for key, value in king.items():
print(key, value)
Output:
sorted() and Set()
• # python code to demonstrate working of sorted()

lis = [ 1 , 3, 5, 6, 2, 1, 3 ]
for i in sorted(lis) :
print (i,end=" ")
print("\r")
# using sorted() and set() to print the list in sorted order
# use of set() removes duplicates.
print ("The list in sorted order (without duplicates) is : ")
for i in sorted(set(lis)) :
print (i,end=" ")
• Using reversed(): reversed() is used to print the values of container in
the descending order as declared.
lis = [ 1 , 3, 5, 6, 2, 1, 3 ]
# using revered() to print the list in reversed order
print ("The list in reversed order is : ")
for i in reversed(lis) :
print (i,end=" ")
Using Iterations in Python Effectively
• C-style approach:This approach requires prior knowledge of total number
of iterations

cars = ["Aston", "Audi", "McLaren"]


i=0
while (i < len(cars)):
print cars[i]
i += 1
Output:
Aston
Audi
McLaren
• Use of for-in (or for each) style:
This style is used in python containing iterator of lists, dictonary, n dimensional-
arrays etc. The iterator fetches each component and prints data while looping.
The iterator is automatically incremented/decremented in this construct.

# Accessing items using for-in loop

cars = ["Aston", "Audi", "McLaren"]


for x in cars:
print x

Output:
Aston
Audi
McLaren
Indexing using Range function:

We can also use indexing using range() in Python


• # Accessing items using indexes and for-in

cars = ["Aston", "Audi", "McLaren"]


for i in range(len(cars)):
print cars[i]

Output:
Aston
Audi
McLaren
• Enumerate:
Enumerate is built-in python function that takes input as iterator, list etc and returns a tuple
containing index and data at that index in the iterator sequence. For example, enumerate(cars),
returns a iterator that will return (0, cars[0]), (1, cars[1]), (2, cars[2]), and so on.

cars = ["Aston" , "Audi", "McLaren "]


for x in enumerate(cars):
print (x[0], x[1])
O/p:->
0 Aston
1 Audi
2 McLaren
Exercises
List slices
list = ['a', 'b', 'c', 'd', 'e', 'f'] a = 0th, b=1st , c=2nd , d=3rd , e=4th , f=5th Indices
x=list[1:3]
print(x)
o/p: ['b', 'c']
y=list[:4]
print(y)
o/p: ['a', 'b', 'c', 'd‘]
z=list[3:]
print(z)
o/p: ['d', 'e', 'f']
m=list[:]
Print(m)
o/p: ['a', 'b', 'c', 'd', 'e', 'f']
n=list[::-1]
print(n)
o/p:['f‘, 'e‘, 'd‘, 'c‘, 'b‘, 'a']
List methods
t = ['a', 'b', 'c']
t.append('d')
print(t)
o/p: ['a', 'b', 'c', 'd’]

t1 = ['a', 'b', 'c']


t2 = ['d', 'e']
t1.extend(t2)
print(t1)
o/p: ['a', 'b', 'c', 'd', 'e']

t = ['d', 'c', 'e', 'b', 'a']


t.sort()
print(t)
o/p: ['a', 'b', 'c', 'd', 'e']
List Operations
a=[0] * 4
print(a)
o/p:[0,0,0,0]
b=[1, 2, 3] * 3
print(b)
o/p:[1, 2, 3, 1, 2, 3, 1, 2, 3]

a = [1, 2, 3]
b = [4, 5, 6] + operator concatenates lists

c=a+b
print(c)
o/p:[1,2,3,4,5,6,]
Deleting elements
t = ['a', 'b', 'c']
x = t.pop(1)
print(t)
o/p: ['a', 'c']
t = ['a', 'b', 'c']
del t[1]
print(t)
o/p: ['a', 'c']
t = ['a', 'b', 'c']
t.remove('b')
print(t)
o/p:['a', 'c']
t = ['a', 'b', 'c', 'd', 'e', 'f']
del t[1:5]
print(t) o/p:['a', 'f']
Index function in python
list_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
element = 3
print(list_numbers.index(element))

list_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


element = 7
list_numbers.index(element, 1, 5)

You might also like