Introduction To Python - 1
Introduction To Python - 1
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!")
• 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
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!")
#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
Output:
Orange
Orange
Orange
print(x)
print(y)
print(z)
Output:
Orange
Banana
Cherry
Output Variables
x = "awesome"
print("Python is " + x)
x = "Python is "
y = "awesome"
z= x+y
print(z)
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
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 = 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 = 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
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
• 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: ?
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]
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()
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
• 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.
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
Output:
Aston
Audi
McLaren
Indexing using Range function:
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.
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))