Python | Java |
---|---|
Interpreted Language | Compiled Language |
Slower, type of data is determined at runtime | Faster, less time to execute the code |
Concise | Verbose |
Uses Identation for structuring code | Uses braces for code structuring |
Best for AI, ML IoT | Embedded and cross-platform applications |
python --version
It provides
Visit https://go.lehigh.edu/linux to use Anaconda (and other Linux software) installed and maintained by the Research Computing group on your local Linux laptop or workstation
message = 'And now for something completely different'
n = 17
pi = 3.1415926535897931
the third assigns the (approximate) value of $\pi$ to pi
To display the value of a variable, you can use a print function
print("Hello World!")
print(message)
Hello World! And now for something completely different
type(message)
str
type(n)
int
type(pi)
float
input('What is your name: ')
What is your name: Sachin Joshi
'Sachin Joshi'
76trombones = 'big parade'
File "<ipython-input-8-ee59a172c534>", line 1 76trombones = 'big parade' ^ SyntaxError: invalid syntax
class = 'Advanced Theoretical Zymurgy'
File "<ipython-input-9-73fc4ce1a15a>", line 1 class = 'Advanced Theoretical Zymurgy' ^ SyntaxError: invalid syntax
and | del | for | is | raise |
as | elif | from | lambda | return |
assert | else | global | not | try |
break | except | if | or | while |
class | exec | import | pass | with |
continue | finally | in | yield | |
def |
Following are the standard or built-in data type of python:
# Creating a String with single Quotes
String1 = 'Welcome to the Geeks World'
print("String with the use of Single Quotes: ")
print(String1)
String with the use of Single Quotes: Welcome to the Geeks World
# Creating a String with double Quotes
String1 = "I'm a Geek"
print("String with the use of Double Quotes: ")
print(String1)
print(type(String1))
String with the use of Double Quotes: I'm a Geek <class 'str'>
# Creating String with triple Quotes
# allows multiple lines
String1 = '''Geeks
For
Life'''
print("Creating a multiline String: ")
print(String1)
Creating a multiline String: Geeks For Life
print("This string contains a single quote (') character.")
print('This string contains a double quote (") character.')
This string contains a single quote (') character. This string contains a double quote (") character.
Escape Sequence | Escaped Interpretation |
---|---|
\' | Literal single quote (') character |
\" | Literal double quote (") character |
\newline | Newline is ignored |
\\ | Literal backslash () character |
\n | ASCII Linefeed (LF) character |
\r | ASCII Carriage Return (CR) character |
\t | ASCII Horizontal Tab (TAB) character |
\v | ASCII Vertical Tab (VT) character |
print('This string contains a single quote (\') character.')
print("This string contains a double quote (\") character.")
This string contains a single quote (') character. This string contains a double quote (") character.
str1="Hello"
str2="Hello"
print(id(str1),id(str2))
1495599709240 1495599709240
str1+=", Welcome to LTS Seminars"
print(str1, "\n", id(str1), "\n", id(str2))
Hello, Welcome to LTS Seminars 1495599788080 1495599709240
# Printing First character
print("\nFirst character of String is: ")
print(str1[0])
First character of String is: H
# Printing Last character
print("\nLast character of String is: ")
print(str1[-1])
Last character of String is: s
s = "So, you want to learn Python? " * 4
print(s)
So, you want to learn Python? So, you want to learn Python? So, you want to learn Python? So, you want to learn Python?
s[start:end]
will return part of the string starting from index start
to index end - 1
s[3:15]
' you want to'
start
index and end
index are optional. start
index is 0 end
is the last index of the strings[:3]
'So,'
s[15:]
' learn Python? So, you want to learn Python? So, you want to learn Python? So, you want to learn Python? '
s[:]
'So, you want to learn Python? So, you want to learn Python? So, you want to learn Python? So, you want to learn Python? '
len(s)
120
# Creating a List
List = []
print("Intial blank List: ")
print(List)
Intial blank List: []
# Creating a List with the use of multiple values
List = [10, 20, 30, 40]
print("List containing multiple values: ")
print(List)
print("Fist Element", List[0])
print("Third Element", List[2])
List containing multiple values: [10, 20, 30, 40] Fist Element 10 Third Element 30
# Creating a Multi-Dimensional List
# (By Nesting a list inside a List)
List = ['spam', 2.0, 5, [10, 20]]
print("Multi-Dimensional List: ")
print(List)
Multi-Dimensional List: ['spam', 2.0, 5, [10, 20]]
List = [5, 10, 15]
print("Initial List: ")
print(List)
Initial List: [5, 10, 15]
# Addition of Elements in the List
List.append(20)
List.append(25)
List.append(15)
print("List after Addition of Three elements: ")
print(List)
List after Addition of Three elements: [5, 10, 15, 20, 25, 15]
# Addition of Element at specific Position (using Insert Method)
List.insert(3, 12)
List.insert(0, 'Geeks')
print("List after performing Insert Operation: ")
print(List)
List after performing Insert Operation: ['Geeks', 5, 10, 15, 12, 20, 25, 15]
# Addition of multiple elements to the List at the end (using Extend Method)
List.extend([8, 'Geeks', 'Always'])
print("List after performing Extend Operation: ")
print(List)
List after performing Extend Operation: ['Geeks', 5, 10, 15, 12, 20, 25, 15, 8, 'Geeks', 'Always']
# You can reference a section of the list using a slice operator
List[3:7]
[15, 12, 20, 25]
List = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
print("Intial List: ")
print(List)
Intial List: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
# Removing elements from List using Remove() method
List.remove(5)
List.remove(6)
print("List after Removal of two elements: ")
print(List)
List after Removal of two elements: [1, 2, 3, 4, 7, 8, 9, 10, 11, 12]
x = List.pop()
print("List after popping an element: ")
print(List)
List after popping an element: [1, 2, 3, 4, 7, 8, 9, 10, 11]
print(x)
12
# Removing element at a specific location from the Set using the pop() method
y = List.pop(2)
print("List after popping a specific element: ")
print(List)
List after popping a specific element: [1, 2, 4, 7, 8, 9, 10, 11]
print(y)
3
# Use del if you do not need the removed value
del List[1]
print(List)
[1, 4, 7, 8, 9, 10, 11]
# To remove more than one element, you can use del with a slice index
del List[1:4]
print("List after deleting more than 1 element:")
print(List)
List after deleting more than 1 element: [1, 9, 10, 11]
s = 'spam'
t = list(s)
print(t)
['s', 'p', 'a', 'm']
s = 'pining for the fjords'
t = s.split()
print(t)
['pining', 'for', 'the', 'fjords']
# An optional argument called a delimiter specifies which characters to use as word boundaries
s = 'spam-spam-spam'
delimiter = '-'
s.split(delimiter)
['spam', 'spam', 'spam']
t = ['pining', 'for', 'the', 'fjords']
delimiter = ':'
delimiter.join(t)
'pining:for:the:fjords'
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
Empty Dictionary: {}
# Creating a Dictionary with Integer Keys
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print("Dictionary with the use of Integer Keys: ")
print(Dict)
Dictionary with the use of Integer Keys: {1: 'Geeks', 2: 'For', 3: 'Geeks'}
# Creating a Dictionary with dict() method
Dict = dict({1: 'Geeks', 2: 'For', 3:'Geeks'})
print("Dictionary with the use of dict(): ")
print(Dict)
Dictionary with the use of dict(): {1: 'Geeks', 2: 'For', 3: 'Geeks'}
# Creating a Dictionary with each item as a Pair
Dict = dict([(1, 'Geeks'), (2, 'For')])
print("Dictionary with each item as a pair: ")
print(Dict)
Dictionary with each item as a pair: {1: 'Geeks', 2: 'For'}
# Creating a Dictionary with Mixed keys
Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}
print("Dictionary with the use of Mixed Keys: ")
print(Dict)
Dictionary with the use of Mixed Keys: {'Name': 'Geeks', 1: [1, 2, 3, 4]}
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
Empty Dictionary: {}
# Adding elements one at a time
Dict[0] = 'Geeks'
Dict[2] = 'For'
Dict[3] = 1
print("Dictionary after adding 3 elements: ")
print(Dict)
Dictionary after adding 3 elements: {0: 'Geeks', 2: 'For', 3: 1}
# Updating existing Key's Value
Dict[2] = 'Welcome'
print("Updated key value: ")
print(Dict)
Updated key value: {0: 'Geeks', 2: 'Welcome', 3: 1}
# Creating a Dictionary
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
# accessing a element using key
print("Accessing a element using key:")
print(Dict['name'])
Accessing a element using key: For
# accessing a element using get() method
print("Accessing a element using get:")
print(Dict.get(3))
Accessing a element using get: Geeks
# The len function returns the number of key-value pairs
len(Dict)
3
# Initial Dictionary
Dict = { 5 : 'Welcome', 6 : 'To', 7 : 'Geeks',
'A' : {1 : 'Geeks', 2 : 'For', 3 : 'Geeks'},
'B' : {1 : 'Geeks', 2 : 'Life'}}
print("Initial Dictionary: ")
print(Dict)
Initial Dictionary: {5: 'Welcome', 6: 'To', 7: 'Geeks', 'A': {1: 'Geeks', 2: 'For', 3: 'Geeks'}, 'B': {1: 'Geeks', 2: 'Life'}}
# Deleting a Key value
del Dict[6]
print("Deleting a specific key: ")
print(Dict)
Deleting a specific key: {5: 'Welcome', 7: 'Geeks', 'A': {1: 'Geeks', 2: 'For', 3: 'Geeks'}, 'B': {1: 'Geeks', 2: 'Life'}}
# Deleting a Key using pop()
x = Dict.pop(5)
print("Popping specific element: ")
print(Dict)
Popping specific element: {7: 'Geeks', 'A': {1: 'Geeks', 2: 'For', 3: 'Geeks'}, 'B': {1: 'Geeks', 2: 'Life'}}
print(x)
Welcome
# Deleting an arbitrary Key-value pair using popitem()
y = Dict.popitem()
print("Pops an arbitrary key-value pair: ")
print(Dict)
Pops an arbitrary key-value pair: {7: 'Geeks', 'A': {1: 'Geeks', 2: 'For', 3: 'Geeks'}}
print(y)
('B', {1: 'Geeks', 2: 'Life'})
# Deleting entire Dictionary
Dict.clear()
print("Deleting Entire Dictionary: ")
print(Dict)
Deleting Entire Dictionary: {}
# You can loop through keys or values by using the keys and values functions
eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}
print("Looping through the Keys:")
for keys in eng2sp.keys():
print(keys)
print("\n")
print("Looping through the Values:")
for vals in eng2sp.values():
print(vals)
Looping through the Keys: one two three Looping through the Values: uno dos tres
# Creating an empty tuple
Tuple1 = ()
print("Initial empty Tuple: ")
print (Tuple1)
Initial empty Tuple: ()
# Creating a Tuple with the use of Strings
Tuple1 = ('Geeks', 'For')
print("Tuple with the use of String: ")
print(Tuple1)
Tuple with the use of String: ('Geeks', 'For')
# Creating a Tuple with the use of list
list1 = [1, 2, 4, 5, 6]
print("Tuple using List: ")
print(tuple(list1))
Tuple using List: (1, 2, 4, 5, 6)
# Creating a Tuple with the use of built-in function
Tuple1 = tuple('Geeks')
print("Tuple with the use of function: ")
print(Tuple1)
Tuple with the use of function: ('G', 'e', 'e', 'k', 's')
# Creating a Tuple with nested tuples
Tuple1 = (0, 1, 2, 3)
Tuple2 = ('python', 'geek')
Tuple3 = (Tuple1, Tuple2)
print("Tuple with nested tuples: ")
print(Tuple3)
Tuple with nested tuples: ((0, 1, 2, 3), ('python', 'geek'))
tuple1 = tuple([1, 2, 3, 4, 5])
# Accessing element using indexing
print("Frist element of tuple")
print(tuple1[0])
Frist element of tuple 1
# Accessing element from last (negative indexing)
print("Last element of tuple")
print(tuple1[-1])
print("Third last element of tuple")
print(tuple1[-3])
Last element of tuple 5 Third last element of tuple 3
tuple1 = tuple([1, 2, 3, 4, 5])
print("Initial tuple")
print(tuple1)
Initial tuple (1, 2, 3, 4, 5)
# Updating an element of a tuple
tuple1[0] = -1
print(tuple1)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-74-50fd515ea2c7> in <module>() 1 # Updating an element of a tuple ----> 2 tuple1[0] = -1 3 print(tuple1) TypeError: 'tuple' object does not support item assignment
# Deleting an element from a tuple
del tuple1[2]
print(tuple1)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-75-e2d0b616135c> in <module>() 1 # Deleting an element from a tuple ----> 2 del tuple1[2] 3 print(tuple1) TypeError: 'tuple' object doesn't support item deletion
# You can’t modify the elements of a tuple, but you can replace one tuple with another
tuple1 = ('A',) + tuple1[0:]
print(tuple1)
('A', 1, 2, 3, 4, 5)
Operator | Meaning | Example |
---|---|---|
+ (unary) | Unary Positive | +a |
+ (binary) | Addition | a + b |
- (unary) | Unary Negation | -a |
- (binary) | Subtraction | a - b |
* | Multiplication | a * b |
/ | Division | a / b |
% | Modulus | a % b |
// | Floor Division (also called Integer Divison | a // b |
** | Exponentiation | a ** b |
a = 4
b = 3
print(a * b)
print(a / b)
print(3 * a // b)
print(2 * a % b)
print(a ** b)
12 1.3333333333333333 4 2 64
Operator | Meaning | Example |
---|---|---|
== | Equal to | a == b |
!= | Not equal to | a != b |
< | Less than | a < b |
<= | Less than or equal to | a <= b |
> | Greater than | a > b |
>= | Greater than or equal to | a >= b |
a = 10
b = 20
print(a == b)
False
c = 'Hi'
d = 'hi'
print(c == d)
print( c < d)
print(ord('H'),ord('h'),ord('i'))
False True 72 104 105
'HI' < 'Hi'
True
Operator | Example | Meaning |
---|---|---|
not | not x | True if x is False False if x is True (Logically reverses the sense of x) |
or | x or y | True if either x or y is True False otherwise |
and | x and y | True if both x and y are True False otherwise |
x = 5
y = 10
print(x > 6 or y < 15)
print(x < 10 and y > 5)
True True
Syntax:
if condition:
statements
if ... else ...
conditional
if condition:
statments_1
else:
statements_2
x = 13
if x % 2 == 0:
print('x is even')
else:
print('x is odd')
x is odd
if ... elif ... else
conditional
if condition1:
statements_1
elif condition2:
statements_2
else
statements_3
y = 10
if x < y:
print('x is less than y')
elif x > y:
print('x is greater than y')
else:
print('x and y are equal')
x is greater than y
if x == y:
print('x and y are equal')
else:
if x < y:
print('x is less than y')
else:
print('x is greater than y')
x is greater than y
# Nested If
if 0 < x:
if x < 10:
print('x is a positive single-digit number.')
else:
print('x is not a positive single-digit number.')
x is not a positive single-digit number.
There may be a situation when you need to execute a block of code a number of times.
A loop statement allows us to execute a statement or group of statements multiple times.
for iterating_var in sequence:
statements(s)
fruits = ['banana', 'apple', 'mango']
for fruit in fruits:
print ('Current fruit :', fruit)
Current fruit : banana Current fruit : apple Current fruit : mango
for letter in 'Hola':
print('Current Letter :', letter)
Current Letter : H Current Letter : o Current Letter : l Current Letter : a
range(5)
range(0, 5)
list(range(5))
[0, 1, 2, 3, 4]
for var in list(range(5)):
print(var)
0 1 2 3 4
for index in range(len(fruits)):
print ('Current fruit :', fruits[index])
Current fruit : banana Current fruit : apple Current fruit : mango
while expression:
statement(s)
number = int(input('Enter any integer: '))
fact = count = 1
while (count <= number ):
fact = count * fact
count += 1
print('Factorial of %d is %d' % (number, fact))
Enter any integer: 6 Factorial of 6 is 720
count = 0
while count < 5:
print (count, " is less than 5")
count = count + 1
else:
print (count, " is not less than 5")
0 is less than 5 1 is less than 5 2 is less than 5 3 is less than 5 4 is less than 5 5 is not less than 5
Python supports the following control statements.
s = 'geeksforgeeks'
# Using for loop
for letter in s:
print(letter)
# break the loop as soon it sees 'e' or 's'
if letter == 'e' or letter == 's':
break
print("Out of for loop")
g e Out of for loop
for i in range(1, 11):
# If i is equals to 6, continue to next iteration without printing
if i == 6:
continue
else:
# otherwise print the value of i
print(i)
1 2 3 4 5 7 8 9 10
for letter in 'geeksforgeeks':
pass
print ('Last Letter :', letter)
Last Letter : s
x = 10
print(x)
10
Function | Description |
---|---|
ascii() | Returns a string containing a printable representation of an object |
bin() | Converts an integer to a binary string |
bool() | Converts an argument to a Boolean value |
callable() | Returns whether the object is callable (i.e., some kind of function) |
chr() | Returns string representation of character given by integer argument |
complex() | Returns a complex number constructed from arguments |
float() | Returns a floating-point object constructed from a number or string |
hex() | Converts an integer to a hexadecimal string |
int() | Returns an integer object constructed from a number or string |
oct() | Converts an integer to an octal string |
ord() | Returns integer representation of a character |
repr() | Returns a string containing a printable representation of an object |
str() | Returns a string version of an object |
type() | Returns the type of an object or creates a new type object |
Function | Description |
---|---|
abs() | Returns absolute value of a number |
divmod() | Returns quotient and remainder of integer division |
max() | Returns the largest of the given arguments or items in an iterable |
min() | Returns the smallest of the given arguments or items in an iterable |
pow() | Raises a number to a power |
round() | Rounds a floating-point value |
sum() | Sums the items of an iterable |
import math
degrees = 45
radians = degrees / 360.0 * 2 * math.pi
math.sin(radians)
0.7071067811865476
Function | Description |
---|---|
all() | Returns True if all elements of an iterable are true |
any() | Returns True if any elements of an iterable are true |
enumerate() | Returns a list of tuples containing indices and values from an iterable |
filter() | Filters elements from an iterable |
iter() | Returns an iterator object |
len() | Returns the length of an object |
map() | Applies a function to every item of an iterable |
next() | Retrieves the next item from an iterator |
range() | Generates a range of integer values |
reversed() | Returns a reverse iterator |
slice() | Returns a slice object |
sorted() | Returns a sorted list from an iterable |
zip() | Creates an iterator that aggregates elements from iterables |
# A simple Python function to check whether x is even or odd
def evenOdd( x ):
if (x % 2 == 0):
print ("even")
else:
print ("odd")
# Driver code
evenOdd(2)
evenOdd(3)
even odd
open(filename, mode)
mode | description |
---|---|
r | Opens a file for reading only, default mode |
w | Opens a file for writing only |
a | Opens a file for appending only. File pointer is at end of file |
rb | Opens a file for reading only in binary |
wb | Opens a file for writing only in binary |
fout = open('output.txt', 'w')
print(fout)
<_io.TextIOWrapper name='output.txt' mode='w' encoding='cp1252'>
line1 = "This here's the wattle,\n"
fout.write(line1)
24
line2 = "the emblem of our land.\n"
fout.write(line2)
24
# When you are done writing, you have to close the file.
fout.close()
Method | Description |
---|---|
read([number]) | Return specified number of characters from the file. if omitted it will read the entire contents of the file. |
readline() | Return the next line of the file. |
readlines() | Read all the lines as a list of strings in the file |
# Reading all the data at once
f = open('output.txt', 'r')
f.read()
"This here's the wattle,\nthe emblem of our land.\n"
f.close()
# Reading all lines as an array
f = open('output.txt', 'r')
f.readlines()
["This here's the wattle,\n", 'the emblem of our land.\n']
f.close()
# Reading only 1 line
f = open('output.txt', 'r')
f.readline()
"This here's the wattle,\n"
f.close()
# Iterating through the file using file pointer
f = open('output.txt', 'r')
for line in f:
print(line)
f.close()
This here's the wattle, the emblem of our land.
import numpy as np
a = np.array([2,3,4])
print(a, a.dtype)
[2 3 4] int32
# array transforms sequences of sequences into two-dimensional arrays,
# sequences of sequences of sequences into three-dimensional arrays
b = np.array([(1.2, 3.5, 5.1),(4.1,6.1,0.5)])
print(b, b.dtype)
print(b.shape)
[[1.2 3.5 5.1] [4.1 6.1 0.5]] float64 (2, 3)
# The type of the array can also be explicitly specified at creation time
c = np.array( [ [1,2], [3,4] ], dtype=complex )
c
array([[1.+0.j, 2.+0.j], [3.+0.j, 4.+0.j]])
print('Zeros: ',np.zeros( (3,4) ))
print('Ones', np.ones( (2,4), dtype=np.float64 ))
print('Empty', np.empty( (2,3) ))
Zeros: [[0. 0. 0. 0.] [0. 0. 0. 0.] [0. 0. 0. 0.]] Ones [[1. 1. 1. 1.] [1. 1. 1. 1.]] Empty [[1.2 3.5 5.1] [4.1 6.1 0.5]]
# NumPy provides a function analogous to range that returns arrays instead of lists.
np.arange( 10, 30, 5 )
array([10, 15, 20, 25])
# The reshape function can be used to convert an array into a matrix
a = np.arange(15).reshape(3, 5)
a
array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14]])
print("array dimensions: ", a.shape)
print("number of dimensions: ", a.ndim)
print("element types: ", a.dtype.name)
print("size of elements: ", a.itemsize)
print("total number of elements: ",a.size)
print("type of object:",type(a))
array dimensions: (3, 5) number of dimensions: 2 element types: int32 size of elements: 4 total number of elements: 15 type of object: <class 'numpy.ndarray'>
# Arithmetic operators on arrays apply elementwise
a = np.array( [20,30,40,50] )
b = np.arange( 4 )
print('a: ', a)
print('b:', b)
print('a-b:', a-b)
print('B**2', b**2)
print('10*sin(a): ', 10*np.sin(a))
print('Which elements of a < 35:', a<35)
print('Elements of a < 35: ',a[a<35])
a: [20 30 40 50] b: [0 1 2 3] a-b: [20 29 38 47] B**2 [0 1 4 9] 10*sin(a): [ 9.12945251 -9.88031624 7.4511316 -2.62374854] Which elements of a < 35: [ True True False False] Elements of a < 35: [20 30]
A = np.array( [[1,1], [0,1]] )
B = np.array( [[2,0], [3,4]] )
print('A = ', A)
print('B = ', B)
print('A*B = ', A*B)
print('A . B = ', A.dot(B))
print('Numpy A. B = ', np.dot(A, B))
A = [[1 1] [0 1]] B = [[2 0] [3 4]] A*B = [[2 0] [0 4]] A . B = [[5 4] [3 4]] Numpy A. B = [[5 4] [3 4]]