Giter VIP home page Giter VIP logo

1day-of-python-learning-tutorial's Introduction

1 Day of Python Learning Tutorial

Contents


Introduction

What is Python?

Python is an interpretedhigh-level and general-purpose programming language. It was created by

Guido-portrait-2014-drc.jpg

Guido van Rossum, and released in 1991. Python got its name from a BBC comedy series from seventies - "Monty Python's Flying Circus".

 

Publications

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?

  • It is a general purpose object oriented programming language which can be used for both scientific and non scientific programming.
  • It is a platform independent programming language. It works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
  • Python has a simple syntax similar to the English language with vast library of add-on modules. It has syntax that allows developers to write programs with fewer lines than some other programming languages.
  • It is excellent for beginners as the language is interpreted, hence gives immediate results.
  • The programs written in Python are easily readable and understandable. It is suitable as an extension language for customizable applications. It is easy to learn and use.
  • Python can be treated in a procedural way, an object-oriented way or a functional way. It is free to use.

The language is used by companies in real revenue generating products, such as:

  • In operations of Google search engine, youtube, etc.
  • BitTorrent peer to peer file sharing is written using python.
  • Intel, Cisco, HP, IBM, etc use Python for hardware testing.
  • Maya provides a python scripting API
  • i-Robot uses python to develop commercial Robot for space exploration and military defense.
  • NASA and others use python for their scientific programming task.

 

print("hello"*3)

hellohellohello

repetition

print("hello"+"world")

helloworld

concatenation

print("hello"[0])

h

indexing

print("hello"[-1])

o

from end

print("hello"[1:4])

ell

slicing

print(len("hello"))

5

size


Python Indentation

Code:

if 4 > 3:
  print("Four is greater than three!") 

Output on the screen:

 Four is greater than three! 


Code:

if 4 > 3:
print("Four is greater than three!") 

Output on the screen:

 print("Four is greater than three!")
       ^
IndentationError: expected an indented block 

↑Back

Python Comments

Code:

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

Output on the screen:

 Hello, World! 

↑Back

Python Variables

Code:

a = 5
b = "Python"
print(a)
print(b) 

Output on the screen:

 
5
Python 


Code:

a, b, c = "Tree", "Chair", "bench" 
print(a)
print(b) 
print(c) 

Output on the screen:

Tree
Chair
bench 


Code:

a = b = c = "Chair" 
print(a)
print(b) 
print(c)

Output on the screen:

Chair
Chair
Chair 


Code:

a = "easy to understand" 
print("Python is " + a)

Output on the screen:

 Python is easy to understand 


Code:

a = 4
b = 3
print(a + b)

Output on the screen:

 7 


Code:

a = 6
b = "Python" 
print(a + b)

Output on the screen:

 TypeError: unsupported operand type(s) for +: 'int' and 'str' 


Code:

a = "Hello"
b = "World"
c = a + b
print(c)

Output on the screen:

 HelloWorld 


Code:

a = "Hello"
b = "World"
c = a + " " + b
print(c)

Output on the screen:

 Hello World 


Code:

a = "easy to understand"

def myfunc(): 
 print("Python is " + a)

myfunc()

Output on the screen:

 Python is easy to understand 

↑Back

Python Data Types

Code:

# Print the data type of the variable a:
a = 5 
print(type(a))

Output on the screen:

<class 'int'>


 

Value of a

 

Data Type

 

a = "Hello World"

 

str

 

a = 20

 

int

 

a = 20.5

 

float

 

a = 1k

 

complex

 

a = ["Tree", "Chair", "bench"]

 

list

 

a = ("Tree", "Chair", "bench")

 

tuple

 

a = range(6)

 

range

 

a = {"name" : "Guido van Rossum", "age" : 65}

 

dict

 

a = {"Tree", "Chair", "bench"}

 

set

 

a = frozenset({"Tree", "Chair", "bench"})

 

frozenset

 

a = True

 

bool

 

a = b"Hello"

 

bytes

 

a = bytearray(5)

 

bytearray

 

a = memoryview(bytes(5))

 

memoryview


↑Back

Python Numbers

Code:

# Display a random number between 1 and 9:

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

Output on the screen:

 7 

↑Back

Python Casting

Code:

a = int(1)   # a will be 1
b = int(2.8) # b will be 2
c = int("3") # c will be 3 
print(a)
print(b)
print(c)

Output on the screen:

 
1
2
3 


Code:

a = float(1)     # a will be 1.0
b = float(2.8)   # b will be 2.8
c = float("3")   # c will be 3.0
print(a)
print(b)
print(c)

Output on the screen:

 
1.0
2.8
3.0 

Code:

a = str("s1") # a will be s1
b = str(2)    # b will be 2
c = str(3.0)  # c will be 3.0
print(a)
print(b)
print(c)

Output on the screen:

 
s1
2
3.0 

↑Back

Python Strings

Code:

a = "Hello" 
b = """Python """ 
c = '''Python''' 
print(a)
print(b)
print(c)

Output on the screen:

 
Hello
Python 
Python 


Code:

# Replace a string with another string

a = "Ear"
print(a.replace("E", "F"))

Output on the screen:

Far

Code:

# Remove whitespace from the beginning or at the end of a string

a = " Hear, Far! "
print(a.strip())

Output on the screen:

Hear, Far!

Code:

# Split a string into substrings
x = "Hear, Far!"
y = x.split(",")
print(y)

Output on the screen:

['Hear', ' Far!']

Code:

# Get the character at position 0
a = "Hello, World!"
print(a[0])

Output on the screen:

 
H 

Code:

for a in "Chair":
  print(a) 

Output on the screen:

 
C
h
a
i
r

Code:

# get the length of a string
a = "Hello"
print(len(a))

Output on the screen:

 
5

Code:

# Check if "was" is present in the following text:
txt = "Albert Einstein was a German-born theoretical physicist."
print("was" in txt)

Output on the screen:

 
True

Code:

# Print only if "Einstein" is present:
txt = "Albert Einstein was a German-born theoretical physicist."
if "Einstein" in txt:
  print("Yes, 'Einstein' is present.")

Output on the screen:

 
Yes, 'Einstein' is present.

Code:

# Check if "newton" is NOT present in the following text:
txt = "Albert Einstein was a German-born theoretical physicist."
print("newton" not in txt)

Output on the screen:

 
True

Code:

# print only if "newton" is NOT present:
txt = "Albert Einstein was a German-born theoretical physicist."
if "newton" not in txt:
  print("Yes, 'newton' is NOT present.")

Output on the screen:

 
Yes, 'newton' is NOT present.

0 1 2 3 4 5
N E W T O N
-6 -5 -4 -3 -2 -1
N E W T O N

Code:

b = "NEWTON"
print(b[4])

Output on the screen:

 
O

Code:

b = "NEWTON"
print(b[-3])

Output on the screen:

 
T

Code:

b = "NEWTON"
print(b[2:5])

Output on the screen:

 
WTO

Code:

b = "NEWTON"
print(b[:5])
print(b[2:])

Output on the screen:

 
NEWTO
WTON

Code:

# count the number of times the character 'N' appears:
b = "NEWTON"
print(b.count("N"))

Output on the screen:

 
2

Code:

b = "Albert Einstein was a German-born theoretical physicist who developed the theory of relativity."
print(b.count("of"))

Output on the screen:

 
1

Code:

a = "ALBERT EINSTEIN"
print(a.lower())

b = "albert einstein"
print(b.upper())

Output on the screen:

 
albert einstein
ALBERT EINSTEIN

↑Back

Python Booleans

Code:

print(10 > 9)
print(10 == 9)
print(10 < 9)

Output on the screen:

 
True 
False 
False 


↑Back

Python Operators

  • Arithmetic Operators

 

 

Operator

 

Name

 

Example

 

+

 

Addition

 

x + y

 

-

 

Subtraction

 

x - y

 

*

 

Multiplication

 

x * y

 

/

 

Division

 

x / y

 

%

 

Modulus

 

x % y

 

**

 

Exponentiation

 

x ** y

 

//

 

Floor division

 

x // y


  • Assignment Operators

 

Operator

 

Example

 

Same As

 

=

 

x = 5

 

x = 5

 

+=

 

x += 3

 

x = x + 3

 

-=

 

x -= 3

 

x = x - 3

 

*=

 

x *= 3

 

x = x * 3

 

/=

 

x /= 3

 

x = x / 3

 

%=

 

x %= 3

 

x = x % 3

 

//=

 

x //= 3

 

x = x // 3

 

**=

 

x **= 3

 

x = x ** 3

 

&=

 

x &= 3

 

x = x & 3

 

|=

 

x |= 3

 

x = x | 3

 

^=

 

x ^= 3

 

x = x ^ 3

 

>>=

 

x >>= 3

 

x = x >> 3

 

<<=

 

x <<= 3

 

x = x << 3


  • Comparison Operators

 

 

Operator

 

Name

 

Example

 

==

 

Equal

 

x == y

 

!=

 

Not equal

 

x != y

 

 

Greater than

 

x > y

 

 

Less than

 

x < y

 

>=

Greater than or equal to

 x>=y

 

<=

Less than or equal to

x<=y

 

  • Logical Operators

 

 

Operator

 

Description

 

Example

 

and

 

Returns True if both statements are true

 

x < 5 and  x < 10

 

or

 

Returns True if one of the statements is true

 

x < 5 or x < 4

 

not

 

Returns False if the result is true

 

not(x < 5 and x < 10)


  • Identity Operators

 

Operator Description Example

is 

 

Returns True if both variables are the same object x is y

is not

 

Returns True if both variables are not the same object x is not y

  • Membership Operators

 

Operator Description Example
in  Returns True if a sequence with the specified value is present in the object x in y
not in Returns True if a sequence with the specified value is not present in the object x not in y

  • Python Bitwise Operators

 

Operator Name Description
AND Sets each bit to 1 if both bits are 1
| OR Sets each bit to 1 if one of two bits is 1
 ^ XOR Sets each bit to 1 if only one of two bits is 1
NOT Inverts all the bits
<< Zero fill left shift Shift left by pushing zeros in from the right and let the leftmost bits fall off
>> Signed right shift Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off

Code:

a = 2
b = 4

print(a ** b) #same as 2*2*2*2

Output on the screen:

 
16

Code:

x = 4
y = 2

print(x % y)

Output on the screen:

 
0

Code:

#the floor division // rounds the result down to the nearest whole number

a = 17
b = 2

print(a // b)

Output on the screen:

 
8

Code:

a = 4

print(a > 3 and a < 9)
# returns True because 4 is greater than 3 AND 4 is less than 9

Output on the screen:

 
True

Code:

a = 5

print(a > 3 or a < 4)

# returns True because one of the conditions are true (5 is greater than 3, but 5 is not less than 4)

Output on the screen:

 
True

Code:

a = ["Chair", "bench"]

print("Car" not in a)

# returns True because a sequence with the value "Car" is not in the list

Output on the screen:

 
True

Code:

a = 6

a += 2 # same as a = a + 2

print(a)  

Output on the screen:

 
8

↑Back

Python Modules

Code:

# importing the module 
import wikipedia  
  
# finding result for the search 
# sentences = 3 refers to numbers of line 
result = wikipedia.summary("Python (programming language)", sentences = 3)  
  
# printing the result 
print(result)  

Output on the screen:

Python is an interpreted, high-level and general-purpose programming language. 
Python's design philosophy emphasizes code readability with its notable use of significant whitespace. 
Its language constructs and object-oriented approach aim to help programmers write clear, logical code 
for small and large-scale projects.Python is dynamically-typed and garbage-collected.

Code:

# importing the module 
import wikipedia 
  
# getting suggestions 
result = wikipedia.search("Python", results = 4) 
  
# printing the result 
print(result) 

Output on the screen:

['Python (programming language)', 'Python', 'Monty Python', 'Burmese python']

↑Back

Python Lists

Code:

thislist = ["Car", "bench", "Chair"] 
print(thislist) 

Output on the screen:

 
['Car', 'bench', 'Chair']

Code:

thislist = ["Car", "bench", "Chair"] 
print(thislist[1])

Output on the screen:

 
bench

Code:

# Print the number of items in the list:
thislist = ["Car", "bench", "Chair"]
print(len(thislist))

Output on the screen:

 
3

Code:

thislist = ["Car", "bench", "Chair"]
print(thislist[-1])

Output on the screen:

 
Chair

Code:

thislist = ["Chair", "bench", "Car"] 
for a in thislist:
  print(a)

Output on the screen:

 
Chair
bench
Car

Code:

# print the data type of a list
a = ["Chair", "bench", "Car"]

print(type(a))

Output on the screen:

<class 'list'>


Code:

thislist = ["Chair", "bench", "Car"] 
if "Chair" in thislist:
  print("Yes, 'Chair' is in the list")

Output on the screen:

 
Yes, 'Chair' is in the list

Code:

thislist = ["Car", "bench", "Chair"] 
thislist[1] = "book"

print(thislist)

Output on the screen:

 
['Car', 'book', 'Chair']

Code:

# add an item to the end of the list

thislist = ["Chair", "bench", "Car"] 
thislist.append("book") 
print(thislist)

Output on the screen:

 
['Chair', 'bench', 'Car', 'book']

Code:

thislist = ["book", "Car", "bench"]
thislist.remove("Car") 
print(thislist)

Output on the screen:

 
['book', 'bench']

Code:

thislist = ["book", "Car", "bench"]
thislist.clear()
print(thislist)

Output on the screen:

 
[]

Code:

a = ["a", "b", "c"] 
b = [1, 2, 3]

c = a + b 
print(c)

Output on the screen:

 
['a', 'b', 'c', 1, 2, 3]

Code:

# Append list2 into list1

list1 = ["a", "b", "c"] 
list2 = [1, 2, 3]

for x in list2: 
  list1.append(x)

print(list1)

Output on the screen:

 
['a', 'b', 'c', 1, 2, 3]

Code:

# copy of a list with the copy() method

thislist = ["car", "bench", "chalk"] 
mylist = thislist.copy()
print(mylist)

Output on the screen:

 
['car', 'bench', 'chalk']

Code:

# copy of a list with the list() method

thislist = ["car", "bench", "chalk"] 
mylist = list(thislist)
print(mylist)

Output on the screen:

 
['car', 'bench', 'chalk']

Code:

# add list2 at the end of list1 using extend() method

list1 = ["a", "b", "c"] 
list2 = [1, 2, 3]

list1.extend(list2)
print(list1)

Output on the screen:

 
['a', 'b', 'c', 1, 2, 3]

  • Python List Methods

 

Method

 

Description

 

append()

 

Adds an element at the end of the list

 

clear()

 

Removes all the elements from the list

 

copy()

 

Returns a copy of the list

 

count()

 

Returns the number of elements with the specified value

 

extend()

 

Add the elements of a list (or any iterable), to the end of the current list

 

index()

 

Returns the index of the first element with the specified value

 

insert()

 

Adds an element at the specified position

 

pop()

 

Removes the element at the specified position

 

remove()

 

Removes the item with the specified value

 

reverse()

 

Reverses the order of the list

 

sort()

 

Sorts the list


↑Back

Python Tuples

Code:

thistuple = ("chair", "bench", "car") 
print(thistuple)
  

Output on the screen:

 
('chair', 'bench', 'car')

Code:

thistuple = ("chair", "bench", "car") 
print(thistuple[1])
  

Output on the screen:

 
bench

Code:

thistuple = ("chair", "bench", "car") 
print(thistuple[-1])
  

Output on the screen:

 
car

Code:

thistuple = ("chair", "bench", "car") 
for x in thistuple:
  print(x)

  

Output on the screen:

 
chair
bench
car

Code:

thistuple = ("chair", "bench", "car") 
if "car" in thistuple:
  print("Yes, 'car' is in the tuple")

Output on the screen:

 
Yes, 'car' is in the tuple

Code:

# Print the number of items in the tuple:
thistuple = ("chair", "bench", "car") 
print(len(thistuple))

Output on the screen:

 
3

Code:

tuple1 = ("a", "b", "c") 
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2 
print(tuple3)

Output on the screen:

 
('a', 'b', 'c', 1, 2, 3)

Code:

x = ("chair", "bench", "car") 
y = list(x)
y[1] = "book" 
x = tuple(y)
print(x)

Output on the screen:

 
('chair', 'book', 'car')


  • Python Tuple Methods

 

 

Method

 

Description

 

count()

 

Returns the number of times a specified value occurs in a tuple

 

index()

 

Searches the tuple for a specified value and returns the position of where it was found


↑Back

Python Sets

Code:

thisset = {"chair", "bench", "car"} 
print(thisset)

Output on the screen:

 
{'bench', 'car', 'chair'}

Code:

thisset = {"chair", "bench", "car"} 
print("book" in thisset)

Output on the screen:

 
False

Code:

thisset = {"chair", "bench", "car"} 
thisset.add("book")
print(thisset)

Output on the screen:

 
{'bench', 'book', 'car', 'chair'}

Code:

thisset = {"chair", "bench", "car"} 
thisset.update(["chalk", "pencil", "table"]) 
print(thisset)

Output on the screen:

 
{'table', 'chalk', 'bench', 'pencil', 'car', 'chair'}

Code:

# Get the number of items in a set:
thisset = {"chair", "bench", "car"} 
print(len(thisset))

Output on the screen:

 
3

Code:

# print the data type of a set
thisset = {"chair", "bench", "car"} 
print(type(thisset))

Output on the screen:

<class 'set'>


Code:

thisset = {"chair", "bench", "car"} 
thisset.remove("bench")  
print(thisset)

Output on the screen:

{'car', 'chair'} 

Code:

thisset = {"chair", "bench", "car"} 
thisset.discard("bench")   
print(thisset)

Output on the screen:

{'car', 'chair'} 

Code:

thisset = {"chair", "bench", "car"} 
thisset.clear()
print(thisset)

Output on the screen:

 set() 

Code:

# The union() method returns a new set with all items from both sets:
set1 = {"a", "b", "c"} 
set2 = {1, 2, 3}
set3 = set1.union(set2) 
print(set3)

Output on the screen:

 {1, 2, 3, 'a', 'b', 'c'} 

Code:

# The update() method inserts the items in set2 into set1:
set1 = {"a", "b", "c"} 
set2 = {1, 2, 3}
set1.update(set2) 
print(set1)

Output on the screen:

 {1, 2, 3, 'a', 'b', 'c'} 


  •  Python Set Methods

 

 

Method

 

Description

 

add()

 

Adds an element to the set

 

clear()

 

Removes all the elements from the set

 

copy()

 

Returns a copy of the set

 

difference()

 

Returns a set containing the difference between two or more sets

 

difference_update()

 

Removes the items in this set that are also included in another, specified set

 

discard()

 

Remove the specified item

 

intersection()

 

Returns a set, that is the intersection of two other sets

 

intersection_update()

 

Removes the items in this set that are not present in other, specified set(s)

 

isdisjoint()

 

Returns whether two sets have a intersection or not

 

issubset()

 

Returns whether another set contains this set or not

 

issuperset()

 

Returns whether this set contains another set or not

 

pop()

 

Removes an element from the set

 

remove()

 

Removes the specified element

 

symmetric_difference()

 

Returns a set with the symmetric differences of two sets

 

symmetric_difference_update()

 

inserts the symmetric differences from this set and another

 

union()

 

Return a set containing the union of sets

 

update()

 

Update the set with the union of this set and others


↑Back

Python Dictionaries

Code:

thisdict={
  "Name": "Albert Einstein",
  "Theory": "Theory of relativity",
  "year": 1905
}
print(thisdict)

Output on the screen:

 {'Name': 'Albert Einstein', 'Theory': 'Theory of relativity', 'year': 1905} 

Code:

thisdict={
  "Name": "Albert Einstein",
  "Theory": "Theory of relativity",
  "year": 1905
}
x = thisdict["Name"] 
print(x)

Output on the screen:

 Albert Einstein 

Code:

thisdict={
  "Name": "Albert Einstein",
  "Theory": "Theory of relativity",
  "year": 1905
}
thisdict["year"] = 2020
print(thisdict)

Output on the screen:

 {'Name': 'Albert Einstein', 'Theory': 'Theory of relativity', 'year': 2020} 

Code:

thisdict={
  "Name": "Albert Einstein",
  "Theory": "Theory of relativity",
  "year": 1905
}
for x in thisdict: 
 print(x)

Output on the screen:

 
Name
Theory
year 

Code:

thisdict={
  "Name": "Albert Einstein",
  "Theory": "Theory of relativity",
  "year": 1905
}
for x in thisdict: 
 print(thisdict[x])

Output on the screen:

 
Albert Einstein
Theory of relativity
1905 

Code:

thisdict={
  "Name": "Albert Einstein",
  "Theory": "Theory of relativity",
  "year": 1905
}
for x in thisdict.values(): 
 print(x)

Output on the screen:

 
Albert Einstein
Theory of relativity
1905 

Code:

thisdict={
  "Name": "Albert Einstein",
  "Theory": "Theory of relativity",
  "year": 1905
}
for x, y in thisdict.items(): 
 print(x, y)

Output on the screen:

 
Name Albert Einstein
Theory Theory of relativity
year 1905 

Code:

thisdict={
  "Name": "Albert Einstein",
  "Theory": "Theory of relativity",
  "year": 1905
}
if "Theory" in thisdict:
  print("Yes, 'Theory' is one of the keys in the thisdict dictionary.")

Output on the screen:

 
Yes, 'Theory' is one of the keys in the thisdict dictionary. 

Code:

# Print the number of items in the dictionary:
thisdict={
  "Name": "Albert Einstein",
  "Theory": "Theory of relativity",
  "year": 1905
}
print(len(thisdict))

Output on the screen:

 
3 

Code:

thisdict={
  "Name": "Albert Einstein",
  "Theory": "Theory of relativity",
  "year": 1905
}
thisdict["best known"] = "mass–energy equivalence" 
print(thisdict)

Output on the screen:

 
{'Name': 'Albert Einstein', 'Theory': 'Theory of relativity', 'year': 1905, 'best known': 'mass–energy equivalence'} 

Code:

thisdict={
  "Name": "Albert Einstein",
  "Theory": "Theory of relativity",
  "year": 1905
}
del thisdict["year"] 
print(thisdict)

Output on the screen:

 
{'Name': 'Albert Einstein', 'Theory': 'Theory of relativity'} 

Code:

thisdict={
  "Name": "Albert Einstein",
  "Theory": "Theory of relativity",
  "year": 1905
}
thisdict.clear() 
print(thisdict)

Output on the screen:

 
{} 


  • Python Dictionary Methods

 

 

Method

 

Description

 

clear()

 

Removes all the elements from the dictionary

 

copy()

 

Returns a copy of the dictionary

 

fromkeys()

 

Returns a dictionary with the specified keys and value

 

get()

 

Returns the value of the specified key

 

items()

 

Returns a list containing a tuple for each key value pair

 

keys()

 

Returns a list containing the dictionary's keys

 

pop()

 

Removes the element with the specified key

 

popitem()

 

Removes the last inserted key-value pair

 

setdefault()

 

Returns the value of the specified key. If the key does not exist: insert the key, with the specified value

 

update()

 

Updates the dictionary with the specified key-value pairs

 

values()

 

Returns a list of all the values in the dictionary


↑Back

Python Lambda

Code:

# Add 10 to argument a, and return the result:
x = lambda a: a + 10 
print(x(5))

Output on the screen:

 
15 

Code:

# Multiply argument a with argument b and return the result:
x = lambda a, b: a * b 
print(x(5, 6))

Output on the screen:

 
30 

Code:

# Summarize argument a, b, and c and return the result:
x = lambda a, b, c: a + b + c
print(x(5, 6, 2))

Output on the screen:

 
13 

Code:

def myfunc(n):
  return lambda a : a * n

mydoubler = myfunc(2)

print(mydoubler(11))

Output on the screen:

 
22 

↑Back

Python Arrays

Code:

# Create an array containing scientists names:
scientists = ["Aristotle", "Francis Bacon", "Niels Bohr"]
print(scientists)

Output on the screen:

 
['Aristotle', 'Francis Bacon', 'Niels Bohr']

Code:

# Get the value of the first array:
scientists = ["Aristotle", "Francis Bacon", "Niels Bohr"]

x = scientists[0]
print(x)

Output on the screen:

 
Aristotle

Code:

# Modify the value of the first array:
scientists = ["Aristotle", "Francis Bacon", "Niels Bohr"]

scientists[0] = "Newton"
print(scientists)

Output on the screen:

 
['Newton', 'Francis Bacon', 'Niels Bohr'] 

Code:

# Return the number of names in the scientists array:
scientists = ["Aristotle", "Francis Bacon", "Niels Bohr"]

x = len(scientists)
print(x)

Output on the screen:

 
3 

Code:

scientists = ["Aristotle", "Francis Bacon", "Niels Bohr"]

for x in scientists: 
   print(x)

Output on the screen:

 
Aristotle
Francis Bacon
Niels Bohr 

Code:

# Add one more name to the scientists array:
scientists = ["Aristotle", "Francis Bacon", "Niels Bohr"]
scientists.append("Newton") 
print(scientists)

Output on the screen:

 
['Aristotle', 'Francis Bacon', 'Niels Bohr', 'Newton'] 

Code:

scientists = ["Aristotle", "Francis Bacon", "Niels Bohr"]
scientists.remove("Niels Bohr") 
print(scientists)

Output on the screen:

 
['Aristotle', 'Francis Bacon'] 

Code:

# Delete the second name in the scientists array:
scientists = ["Aristotle", "Francis Bacon", "Niels Bohr"]
scientists.pop(1)
 
print(scientists)

Output on the screen:

 
['Aristotle', 'Niels Bohr'] 


  • Python Array Methods

 

 

Method

 

Description

 

append()

 

Adds an element at the end of the list

 

clear()

 

Removes all the elements from the list

 

copy()

 

Returns a copy of the list

 

count()

 

Returns the number of elements with the specified value

 

extend()

 

Add the elements of a list (or any iterable), to the end of the current list

 

index()

 

Returns the index of the first element with the specified value

 

insert()

 

Adds an element at the specified position

 

pop()

 

Removes the element at the specified position

 

remove()

 

Removes the first item with the specified value

 

reverse()

 

Reverses the order of the list

 

sort()

 

Sorts the list


↑Back

Python Classes

Code:

class MyClass: x = 5
p1 = MyClass() 
print(p1.x)

Output on the screen:

 
5 

Code:

# Create a class named Person, 
# use the __init__() function to assign values 
# for name and age:

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

p1 = Person("Albert", 56)

print(p1.name)
print(p1.age)

Output on the screen:

Albert
56 

↑Back

Python Iterators

Code:

mytuple = ("bench", "pencil", "chalk")
myit = iter(mytuple)

print(next(myit))
print(next(myit))
print(next(myit))

Output on the screen:

 
bench
pencil
chalk 

Code:

mystr = "newton"
myit = iter(mystr)

print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))

Output on the screen:

 
n
e
w
t
o
n 

Code:

mytuple = ("bench", "board", "book")

for x in mytuple: 
   print(x)

Output on the screen:

 
bench
board
book

Code:

mystr = "newton"

for x in mystr: 
    print(x)

Output on the screen:

 
n
e
w
t
o
n

↑Back

Python Math

Code:

a = min(5, 10, 25)
b = max(5, 10, 25)

print(a)
print(b)

Output on the screen:

 
5
25

Code:

c = abs(-6.35)

print(c)

Output on the screen:

 
6.35

Code:

x = pow(2, 3)

print(x)

Output on the screen:

 
8

Code:

# Import math library
import math

x = math.sqrt(4)

print(x)

Output on the screen:

 
2

Code:

import math

#Round a number upward to its nearest integer
a = math.ceil(2.4)

#Round a number downward to its nearest integer
b = math.floor(2.4)

print(a)
print(b)

Output on the screen:

 
3
2

Code:

import math

a = math.pi

print(a)

Output on the screen:

 
3.141592653589793


  • Math Methods

Method Description
math.acos() Returns the arc cosine of a number
math.acosh() Returns the inverse hyperbolic cosine of a number
math.asin() Returns the arc sine of a number
math.asinh() Returns the inverse hyperbolic sine of a number
math.atan() Returns the arc tangent of a number in radians
math.atan2() Returns the arc tangent of y/x in radians
math.atanh() Returns the inverse hyperbolic tangent of a number
math.ceil() Rounds a number up to the nearest integer
math.comb() Returns the number of ways to choose k items from n items without repetition and order
math.copysign() Returns a float consisting of the value of the first parameter and the sign of the second parameter
math.cos() Returns the cosine of a number
math.cosh() Returns the hyperbolic cosine of a number
math.degrees() Converts an angle from radians to degrees
math.dist() Returns the Euclidean distance between two points (p and q), where p and q are the coordinates of that point
math.erf() Returns the error function of a number
math.erfc() Returns the complementary error function of a number
math.exp() Returns E raised to the power of x
math.expm1() Returns Ex - 1
math.fabs() Returns the absolute value of a number
math.factorial() Returns the factorial of a number
math.floor() Rounds a number down to the nearest integer
math.fmod() Returns the remainder of x/y
math.frexp() Returns the mantissa and the exponent, of a specified number
math.fsum() Returns the sum of all items in any iterable (tuples, arrays, lists, etc.)
math.gamma() Returns the gamma function at x
math.gcd() Returns the greatest common divisor of two integers
math.hypot() Returns the Euclidean norm
math.isclose() Checks whether two values are close to each other, or not
math.isfinite() Checks whether a number is finite or not
math.isinf() Checks whether a number is infinite or not
math.isnan() Checks whether a value is NaN (not a number) or not
math.isqrt() Rounds a square root number downwards to the nearest integer
math.ldexp() Returns the inverse of math.frexp() which is x * (2**i) of the given numbers x and i
math.lgamma() Returns the log gamma value of x
math.log() Returns the natural logarithm of a number, or the logarithm of number to base
math.log10() Returns the base-10 logarithm of x
math.log1p() Returns the natural logarithm of 1+x
math.log2() Returns the base-2 logarithm of x
math.perm() Returns the number of ways to choose k items from n items with order and without repetition
math.pow() Returns the value of x to the power of y
math.prod() Returns the product of all the elements in an iterable
math.radians() Converts a degree value into radians
math.remainder() Returns the closest value that can make numerator completely divisible by the denominator
math.sin() Returns the sine of a number
math.sinh() Returns the hyperbolic sine of a number
math.sqrt() Returns the square root of a number
math.tan() Returns the tangent of a number
math.tanh() Returns the hyperbolic tangent of a number
math.trunc() Returns the truncated integer parts of a number

Code:

# Import math Library
import math

# Return the arc cosine of numbers
print(math.acos(0.56))
print(math.acos(-0.57))
print(math.acos(0))
print(math.acos(1))
print(math.acos(-1))

Output on the screen:

 
0.9764105267938343
2.1773021820079834
1.5707963267948966
0.0
3.141592653589793


  • Math Constants

Constant Description
math.e Returns Euler's number (2.7182...)
math.inf Returns a floating-point positive infinity
math.nan Returns a floating-point NaN (Not a Number) value
math.pi Returns PI (3.1415...)
math.tau Returns tau (6.2831...)

↑Back

Python JSON

Code:

import json

# some JSON:
a = '{ "name":"Albert", "age":21, "city":"Germany"}'

# parse x:
b = json.loads(a)

# the result is a Python dictionary:
print(b["age"])

Output on the screen:

 
21

↑Back

Python RegEx

Code:

import re

#Check if the string starts with "The" and ends with "Bangalore":

txt = "The rain in Bangalore"
x = re.search("^The.*Bangalore$", txt)

if x:
  print("YES! We have a match!")
else:
  print("No match")

Output on the screen:

 
YES! We have a match!

↑Back

Python Try Exception

Code:

#The try block will generate an error, because x is not defined:

try:
  print(x)
except:
  print("An exception occurred")

Output on the screen:

 
An exception occurred

Code:

#The try block will generate a NameError, because x is not defined:

try:
  print(x)
except NameError:
  print("Variable x is not defined")
except:
  print("Something else went wrong")

Output on the screen:

 
Variable x is not defined

Code:

#The try block will generate a NameError, because x is not defined:

try:
  print(x)
except NameError:
  print("Variable x is not defined")
except:
  print("Something else went wrong")

Output on the screen:

 
Variable x is not defined

Python String Formatting

Code:

cost = 56
txt = "The cost is {} Rupees"
print(txt.format(cost))

Output on the screen:

 
The cost is 56 Rupees

Code:

cost = 56
txt = "The cost is {:.2f} Rupees"
print(txt.format(cost))

Output on the screen:

 
The cost is 56.00 Rupees

Code:

age = 16
name = "Albert"
txt = "His name is {1}. {1} is {0} years old."
print(txt.format(age, name))

Output on the screen:

 
His name is Albert. Albert is 16 years old.

↑Back

Python If ... Else

Code:

a = 40
b = 60

if b > a:
  print("b is greater than a")

Output on the screen:

 
b is greater than a

Code:

a = 30
b = 30
if b > a:
  print("b is greater than a")
elif a == b:
  print("a and b are equal")
else:
  print("a is greater than b")

Output on the screen:

 
a and b are equal

↑Back

Python Loops

Code:

items = ["pencil", "rubber", "chalk"]
for x in items:
  print(x) 

Output on the screen:

 
pencil
rubber
chalk

Code:

items = ["pencil", "rubber", "chalk"]
for x in items:
  print(x)
  if x == "rubber": 
   break

Output on the screen:

 
pencil
rubber

Code:

# Exit the loop when x is "rubber", but this time the break comes before the print:
items = ["pencil", "rubber", "chalk"]
for x in items:
  if x == "rubber":
    break
  print(x) 

Output on the screen:

 
pencil

Code:

# Do not print rubber:
items = ["pencil", "rubber", "chalk"]
for x in items:
  if x == "rubber":
    continue
  print(x) 

Output on the screen:

 
pencil
chalk

Code:

# The range() function returns a sequence of numbers, starting from 0 by default, 
# and increments by 1 (by default), and ends at a specified number: range(5)
# is not the values of 0 to 5, but the values 0 to 4.

for x in range(5):
  print(x) 

Output on the screen:

 
0
1
2
3
4

Code:

# range(1, 5), which means values from 1 to 5 (but not including 5):
for x in range(1, 5):
  print(x) 

Output on the screen:

 
1
2
3
4

Code:

# Increment the sequence with 2:
for x in range(2, 10, 2):
  print(x) 

Output on the screen:

 
2
4
6
8

Code:

# Print all numbers from 0 to 4 (but not including 4), 
# and print a message when the loop has ended:

for x in range(4):
  print(x)
else:
  print("Finally finished!")

Output on the screen:

 
0
1
2
3
Finally finished!

Code:

for x in range(5):
  if x == 3: break
  print(x)
else:
  print("Finally finished!")

#If the loop breaks, the else block is not executed.

Output on the screen:

 
0
1
2

Code:

adj = ["red", "big", "best"]
items = ["chalk", "board", "pencil"]

for x in adj:
  for y in items:
    print(x, y).

Output on the screen:

 
red chalk
red board
red pencil
big chalk
big board
big pencil
best chalk
best board
best pencil

Code:

# for loops cannot be empty, but if you for some reason 
# have a for loop with no content, put in the pass statement 
# to avoid getting an error.

for x in [0, 1, 2]:
  pass

Output on the screen:



Code:

# Print i as long as i is less than 5:
i = 0
while i < 5:
  print(i)
  i += 1

Output on the screen:

 
0
1
2
3
4

Code:

# Exit the loop when i is 3:
i = 1
while i < 5:
  print(i)
  if (i == 3):
    break
  i += 1

Output on the screen:

 
1
2
3

Code:

# Continue to the next iteration if i is 3:

i = 0
while i < 6:
  i += 1
  if i == 3:
    continue
  print(i)

# Note that number 3 is missing in the result

Output on the screen:

 
1
2
4
5
6

Code:

# Print a message once the condition is false:

i = 1
while i < 6:
  print(i)
  i += 1
else:
  print("i is no longer less than 6")

Output on the screen:

 
1
2
3
4
5
i is no longer less than 6

↑Back

Python User Input

Code:

# The following example asks for the username, and when you entered the username, 
# it gets printed on the screen:

username = input("Enter username:")
print("Username is: " + username)

Output on the screen:

 
Enter username:

If you enter the word "ram"

Username is: ram

will be outputted on the console screen.

↑Back

File Handling

Code:

import os
if os.path.exists("demofile.txt"): os.remove("demofile.txt")
else:
  print("The file does not exist")

Output on the screen:

 
The file does not exist

↑Back

Python PIP

Code:

# pip is the standard package manager for Python. 
# We use pip to install additional packages that are not 
# available in the Python standard library.
pip install numpy


Code:

# Display package information 
pip show numpy


↑Back

Python Remove List Duplicates

Code:

# Remove Duplicates From a Python List

mylist = ["a", "b", "a", "c", "c"]
mylist = list(dict.fromkeys(mylist))
print(mylist)

Output on the screen:

 
['a', 'b', 'c']

↑Back

Python Reverse a String

Code:

# Reverse the string "World":

txt = "World"[::-1]
print(txt)

Output on the screen:

 
dlroW

↑Back

Python Pandas Read CSV

Code:

# Load the CSV into a DataFrame:

import pandas as pd

b = pd.read_csv('data.csv')

print(b.to_string())

Output on the screen:

 
     Duration  Pulse  Maxpulse  Calories
0          60    110       130     409.1
1          60    117       145     479.0
2          60    103       135     340.0
3          45    109       175     282.4
4          45    117       148     406.0
5          60    102       127     300.5
6          60    110       136     374.0
7          45    104       134     253.3
8          30    109       133     195.1
9          60     98       124     269.0
10         60    103       147     329.3
11         60    100       120     250.7
12         60    106       128     345.3
13         60    104       132     379.3
14         60     98       123     275.0
15         60     98       120     215.2
16         60    100       120     300.0
17         45     90       112       NaN
18         60    103       123     323.0
19         45     97       125     243.0
20         60    108       131     364.2
21         45    100       119     282.0
22         60    130       101     300.0
23         45    105       132     246.0
24         60    102       126     334.5
25         60    100       120     250.0
26         60     92       118     241.0
27         60    103       132       NaN
28         60    100       132     280.0
29         60    102       129     380.3
30         60     92       115     243.0
31         45     90       112     180.1
32         60    101       124     299.0
33         60     93       113     223.0
34         60    107       136     361.0
35         60    114       140     415.0
36         60    102       127     300.5
37         60    100       120     300.1
38         60    100       120     300.0
39         45    104       129     266.0
40         45     90       112     180.1
41         60     98       126     286.0
42         60    100       122     329.4
43         60    111       138     400.0
44         60    111       131     397.0
45         60     99       119     273.0
46         60    109       153     387.6
47         45    111       136     300.0
48         45    108       129     298.0
49         60    111       139     397.6
50         60    107       136     380.2
51         80    123       146     643.1
52         60    106       130     263.0
53         60    118       151     486.0
54         30    136       175     238.0
55         60    121       146     450.7
56         60    118       121     413.0
57         45    115       144     305.0
58         20    153       172     226.4
59         45    123       152     321.0
60        210    108       160    1376.0
61        160    110       137    1034.4
62        160    109       135     853.0
63         45    118       141     341.0
64         20    110       130     131.4
65        180     90       130     800.4
66        150    105       135     873.4
67        150    107       130     816.0
68         20    106       136     110.4
69        300    108       143    1500.2
70        150     97       129    1115.0
71         60    109       153     387.6
72         90    100       127     700.0
73        150     97       127     953.2
74         45    114       146     304.0
75         90     98       125     563.2
76         45    105       134     251.0
77         45    110       141     300.0
78        120    100       130     500.4
79        270    100       131    1729.0
80         30    159       182     319.2
81         45    149       169     344.0
82         30    103       139     151.1
83        120    100       130     500.0
84         45    100       120     225.3
85         30    151       170     300.1
86         45    102       136     234.0
87        120    100       157    1000.1
88         45    129       103     242.0
89         20     83       107      50.3
90        180    101       127     600.1
91         45    107       137       NaN
92         30     90       107     105.3
93         15     80       100      50.5
94         20    150       171     127.4
95         20    151       168     229.4
96         30     95       128     128.2
97         25    152       168     244.2
98         30    109       131     188.2
99         90     93       124     604.1
100        20     95       112      77.7
101        90     90       110     500.0
102        90     90       100     500.0
103        90     90       100     500.4
104        30     92       108      92.7
105        30     93       128     124.0
106       180     90       120     800.3
107        30     90       120      86.2
108        90     90       120     500.3
109       210    137       184    1860.4
110        60    102       124     325.2
111        45    107       124     275.0
112        15    124       139     124.2
113        45    100       120     225.3
114        60    108       131     367.6
115        60    108       151     351.7
116        60    116       141     443.0
117        60     97       122     277.4
118        60    105       125       NaN
119        60    103       124     332.7
120        30    112       137     193.9
121        45    100       120     100.7
122        60    119       169     336.7
123        60    107       127     344.9
124        60    111       151     368.5
125        60     98       122     271.0
126        60     97       124     275.3
127        60    109       127     382.0
128        90     99       125     466.4
129        60    114       151     384.0
130        60    104       134     342.5
131        60    107       138     357.5
132        60    103       133     335.0
133        60    106       132     327.5
134        60    103       136     339.0
135        20    136       156     189.0
136        45    117       143     317.7
137        45    115       137     318.0
138        45    113       138     308.0
139        20    141       162     222.4
140        60    108       135     390.0
141        60     97       127       NaN
142        45    100       120     250.4
143        45    122       149     335.4
144        60    136       170     470.2
145        45    106       126     270.8
146        60    107       136     400.0
147        60    112       146     361.9
148        30    103       127     185.0
149        60    110       150     409.4
150        60    106       134     343.0
151        60    109       129     353.2
152        60    109       138     374.0
153        30    150       167     275.8
154        60    105       128     328.0
155        60    111       151     368.5
156        60     97       131     270.4
157        60    100       120     270.4
158        60    114       150     382.8
159        30     80       120     240.9
160        30     85       120     250.4
161        45     90       130     260.4
162        45     95       130     270.0
163        45    100       140     280.9
164        60    105       140     290.8
165        60    110       145     300.4
166        60    115       145     310.2
167        75    120       150     320.4
168        75    125       150     330.4

↑Back

Python Datetime

Code:

# Import the datetime module and display the current date:
import datetime

x = datetime.datetime.now()

print(x)

Output on the screen:

 
2021-02-08 02:35:46.405410

Code:

# Return the year and name of weekday: 

import datetime
x = datetime.datetime.now()


print(x.year) 
print(x.strftime("%A"))

Output on the screen:

 
2021
Monday


Directive Description Example
%a Weekday, short version Wed
%A Weekday, full version Wednesday
%w Weekday as a number 0-6, 0 is Sunday 3
%d Day of month 01-31 31
%b Month name, short version Dec
%B Month name, full version December
%m Month as a number 01-12 12
%y Year, short version, without century 18
%Y Year, full version 2018
%H Hour 00-23 17
%I Hour 00-12 05
%p AM/PM PM
%M Minute 00-59 41
%S Second 00-59 08
%f Microsecond 000000-999999 548513
%z UTC offset +0100
%Z Timezone CST
%j Day number of year 001-366 365
%U Week number of year, Sunday as the first day of week, 00-53 52
%W Week number of year, Monday as the first day of week, 00-53 52
%c Local version of date and time Mon Dec 31 17:41:00 2018
%x Local version of date 12/31/18
%X Local version of time 17:41:00
%% A % character %
%G ISO 8601 year 2018
%u ISO 8601 weekday (1-7) 1
%V ISO 8601 weeknumber (01-53) 01

↑Back

Python Pandas Series

Code:

# Create a simple Pandas Series from a list:

import pandas as pd

x = [2, 8, 6]

var = pd.Series(x)

print(var)

Output on the screen:

 
0    2
1    8
2    6
dtype: int64

↑Back

Python Pandas Read JSON

Code:

#Load the JSON file into a DataFrame:

import pandas as pd

x = pd.read_json('data.json')

print(x.to_string())

Output on the screen:

 
     Duration  Pulse  Maxpulse  Calories
0          60    110       130     409.1
1          60    117       145     479.0
2          60    103       135     340.0
3          45    109       175     282.4
4          45    117       148     406.0
5          60    102       127     300.5
6          60    110       136     374.0
7          45    104       134     253.3
8          30    109       133     195.1
9          60     98       124     269.0
10         60    103       147     329.3
11         60    100       120     250.7
12         60    106       128     345.3
13         60    104       132     379.3
14         60     98       123     275.0
15         60     98       120     215.2
16         60    100       120     300.0
17         45     90       112       NaN
18         60    103       123     323.0
19         45     97       125     243.0
20         60    108       131     364.2
21         45    100       119     282.0
22         60    130       101     300.0
23         45    105       132     246.0
24         60    102       126     334.5
25         60    100       120     250.0
26         60     92       118     241.0
27         60    103       132       NaN
28         60    100       132     280.0
29         60    102       129     380.3
30         60     92       115     243.0
31         45     90       112     180.1
32         60    101       124     299.0
33         60     93       113     223.0
34         60    107       136     361.0
35         60    114       140     415.0
36         60    102       127     300.5
37         60    100       120     300.1
38         60    100       120     300.0
39         45    104       129     266.0
40         45     90       112     180.1
41         60     98       126     286.0
42         60    100       122     329.4
43         60    111       138     400.0
44         60    111       131     397.0
45         60     99       119     273.0
46         60    109       153     387.6
47         45    111       136     300.0
48         45    108       129     298.0
49         60    111       139     397.6
50         60    107       136     380.2
51         80    123       146     643.1
52         60    106       130     263.0
53         60    118       151     486.0
54         30    136       175     238.0
55         60    121       146     450.7
56         60    118       121     413.0
57         45    115       144     305.0
58         20    153       172     226.4
59         45    123       152     321.0
60        210    108       160    1376.0
61        160    110       137    1034.4
62        160    109       135     853.0
63         45    118       141     341.0
64         20    110       130     131.4
65        180     90       130     800.4
66        150    105       135     873.4
67        150    107       130     816.0
68         20    106       136     110.4
69        300    108       143    1500.2
70        150     97       129    1115.0
71         60    109       153     387.6
72         90    100       127     700.0
73        150     97       127     953.2
74         45    114       146     304.0
75         90     98       125     563.2
76         45    105       134     251.0
77         45    110       141     300.0
78        120    100       130     500.4
79        270    100       131    1729.0
80         30    159       182     319.2
81         45    149       169     344.0
82         30    103       139     151.1
83        120    100       130     500.0
84         45    100       120     225.3
85         30    151       170     300.1
86         45    102       136     234.0
87        120    100       157    1000.1
88         45    129       103     242.0
89         20     83       107      50.3
90        180    101       127     600.1
91         45    107       137       NaN
92         30     90       107     105.3
93         15     80       100      50.5
94         20    150       171     127.4
95         20    151       168     229.4
96         30     95       128     128.2
97         25    152       168     244.2
98         30    109       131     188.2
99         90     93       124     604.1
100        20     95       112      77.7
101        90     90       110     500.0
102        90     90       100     500.0
103        90     90       100     500.4
104        30     92       108      92.7
105        30     93       128     124.0
106       180     90       120     800.3
107        30     90       120      86.2
108        90     90       120     500.3
109       210    137       184    1860.4
110        60    102       124     325.2
111        45    107       124     275.0
112        15    124       139     124.2
113        45    100       120     225.3
114        60    108       131     367.6
115        60    108       151     351.7
116        60    116       141     443.0
117        60     97       122     277.4
118        60    105       125       NaN
119        60    103       124     332.7
120        30    112       137     193.9
121        45    100       120     100.7
122        60    119       169     336.7
123        60    107       127     344.9
124        60    111       151     368.5
125        60     98       122     271.0
126        60     97       124     275.3
127        60    109       127     382.0
128        90     99       125     466.4
129        60    114       151     384.0
130        60    104       134     342.5
131        60    107       138     357.5
132        60    103       133     335.0
133        60    106       132     327.5
134        60    103       136     339.0
135        20    136       156     189.0
136        45    117       143     317.7
137        45    115       137     318.0
138        45    113       138     308.0
139        20    141       162     222.4
140        60    108       135     390.0
141        60     97       127       NaN
142        45    100       120     250.4
143        45    122       149     335.4
144        60    136       170     470.2
145        45    106       126     270.8
146        60    107       136     400.0
147        60    112       146     361.9
148        30    103       127     185.0
149        60    110       150     409.4
150        60    106       134     343.0
151        60    109       129     353.2
152        60    109       138     374.0
153        30    150       167     275.8
154        60    105       128     328.0
155        60    111       151     368.5
156        60     97       131     270.4
157        60    100       120     270.4
158        60    114       150     382.8
159        30     80       120     240.9
160        30     85       120     250.4
161        45     90       130     260.4
162        45     95       130     270.0
163        45    100       140     280.9
164        60    105       140     290.8
165        60    110       145     300.4
166        60    115       145     310.2
167        75    120       150     320.4
168        75    125       150     330.4


↑Back

Python Pandas Analyzing Data

Code:

# print the first 5 rows of the DataFrame:

import pandas as pd

x = pd.read_csv('data.csv')

print(x.head(5))

Output on the screen:

 
   Duration  Pulse  Maxpulse  Calories
0        60    110       130     409.1
1        60    117       145     479.0
2        60    103       135     340.0
3        45    109       175     282.4
4        45    117       148     406.0

↑Back

Python SciPy Constants

Code:

# Print the constant value of PI:

from scipy import constants

print(constants.pi)

Output on the screen:

 

3.141592653589793

↑Back

Python SciPy Sparse Data

Code:

# Create a CSR matrix from an array:

import numpy as np
from scipy.sparse import csr_matrix

arr = np.array([0, 0, 0, 0, 0, 1, 1, 0, 2])

print(csr_matrix(arr))

Output on the screen:

 
  (0, 5)	1
  (0, 6)	1
  (0, 8)	2

↑Back

Python Matplotlib Plotting

Code:

# Draw a line in a diagram from position (1, 3) to position (8, 10):


import matplotlib.pyplot as plt
import numpy as np

xpoints = np.array([1, 8])
ypoints = np.array([3, 10])

plt.plot(xpoints, ypoints)
plt.show()

Output on the screen:

Matplotlib Plotting


Code:

# Draw two points in the diagram, one at position (1, 3) and one in position (8, 10):

import matplotlib.pyplot as plt
import numpy as np

xpoints = np.array([1, 8])
ypoints = np.array([3, 10])

plt.plot(xpoints, ypoints, 'o')
plt.show()

Output on the screen:

Matplotlib Plotting


↑Back

Python Matplotlib Bars

Code:

# Draw 4 bars:
import matplotlib.pyplot as plt
import numpy as np

x = np.array(["X", "Y", "Z", "W"])
y = np.array([5, 9, 11, 12])

plt.bar(x,y)
plt.show()

Output on the screen:

Matplotlib Plotting


↑Back

Python Matplotlib Pie Charts

Code:

import matplotlib.pyplot as plt
import numpy as np

y = np.array([35, 25, 25, 15])
mylabels = ["Apples", "Bananas", "Cherries", "Dates"]

plt.pie(y, labels = mylabels)
plt.show() 

Output on the screen:

Matplotlib Plotting


Code:

import matplotlib.pyplot as plt
import numpy as np

y = np.array([35, 25, 25, 15])
mylabels = ["Apples", "Bananas", "Cherries", "Dates"]

plt.pie(y, labels = mylabels, startangle = 60)
plt.show()

Output on the screen:

Matplotlib Plotting


↑Back

Python Statistics

Code:

# Import statistics Library
import statistics 

# Calculate the harmonic mean of the given data:
print(statistics.harmonic_mean([20, 50, 100]))
print(statistics.harmonic_mean([20, 40, 60, 80, 100]))

Output on the screen:

37.5
43.7956204379562

Code:

# Import statistics Library
import statistics 

# Calculate the median (middle value) of the given data:
print(statistics.median([1, 3, 5, 7, 9, 11, 13]))
print(statistics.median([-11, 5.5, -3.4, 7.1, -9, 22]))

Output on the screen:

7
1.05

  • Statistics Methods

Method Description
statistics.harmonic_mean() Calculates the harmonic mean (central location) of the given data
statistics.mean() Calculates the mean (average) of the given data
statistics.median() Calculates the median (middle value) of the given data
statistics.median_grouped() Calculates the median of grouped continuous data
statistics.median_high() Calculates the high median of the given data
statistics.median_low() Calculates the low median of the given data
statistics.mode() Calculates the mode (central tendency) of the given numeric or nominal data
statistics.pstdev() Calculates the standard deviation from an entire population
statistics.stdev() Calculates the standard deviation from a sample of data
statistics.pvariance() Calculates the variance of an entire population
statistics.variance() Calculates the variance from a sample of data

↑Back

Python Requests

Code:

# Make a request to a web page, and print the response text:
import requests
x = requests.get('https://w3schools.com/python/demopage.htm')
print(x.text)

Output on the screen:

<!DOCTYPE html>
<html>
<body>

<h1>This is a Test Page</h1>

</body>
</html>


↑Back

Python NumPy

Code:

import numpy
arr = numpy.array([1, 2, 3, 4, 5]) 
print(arr)

Output on the screen:

 
[1 2 3 4 5]

Code:

import numpy as np
arr = np.array([1, 2, 3, 4, 5]) 
print(arr)

Output on the screen:

 
[1 2 3 4 5]

Code:

# Join two arrays

import numpy as np

x = np.array([4, 5, 6])

y = np.array([7, 8, 9])

z = np.concatenate((x, y))

print(z)

Output on the screen:

 
[4 5 6 7 8 9]

Code:

# Split the array in 3 parts:

import numpy as np

x = np.array([1, 2, 3, 4, 5, 6])

y = np.array_split(x, 3)

print(y)

Output on the screen:

 
[array([1, 2]), array([3, 4]), array([5, 6])]

Code:

# Use the NumPy std() method to find the standard deviation:

import numpy

y = [86,87,88,86,87,85,86]

x = numpy.std(y)

print(x)

Output on the screen:

 
0.9035079029052513

Code:

# Use the NumPy percentile() method to find the percentiles:
import numpy

x = [5,31,43,48,50,41,7,11,15,39,80,82,32,2,8,6,25,36,27,61,31]

y = numpy.percentile(x, 65)

print(y)

Output on the screen:

39.0

↑Back

Python Papers


↑Back

Girl in a jacket


Books


↑Back

Python MySQL

Code:

# create a database named "mydata":
import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="myusername",
  password="mypassword"
)

mycursor = mydb.cursor()

mycursor.execute("CREATE DATABASE mydata")

Code:

# Create a table named "students":
import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  password="yourpassword",
  database="mydata"
)

mycursor = mydb.cursor()

mycursor.execute("CREATE TABLE students (name VARCHAR(255), address VARCHAR(255))")

Code:

# Insert a record in the "students" table:
import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  password="yourpassword",
  database="mydata"
)

mycursor = mydb.cursor()

sql = "INSERT INTO students (name, address) VALUES (%s, %s)"
val = ("Albert", "Highway 21")
mycursor.execute(sql, val)

mydb.commit()

print(mycursor.rowcount, "record inserted.")

Code:

# Delete the table "students":
import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  password="yourpassword",
  database="mydata"
)

mycursor = mydb.cursor()

sql = "DROP TABLE students"

mycursor.execute(sql)

↑Back

Python Global Keyword

Code:

def myfunc():
  global z
  z = 5

myfunc()

print(z)

Output on the screen:

5

↑Back

Python Raise an Exception

Code:

a = -2

if a < 0:
  raise Exception("Sorry, no numbers below zero")

Output on the screen:

 raise Exception("Sorry, no numbers below zero")

Exception: Sorry, no numbers below zero


↑Back

Python Try Finally

Code:

#The finally block gets executed no matter if the try block raises any errors or not:

try:
  print(z)
except:
  print("Something went wrong")
finally:
  print("The 'try except' is finished")

Output on the screen:

Something went wrong
The 'try except' is finished

↑Back

Python cmath

Code:

#import cmath for complex number operations 
import cmath

#find the arc cosine of a complex number
print (cmath.acos(3+2j))

Output on the screen:

(0.6061378223872937-1.9686379257930964j)

  • cMath Methods

Method Description
cmath.acos(x) Returns the arc cosine value of x
cmath.acosh(x) Returns the hyperbolic arc cosine of x
cmath.asin(x) Returns the arc sine of x
cmath.asinh(x) Returns the hyperbolic arc sine of x
cmath.atan(x) Returns the arc tangent value of x
cmath.atanh(x) Returns the hyperbolic arctangent value of x
cmath.cos(x) Returns the cosine of x
cmath.cosh(x) Returns the hyperbolic cosine of x
cmath.exp(x) Returns the value of Ex, where E is Euler's number (approximately 2.718281...), and x is the number passed to it
cmath.isclose() Checks whether two values are close, or not
cmath.isfinite(x) Checks whether x is a finite number
cmath.isinf(x) Check whether x is a positive or negative infinty
cmath.isnan(x) Checks whether x is NaN (not a number)
cmath.log(x[, base]) Returns the logarithm of x to the base
cmath.log10(x) Returns the base-10 logarithm of x
cmath.phase() Return the phase of a complex number
cmath.polar() Convert a complex number to polar coordinates
cmath.rect() Convert polar coordinates to rectangular form
cmath.sin(x) Returns the sine of x
cmath.sinh(x) Returns the hyperbolic sine of x
cmath.sqrt(x) Returns the square root of x
cmath.tan(x) Returns the tangent of x
cmath.tanh(x) Returns the hyperbolic tangent of x

  • cMath Constants

Constant Description
cmath.e Returns Euler's number (2.7182...)
cmath.inf Returns a floating-point positive infinity value
cmath.infj Returns a complex infinity value
cmath.nan Returns floating-point NaN (Not a Number) value
cmath.nanj Returns coplext NaN (Not a Number) value
cmath.pi Returns PI (3.1415...)
cmath.tau Returns tau (6.2831...)

Code:

#Import cmath Library
import cmath

# Print complex infinity
print (cmath.infj)

Output on the screen:

infj

↑Back


Python Exercises with Solutions [183 Exercises]

Question 1

Question:

Write a program to Add Two Numbers.


Solution:

a = 1
b = 2
c= a+b
print(c)

a = int(input("enter a number: "))
b = int(input("enter a number: "))
c= a+b
print(c)

Question 2

Question:

Write a program to find whether a given number (accept from the user) is even or odd, print out an appropriate message to the user.


Solution:

a = int(input("enter a number: "))
if a % 2 == 0:
    print("This is an even number.")
else:
    print("This is an odd number.")

Question 3

Question:

Write a program to check whether a number entered by the user is positive, negative or zero.


Solution:

a = int(input("Enter a number: "))
if a > 0:
   print("Positive number")
elif a == 0:
   print("Zero")
else:
   print("Negative number")

Question 4

Question:

Write a program to display the calendar of a given date.


Solution:

import calendar
yy = int(input("Enter year: "))
mm = int(input("Enter month: "))
print(calendar.month(yy, mm))

Question 5

Question:

Write a program to ask the user to enter the string and print that string as output of the program.


Solution:

string = input("Enter string: ")
print("You entered:",string)

Question 6

Question:

Write a program to Concatenate Two Strings.


Solution:

string1 = input("Enter first string to concatenate: ")
string2 = input("Enter second string to concatenate: ")
string3 = string1 + string2
print("String after concatenation = ",string3)

Question 7

Question:

Write a program to Check if an item exists in the list.


Solution:

list_of_items = ["ball", "book", "pencil"]
item = input("Type item to check: ")
if item in list_of_items:
 print("Item exists in the list.")
else:
  print("Item does not exist in the list.") 

Question 8

Question:

Write a program to Join two or more lists.


Solution:

list1 = ["This" , "is", "a", "sample", "program"]
list2 = [10, 2, 45, 3, 5, 7, 8, 10]
finalList = list1 + list2
print(finalList) 

Question 9

Question:

Write a program to Calculate Cube of a Number.


Solution:

import math 
a = int(input("Enter a number: "))
b=math.pow(a,3)
print (b) 

Question 10

Question:

Write a program to Calculate Square root of a Number.


Solution:

import math 
a = int(input("Enter a number: "))
b=math.sqrt(a)
print (b)  

Question 11

Question:

Write a program that takes a list of numbers (for example, a = [5, 10, 15, 20, 25]) and makes a new list of only the first and last elements of the given list.


Solution:

a = [5, 10, 15, 20, 25]
print([a[0], a[4]]) 

Question 12

Question:

Take a list, say for example this one: a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] and write a program that prints out all the elements of the list that are less than 5.


Solution:

a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
for i in a:
    if i < 5:
        print(i)

Question 13

Question:

Let's say I give you a list saved in a variable: a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]. Write one line of Python that takes this list 'a' and makes a new list that has only the even elements of this list in it.


Solution:

a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
b = [number for number in a if number % 2 == 0]
print(b)

Question 14

Question:

Ask the user for a string and print out whether this string is a palindrome or not (A palindrome is a string that reads the same forwards and backwards).


Solution:

a=input("Please enter a word: ")
c = a.casefold()
b = reversed(c)
if list(c) == list(b):
   print("It is palindrome")
else:
   print("It is not palindrome")

Question 15

Question:

Take two lists, say for example these two: a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] and write a program that returns a list that contains only the elements that are common between the lists (without duplicates). Make sure your program works on two lists of different sizes.


Solution:

a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
result = [i for i in set(a) if i in b]
print(result)

Question 16

Question:

Write a program to add a string to text file.


Solution:

file = open("testfile.txt","w") 
file.write("Hello World") 
file.write("This is our new text file") 
file.write("and this is another line.") 
file.write("Why? Because we can.") 
file.close()

Question 17

Question:

Write a program to read a file and display its contents on console.


Solution:

with open('testfile.txt') as f:
  	line = f.readline()
  	while line:
  		print(line)
  		line = f.readline()

Question 18

Question:

Take two sets, say for example these two: a = {1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89} b = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13} and write a program that returns a set that contains only the elements that are common between the sets.


Solution:

a = {1, 1, 2, 2, 3, 5, 8, 13, 21, 34, 55, 89}
b = {1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}
c = set(a) & set(b)  
print(c)

Question 19

Question:

Write a program to split the characters of the given string into a list.


Solution:

s = "mystring"
l = list(s)
print (l)

Question 20

Question:

Create a program that asks the user for a number and then prints out a list of all the divisors of that number.


Solution:

n=int(input("Enter an integer: "))
print("The divisors of the number are: ")
for i in range(1,n+1):
    if(n%i==0):
        print(i)

Question 21

Question:

Write a program to Find the largest of three numbers.


Solution:

a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
c = int(input("Enter third number: "))
if (a > b) and (a > c):
   largest = a
elif (b > a) and (b > c):
   largest = b
else:
   largest = c
print("The largest number is", largest)

Question 22

Question:

Write a Program to Find Absolute value of a Number.


Solution:

num = int(input("Enter a number: "))
if num >= 0:
		print(num)
else:
		print(-num)

Question 23

Question:

Write a program to Find the length of a String.


Solution:

print("Enter 'y' for exit.")
string = input("Enter a string: ")
if string == 'y':
    exit()
else:
    print("Length of the string =", len(string))

Question 24

Question:

Write a program to Print Natural Numbers from 1 to N.


Solution:

N = int(input("Please Enter any Number: "))
for i in range(1, N+1):
    print (i)

Question 25

Question:

Write a program to calculate the sum and average of Natural Numbers from 1 to N.


Solution:

N = int(input("Please Enter any Number: "))
sum = 0
for i in range(1,N+1):
  sum = sum + i
print(sum)
average = sum / N
print(average)

Question 26

Question:

Write a program to Print a Statement Any Number of Times.


Solution:

n = int(input("Please Enter any Number: "))
for i in range(n):
    print("hello world")

Question 27

Question:

Write a program To Multiply Two Numbers Using Function.


Solution:

def my_function():
    a = int(input("enter a number: "))
    b=int(input("enter a number: "))
    c= a*b
    return c
d = my_function()
print (d)

Question 28

Question:

Write a program To add an item to the end of the list.


Solution:

list1 = ["pen", "book", "ball"]
list1.append("bat")
print(list1)

Question 29

Question:

Write a program To remove an item from the list.


Solution:

list1 = ["pen", "book", "ball"]
list1.remove("ball")
print(list1)

Question 30

Question:

Write a program To print the number of elements in an array.


Solution:

list1 = ["pen", "book", "ball"]
a = len(list1)
print(a)

Question 31

Question:

Write a program To calculate the variance and standard deviation of the elements of the list.


Solution:

import numpy as np
a= [2,6,8,12,18,24,28,32]
variance= np.var(a)
std = np.std(a)
print(variance)
print(std)

Question 32

Question:

Write a program to get the difference between the two lists.


Solution:

list1 = [4, 5, 6, 7]
list2 = [4, 5]
print(list(set(list1) - set(list2)))

Question 33

Question:

Write a program to select an item randomly from a list.


Solution:

import random
list = ['Paper', 'Pencil', 'Book', 'Bag', 'Pen']
print(random.choice(list))

Question 34

Question:

Write a program that prints all the numbers from 0 to 6 except 2 and 6.


Solution:

for x in range(6):
    if (x == 2 or x==6):
        continue
    print(x)

Question 35

Question:

Write a program that takes input from the user and displays that input back in upper and lower cases.


Solution:

a = input("What's your name? ")
print(a.upper())
print(a.lower())

Question 36

Question:

Write a program to check whether a string starts with specified characters.


Solution:

string = "myw3schools.com"
print(string.startswith("w3s"))

Question 37

Question:

Write a program to create the multiplication table (from 1 to 10) of a number.


Solution:

n = int(input("Enter a number: "))
for i in range(1,11):
   print(n,'x',i,'=',n*i)

Question 38

Question:

Write a program to check a triangle is equilateral, isosceles or scalene.


Solution:

print("Enter lengths of the triangle sides: ")
a = int(input("a: "))
b = int(input("b: "))
c = int(input("c: "))
if a == b == c:
	print("Equilateral triangle")
elif a==b or b==c or c==a:
	print("isosceles triangle")
else:
	print("Scalene triangle")

Question 39

Question:

Write a program to sum of two given integers. However, if the sum is between 15 to 20 it will return 20.


Solution:

a = int(input("enter a number: "))
b = int(input("enter a number: "))
c= a+b
if c in range(15, 20):
        print (20)
else:
        print(c) 

Question 40

Question:

Write a program to convert degree to radian.


Solution:

pi=22/7
degree = int(input("Input degrees: "))
radian = degree*(pi/180)
print(radian)

Question 41

Question:

Write a program to Generate a Random Number.


Solution:

import random
print(random.randint(0,9))

Question 42

Question:

Write a Program to find the semi-perimeter of triangle.


Solution:

a = int(input('Enter first side: '))
b = int(input('Enter second side: '))
c = int(input('Enter third side: '))
s = (a + b + c) / 2
print(s)

Question 43

Question:

Given a list of numbers, Iterate it and print only those numbers which are divisible of 2.


Solution:

List = [10, 20, 33, 46, 55]
for i in List:
    if (i % 2 == 0):
      print(i)

Question 44

Question:

Write a program to Multiply all numbers in the list.


Solution:

import numpy  
list = [1, 2, 3]  
result = numpy.prod(list) 
print(result) 

Question 45

Question:

Write a program to print ASCII Value of a character.


Solution:

a = 'j'
print("The ASCII value of '" + a + "' is", ord(a))  

Question 46

Question:

Write a program to list files in a directory.


Solution:

# Import os module to read directory
import os

# Set the directory path
path = 'C:/Users/Manju/.spyder-py3/'

# Read the content of the file
files = os.listdir(path)

# Print the content of the directory
for file in files:
    print(file)
 

Question 47

Question:

Write a program to Read and Write File.


Solution:

#Assign the filename
filename = "languages.txt"
# Open file for writing
fileHandler = open(filename, "w")

# Add some text
fileHandler.write("Bash\n")
fileHandler.write("Python\n")
fileHandler.write("PHP\n")

# Close the file
fileHandler.close()

# Open file for reading
fileHandler = open(filename, "r")

# Read a file line by line
for line in fileHandler:
  print(line)
 
# Close the file
fileHandler.close()
 

Question 48

Question:

Write a program to add and search data in the dictionary.


Solution:

# Define a dictionary
customers = {'1':'Mehzabin Afroze','2':'Md. Ali',
'3':'Mosarof Ahmed','4':'Mila Hasan', '5':'Yaqub Ali'}

# Append a new data
customers['6'] = 'Mehboba Ferdous'

print("The customer names are:")
# Print the values of the dictionary
for customer in customers:
    print(customers[customer])

# Take customer ID as input to search
name = input("Enter customer ID:")

# Search the ID in the dictionary
for customer in customers:
    if customer == name:
        print(customers[customer])
        break
 

Question 49

Question:

Write a program to add and search data in the set.


Solution:

# Define the number set
numbers = {23, 90, 56, 78, 12, 34, 67}
 
# Add a new data
numbers.add(50)
# Print the set values
print(numbers)

message = "Number is not found"

# Take a number value for search
search_number = int(input("Enter a number:"))
# Search the number in the set
for val in numbers:
    if val == search_number:
        message = "Number is found"
        break

print(message)
 

Question 50

Question:

Write a program to demonstrate throw and catch exception.


Solution:

# Try block
try:
    # Take a number
    number = int(input("Enter a number: "))
    if number % 2 == 0:
        print("Number is even")
    else:
        print("Number is odd")

# Exception block    
except (ValueError):
  # Print error message
  print("Enter a numeric value")
 

Question 51

Question:

Write a program to illustrate password authentication.


Solution:

# import getpass module
import getpass

# Take password from the user
passwd = getpass.getpass('Password:')

# Check the password
if passwd == "python":
    print("You are authenticated")
else:
    print("You are not authenticated")
 

Question 52

Question:

Write a program to calculate the average of numbers in a given list.


Solution:

n=int(input("Enter the number of elements to be inserted: "))
a=[]
for i in range(0,n):
    elem=int(input("Enter element: "))
    a.append(elem)
avg=sum(a)/n
print("Average of elements in the list",round(avg,2))
 

Question 53

Question:

Write a program to exchange the values of two numbers without using a temporary variable.


Solution:

a=int(input("Enter value of first variable: "))
b=int(input("Enter value of second variable: "))
a=a+b
b=a-b
a=a-b
print("a is:",a," b is:",b)
 

Question 54

Question:

Write a program to reverse a given number.


Solution:

n=int(input("Enter number: "))
rev=0
while(n>0):
    dig=n%10
    rev=rev*10+dig
    n=n//10
print("Reverse of the number:",rev)
 

Question 55

Question:

Write a program to take in the marks of 5 subjects and display the grade.


Solution:

sub1=int(input("Enter marks of the first subject: "))
sub2=int(input("Enter marks of the second subject: "))
sub3=int(input("Enter marks of the third subject: "))
sub4=int(input("Enter marks of the fourth subject: "))
sub5=int(input("Enter marks of the fifth subject: "))
avg=(sub1+sub2+sub3+sub4+sub4)/5
if(avg>=90):
    print("Grade: A")
elif(avg>=80&avg<90):
    print("Grade: B")
elif(avg>=70&avg<80):
    print("Grade: C")
elif(avg>=60&avg<70):
    print("Grade: D")
else:
    print("Grade: F")
 

Question 56

Question:

Write a program to print all numbers in a range divisible by a given number.


Solution:

 
lower=int(input("Enter lower range limit:"))
upper=int(input("Enter upper range limit:"))
n=int(input("Enter the number to be divided by:"))
for i in range(lower,upper+1):
    if(i%n==0):
        print(i)
 

Question 57

Question:

Write a program to read two numbers and print their quotient and remainder.


Solution:

 
a=int(input("Enter the first number: "))
b=int(input("Enter the second number: "))
quotient=a//b
remainder=a%b
print("Quotient is:",quotient)
print("Remainder is:",remainder)
 

Question 58

Question:

Write a program to accept three distinct digits and print all possible combinations from the digits.


Solution:

 
a=int(input("Enter first number:"))
b=int(input("Enter second number:"))
c=int(input("Enter third number:"))
d=[]
d.append(a)
d.append(b)
d.append(c)
for i in range(0,3):
    for j in range(0,3):
        for k in range(0,3):
            if(i!=j&j!=k&k!=i):
                print(d[i],d[j],d[k])
 

Question 59

Question:

Write a program to print odd numbers within a given range.


Solution:

 
lower=int(input("Enter the lower limit for the range:"))
upper=int(input("Enter the upper limit for the range:"))
for i in range(lower,upper+1):
    if(i%2!=0):
        print(i)
 

Question 60

Question:

Write a program to find the smallest divisor of an integer.


Solution:

 
n=int(input("Enter an integer:"))
a=[]
for i in range(2,n+1):
    if(n%i==0):
        a.append(i)
a.sort()
print("Smallest divisor is:",a[0])
 

Question 61

Question:

Write a program to count the number of digits in a number.


Solution:

 
n=int(input("Enter number:"))
count=0
while(n>0):
    count=count+1
    n=n//10
print("The number of digits in the number are:",count)
 

Question 62

Question:

Write a program to read a number n and print and compute the series "1+2+…+n=".


Solution:

 
n=int(input("Enter a number: "))
a=[]
for i in range(1,n+1):
    print(i,sep=" ",end=" ")
    if(i<n):
        print("+",sep=" ",end=" ")
    a.append(i)
print("=",sum(a))
 
print()
 

Question 63

Question:

Write a program to read a number n and print the natural numbers summation pattern.


Solution:

n=int(input("Enter a number: "))
for j in range(1,n+1):
    a=[]
    for i in range(1,j+1):
        print(i,sep=" ",end=" ")
        if(i<j):
            print("+",sep=" ",end=" ")
        a.append(i)
    print("=",sum(a))
 
print()
 

Question 64

Question:

Write a program to read a number n and print an identity matrix of the desired size.


Solution:

n=int(input("Enter a number: "))
for i in range(0,n):
    for j in range(0,n):
        if(i==j):
            print("1",sep=" ",end=" ")
        else:
            print("0",sep=" ",end=" ")
    print()
 

Question 65

Question:

Write a program to read a number n and print an inverted star pattern of the desired size.


Solution:

n=int(input("Enter number of rows: "))
for i in range (n,0,-1):
    print((n-i) * ' ' + i * '*')
 

Question 66

Question:

Write a program to print prime numbers in a range using Sieve of Eratosthenes.


Solution:

n=int(input("Enter upper limit of range: "))
sieve=set(range(2,n+1))
while sieve:
    prime=min(sieve)
    print(prime,end="\t")
    sieve-=set(range(prime,n+1,prime))
 
print()

 

Question 67

Question:

Write a program to find the largest number in a list.


Solution:

a=[]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
    b=int(input("Enter element:"))
    a.append(b)
a.sort()
print("Largest element is:",a[n-1])
 

Question 68

Question:

Write a program to find the second largest number in a list.


Solution:

a=[]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
    b=int(input("Enter element:"))
    a.append(b)
a.sort()
print("Second largest element is:",a[n-2])
 

Question 69

Question:

Write a program to put the even and odd elements in a list into two different lists.


Solution:

a=[]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
    b=int(input("Enter element:"))
    a.append(b)
even=[]
odd=[]
for j in a:
    if(j%2==0):
        even.append(j)
    else:
        odd.append(j)
print("The even list",even)
print("The odd list",odd)
 

Question 70

Question:

Write a program to sort the list according to the second element in the sublist.


Solution:

a=[['A',34],['B',21],['C',26]]
for i in range(0,len(a)):
    for j in range(0,len(a)-i-1):
        if(a[j][1]>a[j+1][1]):
            temp=a[j]
            a[j]=a[j+1]
            a[j+1]=temp
 
print(a)
 

Question 71

Question:

Write a program to find the second largest number in a list using bubble sort.


Solution:

 
a=[]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
    b=int(input("Enter element:"))
    a.append(b)
for i in range(0,len(a)):
    for j in range(0,len(a)-i-1):
        if(a[j]>a[j+1]):
            temp=a[j]
            a[j]=a[j+1]
            a[j+1]=temp 
print('Second largest number is:',a[n-2])
 

Question 72

Question:

Write a program to sort a list according to the length of the elements.


Solution:

 
a=[]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
    b=input("Enter element:")
    a.append(b)
a.sort(key=len)
print(a)
 

Question 73

Question:

Write a program to create a list of tuples with the first element as the number and the second element as the square of the number.


Solution:

 
l_range=int(input("Enter the lower range:"))
u_range=int(input("Enter the upper range:"))
a=[(x,x**2) for x in range(l_range,u_range+1)]
print(a)
 

Question 74

Question:

Write a program to create a list of all numbers in a range which are perfect squares and the sum of the digits of the number is less than 10.


Solution:

 
l=int(input("Enter lower range: "))
u=int(input("Enter upper range: "))
a=[]
a=[x for x in range(l,u+1) if (int(x**0.5))**2==x and sum(list(map(int,str(x))))<10]
print(a)
 

Question 75

Question:

Write a program to find the cumulative sum of a list where the ith element is the sum of the first i+1 elements from the original list.


Solution:

 
a=[]
n= int(input("Enter the number of elements in list:"))
for x in range(0,n):
    element=int(input("Enter element" + str(x+1) + ":"))
    a.append(element)
b=[sum(a[0:x+1]) for x in range(0,len(a))]
print("The original list is: ",a)
print("The new list is: ",b)
 

Question 76

Question:

Write a program to generate random numbers from 1 to 20 and append them to the list.


Solution:

 
import random
a=[]
n=int(input("Enter number of elements:"))
for j in range(n):
    a.append(random.randint(1,20))
print('Randomised list is: ',a)
 

Question 77

Question:

Write a program to sort a list of tuples in increasing order by the last element in each tuple.


Solution:

 
def last(n):
    return n[-1]  
 
def sort(tuples):
    return sorted(tuples, key=last)
 
a=input("Enter a list of tuples:")
print("Sorted:")
print(sort(a))
 

Question 78

Question:

Write a program to swap the first and last value of a list.


Solution:

a=[]
n= int(input("Enter the number of elements in list:"))
for x in range(0,n):
    element=int(input("Enter element" + str(x+1) + ":"))
    a.append(element)
temp=a[0]
a[0]=a[n-1]
a[n-1]=temp
print("New list is:")
print(a)
 

Question 79

Question:

Write a program to remove the duplicate items from a list.


Solution:

a=[]
n= int(input("Enter the number of elements in list:"))
for x in range(0,n):
    element=int(input("Enter element" + str(x+1) + ":"))
    a.append(element)
b = set()
unique = []
for x in a:
    if x not in b:
        unique.append(x)
        b.add(x)
print("Non-duplicate items:")
print(unique)
 

Question 80

Question:

Write a program to read a list of words and return the length of the longest one.


Solution:

a=[]
n= int(input("Enter the number of elements in list:"))
for x in range(0,n):
    element=input("Enter element" + str(x+1) + ":")
    a.append(element)
max1=len(a[0])
temp=a[0]
for i in a:
    if(len(i)>max1):
       max1=len(i)
       temp=i
print("The word with the longest length is:")
print(temp)
 

Question 81

Question:

Write a program to remove the ith occurrence of the given word in list where words can repeat.


Solution:

a=[]
n= int(input("Enter the number of elements in list:"))
for x in range(0,n):
    element=input("Enter element" + str(x+1) + ":")
    a.append(element)
print(a)
c=[]
count=0
b=input("Enter word to remove: ")
n=int(input("Enter the occurrence to remove: "))
for i in a:
    if(i==b):
        count=count+1
        if(count!=n):
            c.append(i)
    else:
        c.append(i)
if(count==0):
    print("Item not found ")
else: 
    print("The number of repetitions is: ",count)
    print("Updated list is: ",c)
    print("The distinct elements are: ",set(a))

 

Question 82

Question:

Write a program to solve the maximum subarray problem using divide and conquer technique.


Solution:

def find_max_subarray(alist, start, end):
    """Returns (l, r, m) such that alist[l:r] is the maximum subarray in
    A[start:end] with sum m. Here A[start:end] means all A[x] for start <= x <
    end."""
    # base case
    if start == end - 1:
        return start, end, alist[start]
    else:
        mid = (start + end)//2
        left_start, left_end, left_max = find_max_subarray(alist, start, mid)
        right_start, right_end, right_max = find_max_subarray(alist, mid, end)
        cross_start, cross_end, cross_max = find_max_crossing_subarray(alist, start, mid, end)
        if (left_max > right_max and left_max > cross_max):
            return left_start, left_end, left_max
        elif (right_max > left_max and right_max > cross_max):
            return right_start, right_end, right_max
        else:
            return cross_start, cross_end, cross_max
 
def find_max_crossing_subarray(alist, start, mid, end):
    """Returns (l, r, m) such that alist[l:r] is the maximum subarray within
    alist with start <= l < mid <= r < end with sum m. The arguments start, mid,
    end must satisfy start <= mid <= end."""
    sum_left = float('-inf')
    sum_temp = 0
    cross_start = mid
    for i in range(mid - 1, start - 1, -1):
        sum_temp = sum_temp + alist[i]
        if sum_temp > sum_left:
            sum_left = sum_temp
            cross_start = i
 
    sum_right = float('-inf')
    sum_temp = 0
    cross_end = mid + 1
    for i in range(mid, end):
        sum_temp = sum_temp + alist[i]
        if sum_temp > sum_right:
            sum_right = sum_temp
            cross_end = i + 1
    return cross_start, cross_end, sum_left + sum_right
 
alist = input('Enter the list of numbers: ')
alist = alist.split()
alist = [int(x) for x in alist]
start, end, maximum = find_max_subarray(alist, 0, len(alist))
print('The maximum subarray starts at index {}, ends at index {}'
      ' and has sum {}.'.format(start, end - 1, maximum))

 

Question 83

Question:

Write a program to solve the maximum subarray problem using Kadane's algorithm.


Solution:

def find_max_subarray(alist, start, end):
    """Returns (l, r, m) such that alist[l:r] is the maximum subarray in
    A[start:end] with sum m. Here A[start:end] means all A[x] for start <= x <
    end."""
    max_ending_at_i = max_seen_so_far = alist[start]
    max_left_at_i = max_left_so_far = start
    # max_right_at_i is always i + 1
    max_right_so_far = start + 1
    for i in range(start + 1, end):
        if max_ending_at_i > 0:
            max_ending_at_i += alist[i]
        else:
            max_ending_at_i = alist[i]
            max_left_at_i = i
        if max_ending_at_i > max_seen_so_far:
            max_seen_so_far = max_ending_at_i
            max_left_so_far = max_left_at_i
            max_right_so_far = i + 1
    return max_left_so_far, max_right_so_far, max_seen_so_far
 
 
alist = input('Enter the list of numbers: ')
alist = alist.split()
alist = [int(x) for x in alist]
start, end, maximum = find_max_subarray(alist, 0, len(alist))
print('The maximum subarray starts at index {}, ends at index {}'
      ' and has sum {}.'.format(start, end - 1, maximum))

 

Question 84

Question:

Write a program to find the element that occurs odd number of times in a list.


Solution:

def find_odd_occurring(alist):
    """Return the element that occurs odd number of times in alist.
 
    alist is a list in which all elements except one element occurs an even
    number of times.
    """
    ans = 0
 
    for element in alist:
        ans ^= element
 
    return ans
 
 
alist = input('Enter the list: ').split()
alist = [int(i) for i in alist]
ans = find_odd_occurring(alist)
print('The element that occurs odd number of times:', ans)

 

Question 85

Question:

Write a program to check if a date is valid and print the incremented date if it is.


Solution:

date=input("Enter the date: ")
dd,mm,yy=date.split('/')
dd=int(dd)
mm=int(mm)
yy=int(yy)
if(mm==1 or mm==3 or mm==5 or mm==7 or mm==8 or mm==10 or mm==12):
    max1=31
elif(mm==4 or mm==6 or mm==9 or mm==11):
    max1=30
elif(yy%4==0 and yy%100!=0 or yy%400==0):
    max1=29
else:
    max1=28
if(mm<1 or mm>12):
    print("Date is invalid.")
elif(dd<1 or dd>max1):
    print("Date is invalid.")
elif(dd==max1 and mm!=12):
    dd=1
    mm=mm+1
    print("The incremented date is: ",dd,mm,yy)
elif(dd==31 and mm==12):
    dd=1
    mm=1
    yy=yy+1
    print("The incremented date is: ",dd,mm,yy)
else:
    dd=dd+1
    print("The incremented date is: ",dd,mm,yy)
 

Question 86

Question:

Write a program to compute simple interest given all the required values.


Solution:

principle=float(input("Enter the principle amount:"))
time=int(input("Enter the time(years):"))
rate=float(input("Enter the rate:"))
simple_interest=(principle*time*rate)/100
print("The simple interest is:",simple_interest)
 

Question 87

Question:

Write a program to check whether a given year is a leap year or not.


Solution:

year=int(input("Enter year to be checked:"))
if(year%4==0 and year%100!=0 or year%400==0):
    print("The year is a leap year!")
else:
    print("The year isn't a leap year!")

 

Question 88

Question:

Write a program to compute prime factors of an integer.


Solution:

n=int(input("Enter an integer:"))
print("Factors are:")
i=1
while(i<=n):
    k=0
    if(n%i==0):
        j=1
        while(j<=i):
            if(i%j==0):
                k=k+1
            j=j+1
        if(k==2):
            print(i)
    i=i+1
 
 

Question 89

Question:

Write a program to generate all the divisors of an integer.


Solution:

 
n=int(input("Enter an integer:"))
print("The divisors of the number are:")
for i in range(1,n+1):
    if(n%i==0):
        print(i)
 

Question 90

Question:

Write a program to print the table of a given number.


Solution:

 
n=int(input("Enter the number to print the tables for:"))
for i in range(1,11):
    print(n,"x",i,"=",n*i)
 

Question 91

Question:

Write a program to check if a number is an Armstrong number.


Solution:

 
n=int(input("Enter any number: "))
a=list(map(int,str(n)))
b=list(map(lambda x:x**3,a))
if(sum(b)==n):
    print("The number is an armstrong number. ")
else:
    print("The number isn't an arsmtrong number. ")
 

Question 92

Question:

Write a program to print the Pascal's triangle for n number of rows given by the user.


Solution:

 
n=int(input("Enter number of rows: "))
a=[]
for i in range(n):
    a.append([])
    a[i].append(1)
    for j in range(1,i):
        a[i].append(a[i-1][j-1]+a[i-1][j])
    if(n!=0):
        a[i].append(1)
for i in range(n):
    print("   "*(n-i),end=" ",sep=" ")
    for j in range(0,i+1):
        print('{0:6}'.format(a[i][j]),end=" ",sep=" ")
    print()
 

Question 93

Question:

Write a program to check if a number is a Perfect number.


Solution:

 
n = int(input("Enter any number: "))
sum1 = 0
for i in range(1, n):
    if(n % i == 0):
        sum1 = sum1 + i
if (sum1 == n):
    print("The number is a Perfect number!")
else:
    print("The number is not a Perfect number!")
 

Question 94

Question:

Write a program to find the LCM of two numbers.


Solution:

 
a=int(input("Enter the first number:"))
b=int(input("Enter the second number:"))
if(a>b):
    min1=a
else:
    min1=b
while(1):
    if(min1%a==0 and min1%b==0):
        print("LCM is:",min1)
        break
    min1=min1+1
 

Question 95

Question:

Write a program to find the GCD of two numbers.


Solution:

 
import math
a=int(input("Enter the first number:"))
b=int(input("Enter the second number:"))
print("The GCD of the two numbers is",math.gcd(a,b))
 

Question 96

Question:

Write a program to compute a polynomial equation given that the coefficients of the polynomial are stored in the list.


Solution:

import math
print("Enter the coefficients of the form ax^3 + bx^2 + cx + d")
lst=[]
for i in range(0,4):
    a=int(input("Enter coefficient:"))
    lst.append(a)
x=int(input("Enter the value of x:"))
sum1=0
j=3
for i in range(0,3):
    while(j>0):
        sum1=sum1+(lst[i]*math.pow(x,j))
        break
    j=j-1
sum1=sum1+lst[3]
print("The value of the polynomial is:",sum1)
 

Question 97

Question:

Write a program to check if two numbers are amicable numbers.


Solution:

x=int(input('Enter number 1: '))
y=int(input('Enter number 2: '))
sum1=0
sum2=0
for i in range(1,x):
    if x%i==0:
        sum1+=i
for j in range(1,y):
    if y%j==0:
        sum2+=j
if(sum1==y and sum2==x):
    print('Amicable!')
else:
    print('Not Amicable!')
 

Question 98

Question:

Write a program to find the area of a triangle given all three sides.


Solution:

import math
a=int(input("Enter first side: "))
b=int(input("Enter second side: "))
c=int(input("Enter third side: "))
s=(a+b+c)/2
area=math.sqrt(s*(s-a)*(s-b)*(s-c))
print("Area of the triangle is: ",round(area,2))
 

Question 99

Question:

Write a program to find the gravitational force acting between two objects.


Solution:

m1=float(input("Enter the first mass: "))
m2=float(input("Enter the second mass: "))
r=float(input("Enter the distance between the centres of the masses: "))
G=6.673*(10**-11)
f=(G*m1*m2)/(r**2)
print("Hence, the gravitational force is: ",round(f,2),"N")

 

Question 100

Question:

Write a program to find the sum of sine series.


Solution:

import math
def sin(x,n):
    sine = 0
    for i in range(n):
        sign = (-1)**i
        pi=22/7
        y=x*(pi/180)
        sine = sine + ((y**(2.0*i+1))/math.factorial(2*i+1))*sign
    return sine
x=int(input("Enter the value of x in degrees:"))
n=int(input("Enter the number of terms:"))
print(round(sin(x,n),2))

 

Question 101

Question:

Write a program to find the sum of cosine series.


Solution:

import math
def cosine(x,n):
    cosx = 1
    sign = -1
    for i in range(2, n, 2):
        pi=22/7
        y=x*(pi/180)
        cosx = cosx + (sign*(y**i))/math.factorial(i)
        sign = -sign
    return cosx
x=int(input("Enter the value of x in degrees:"))
n=int(input("Enter the number of terms:"))
print(round(cosine(x,n),2))

 

Question 102

Question:

Write a program to find the sum of first N Natural Numbers.


Solution:

n=int(input("Enter a number: "))
sum1 = 0
while(n > 0):
    sum1=sum1+n
    n=n-1
print("The sum of first n natural numbers is",sum1)
 

Question 103

Question:

Write a program to find the sum of series: 1 + 1/2 + 1/3 + ….. + 1/N.


Solution:

n=int(input("Enter the number of terms: "))
sum1=0
for i in range(1,n+1):
    sum1=sum1+(1/i)
print("The sum of series is",round(sum1,2))
 

Question 104

Question:

Write a program to determine all Pythagorean triplets till the upper limit.


Solution:

limit=int(input("Enter upper limit:"))
c=0
m=2
while(c<limit):
    for n in range(1,m+1):
        a=m*m-n*n
        b=2*m*n
        c=m*m+n*n
        if(c>limit):
            break
        if(a==0 or b==0 or c==0):
            break
        print(a,b,c)
    m=m+1
 

Question 105

Question:

Write a program to search the number of times a particular number occurs in a list.


Solution:

a=[]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
    b=int(input("Enter element:"))
    a.append(b)
k=0
num=int(input("Enter the number to be counted:"))
for j in a:
    if(j==num):
        k=k+1
print("Number of times",num,"appears is",k)

 

Question 106

Question:

Write a program to test Collatz conjecture for a given number.


Solution:

def collatz(n):
    while n > 1:
        print(n, end=' ')
        if (n % 2):
            # n is odd
            n = 3*n + 1
        else:
            # n is even
            n = n//2
    print(1, end='')
 
 
n = int(input('Enter n: '))
print('Sequence: ', end='')
collatz(n)
 
 

Question 107

Question:

Write a program to count set bits in a number.


Solution:

 
def count_set_bits(n):
    count = 0
    while n:
        n &= n - 1
        count += 1
    return count
 
 
n = int(input('Enter n: '))
print('Number of set bits:', count_set_bits(n))
 

Question 108

Question:

Write a program to find whether a number is a power of two.


Solution:

 
def is_power_of_two(n):
    """Return True if n is a power of two."""
    if n <= 0:
        return False
    else:
        return n & (n - 1) == 0
 
 
n = int(input('Enter a number: '))
 
if is_power_of_two(n):
    print('{} is a power of two.'.format(n))
else:
    print('{} is not a power of two.'.format(n))
 

Question 109

Question:

Write a program to clear the rightmost set bit of a number.


Solution:

 
def clear_rightmost_set_bit(n):
    """Clear rightmost set bit of n and return it."""
    return n & (n - 1)
 
 
n = int(input('Enter a number: '))
ans = clear_rightmost_set_bit(n)
print('n with its rightmost set bit cleared equals:', ans)
 

Question 110

Question:

Write a program to generate all gray codes using recursion.


Solution:

 
def get_gray_codes(n):
    """Return n-bit Gray code in a list."""
    if n == 0:
        return ['']
    first_half = get_gray_codes(n - 1)
    second_half = first_half.copy()
 
    first_half = ['0' + code for code in first_half]
    second_half = ['1' + code for code in reversed(second_half)]
 
    return first_half + second_half
 
 
n = int(input('Enter the number of bits: '))
codes = get_gray_codes(n)
print('All {}-bit Gray Codes:'.format(n))
print(codes)
 

Question 111

Question:

Write a program to convert Gray code to binary.


Solution:

 
def gray_to_binary(n):
    """Convert Gray codeword to binary and return it."""
    n = int(n, 2) # convert to int
 
    mask = n
    while mask != 0:
        mask >>= 1
        n ^= mask
 
    # bin(n) returns n's binary representation with a '0b' prefixed
    # the slice operation is to remove the prefix
    return bin(n)[2:]
 
 
g = input('Enter Gray codeword: ')
b = gray_to_binary(g)
print('In binary:', b)
 

Question 112

Question:

Write a program to convert binary to Gray code.


Solution:

 
def binary_to_gray(n):
    """Convert Binary to Gray codeword and return it."""
    n = int(n, 2) # convert to int
    n ^= (n >> 1)
 
    # bin(n) returns n's binary representation with a '0b' prefixed
    # the slice operation is to remove the prefix
    return bin(n)[2:]
 
 
g = input('Enter binary number: ')
b = binary_to_gray(g)
print('Gray codeword:', b)
 

Question 113

Question:

Write a program to replace all occurrences of 'a' with '$' in a string.


Solution:

string=input("Enter string:")
string=string.replace('a','$')
string=string.replace('A','$')
print("Modified string:")
print(string)
 

Question 114

Question:

Write a program to remove the nth index character from a non-empty string.


Solution:

def remove(string, n):  
      first = string[:n]   
      last = string[n+1:]  
      return first + last
string=input("Enter the string:")
n=int(input("Enter the index of the character to remove:"))
print("Modified string:")
print(remove(string, n))
 

Question 115

Question:

Write a program to detect if two strings are anagrams.


Solution:

s1=input("Enter first string:")
s2=input("Enter second string:")
if(sorted(s1)==sorted(s2)):
      print("The strings are anagrams.")
else:
      print("The strings aren't anagrams.")

 

Question 116

Question:

Write a program to form a string where the first character and the last character have been exchanged.


Solution:

def change(string):
      return string[-1:] + string[1:-1] + string[:1]
string=input("Enter string:")
print("Modified string:")
print(change(string))
 
 

Question 117

Question:

Write a program to count the number of vowels in a string.


Solution:

 
string=input("Enter string:")
vowels=0
for i in string:
      if(i=='a' or i=='e' or i=='i' or i=='o' or i=='u' or i=='A' or i=='E' or i=='I' or i=='O' or i=='U'):
            vowels=vowels+1
print("Number of vowels are:")
print(vowels)
 

Question 118

Question:

Write a program to take a string and replace every blank space with a hyphen.


Solution:

 
string=input("Enter string:")
string=string.replace(' ','-')
print("Modified string:")
print(string)
 

Question 119

Question:

Write a program to calculate the length of a string without using library functions.


Solution:

 
string=input("Enter string:")
count=0
for i in string:
      count=count+1
print("Length of the string is:")
print(count)
 

Question 120

Question:

Write a program to remove the characters of odd index values in a string.


Solution:

def modify(string):  
  final = ""   
  for i in range(len(string)):  
    if i % 2 == 0:  
      final = final + string[i]  
  return final
string=input("Enter string:")
print("Modified string is:")
print(modify(string))
 

Question 121

Question:

Write a program to calculate the number of words and characters present in a string.


Solution:

 
string=input("Enter string:")
char=0
word=1
for i in string:
      char=char+1
      if(i==' '):
            word=word+1
print("Number of words in the string:")
print(word)
print("Number of characters in the string:")
print(char)
 

Question 122

Question:

Write a program to take in two strings and display the larger string without using built-in functions.


Solution:

 
string1=input("Enter first string:")
string2=input("Enter second string:")
count1=0
count2=0
for i in string1:
      count1=count1+1
for j in string2:
      count2=count2+1
if(count1<count2):
      print("Larger string is:")
      print(string2)
elif(count1==count2):
      print("Both strings are equal.")
else:
      print("Larger string is:")
      print(string1)
 

Question 123

Question:

Write a program to count number of lowercase characters in a string.


Solution:

 
string=input("Enter string:")
count=0
for i in string:
      if(i.islower()):
            count=count+1
print("The number of lowercase characters is:")
print(count)
 

Question 124

Question:

Write a program to count the number of lowercase letters and uppercase letters in a string.


Solution:

string=input("Enter string:")
count1=0
count2=0
for i in string:
      if(i.islower()):
            count1=count1+1
      elif(i.isupper()):
            count2=count2+1
print("The number of lowercase characters is:")
print(count1)
print("The number of uppercase characters is:")
print(count2)
 

Question 125

Question:

Write a program to calculate the number of digits and letters in a string.


Solution:

string=input("Enter string:")
count1=0
count2=0
for i in string:
      if(i.isdigit()):
            count1=count1+1
      count2=count2+1
print("The number of digits is:")
print(count1)
print("The number of characters is:")
print(count2)
 

Question 126

Question:

Write a program to form a new string made of the first 2 characters and last 2 characters from a given string.


Solution:

string=input("Enter string:")
count=0
for i in string:
      count=count+1
new=string[0:2]+string[count-2:count]
print("Newly formed string is:")
print(new)
 

Question 127

Question:

Write a program to count the occurrences of each word in a given string sentence.


Solution:

string=input("Enter string:")
word=input("Enter word:")
a=[]
count=0
a=string.split(" ")
for i in range(0,len(a)):
      if(word==a[i]):
            count=count+1
print("Count of the word is:")
print(count)

 

Question 128

Question:

Write a program to check if a substring is present in a given string.


Solution:

string=input("Enter string:")
sub_str=input("Enter word:")
if(string.find(sub_str)==-1):
      print("Substring not found in string!")
else:
      print("Substring in string!")

 

Question 129

Question:

Write a program to print all permutations of a string in lexicographic order without using recursion.


Solution:

from math import factorial
 
def print_permutations_lexicographic_order(s):
    """Print all permutations of string s in lexicographic order."""
    seq = list(s)
 
    # there are going to be n! permutations where n = len(seq)
    for _ in range(factorial(len(seq))):
        # print permutation
        print(''.join(seq))
 
        # find p such that seq[p:] is the largest sequence with elements in
        # descending lexicographic order
        p = len(seq) - 1
        while p > 0 and seq[p - 1] > seq[p]:
            p -= 1
 
        # reverse seq[p:]
        seq[p:] = reversed(seq[p:])
 
        if p > 0:
            # find q such that seq[q] is the smallest element in seq[p:] such that
            # seq[q] > seq[p - 1]
            q = p
            while seq[p - 1] > seq[q]:
                q += 1
 
            # swap seq[p - 1] and seq[q]
            seq[p - 1], seq[q] = seq[q], seq[p - 1]
 
 
s = input('Enter the string: ')
print_permutations_lexicographic_order(s)

 

Question 130

Question:

Write a program to print all permutations of a string in lexicographic order using recursion.


Solution:

from math import factorial
 
def print_permutations_lexicographic_order(s):
    """Print all permutations of string s in lexicographic order."""
    seq = list(s)
    for _ in range(factorial(len(seq))):
        print(''.join(seq))
        nxt = get_next_permutation(seq)
        # if seq is the highest permutation
        if nxt is None:
            # then reverse it
            seq.reverse()
        else:
            seq = nxt
 
def get_next_permutation(seq):
    """Return next greater lexicographic permutation. Return None if cannot.
 
    This will return the next greater permutation of seq in lexicographic
    order. If seq is the highest permutation then this will return None.
 
    seq is a list.
    """
    if len(seq) == 0:
        return None
 
    nxt = get_next_permutation(seq[1:])
 
    # if seq[1:] is the highest permutation
    if nxt is None:
        # reverse seq[1:], so that seq[1:] now is in ascending order
        seq[1:] = reversed(seq[1:])
 
        # find q such that seq[q] is the smallest element in seq[1:] such that
        # seq[q] > seq[0]
        q = 1
        while q < len(seq) and seq[0] > seq[q]:
            q += 1
 
        # if cannot find q, then seq is the highest permutation
        if q == len(seq):
            return None
 
        # swap seq[0] and seq[q]
        seq[0], seq[q] = seq[q], seq[0]
 
        return seq
    else:
        return [seq[0]] + nxt
 
 
s = input('Enter the string: ')
print_permutations_lexicographic_order(s)
 

Question 131

Question:

Write a program to add a key-value pair to a dictionary.


Solution:

key=int(input("Enter the key (int) to be added:"))
value=int(input("Enter the value for the key to be added:"))
d={}
d.update({key:value})
print("Updated dictionary is:")
print(d)
 

Question 132

Question:

Write a program to concatenate two dictionaries into one dictionary.


Solution:

d1={'A':1,'B':2}
d2={'C':3}
d1.update(d2)
print("Concatenated dictionary is:")
print(d1)
 

Question 133

Question:

Write a program to check if a given key exists in a dictionary or not.


Solution:

d={'A':1,'B':2,'C':3}
key=input("Enter key to check:")
if key in d.keys():
      print("Key is present and value of the key is:")
      print(d[key])
else:
      print("Key isn't present!")

 

Question 134

Question:

Write a program to find the sum all the items in a dictionary.


Solution:

d={'A':100,'B':540,'C':239}
print("Total sum of values in the dictionary:")
print(sum(d.values()))
 
 

Question 135

Question:

Write a program to multiply all the items in a dictionary.


Solution:

 
d={'A':10,'B':10,'C':239}
tot=1
for i in d:    
    tot=tot*d[i]
print(tot)
 

Question 136

Question:

Write a program to remove the given key from a dictionary.


Solution:

 
d = {'a':1,'b':2,'c':3,'d':4}
print("Initial dictionary")
print(d)
key=input("Enter the key to delete(a-d):")
if key in d: 
    del d[key]
else:
    print("Key not found!")
    exit(0)
print("Updated dictionary")
print(d)
 

Question 137

Question:

Write a program to form a dictionary from an object of a class.


Solution:

 
class A(object):  
     def __init__(self):  
         self.A=1  
         self.B=2  
obj=A()  
print(obj.__dict__)
 

Question 138

Question:

Write a program to map two lists into a dictionary.


Solution:

keys=[]
values=[]
n=int(input("Enter number of elements for dictionary:"))
print("For keys:")
for x in range(0,n):
    element=int(input("Enter element" + str(x+1) + ":"))
    keys.append(element)
print("For values:")
for x in range(0,n):
    element=int(input("Enter element" + str(x+1) + ":"))
    values.append(element)
d=dict(zip(keys,values))
print("The dictionary is:")
print(d)
 

Question 139

Question:

Write a program to count the frequency of words appearing in a string using a dictionary.


Solution:

 
test_string=input("Enter string:")
l=[]
l=test_string.split()
wordfreq=[l.count(p) for p in l]
print(dict(zip(l,wordfreq)))
 

Question 140

Question:

Write a program to create a dictionary with key as first character and value as words starting with that character.


Solution:

 
test_string=input("Enter string:")
l=test_string.split()
d={}
for word in l:
    if(word[0] not in d.keys()):
        d[word[0]]=[]
        d[word[0]].append(word)
    else:
        if(word not in d[word[0]]):
          d[word[0]].append(word)
for k,v in d.items():
        print(k,":",v)
 

Question 141

Question:

Write a program to count the number of vowels present in a string using sets.


Solution:

 
s=input("Enter string:")
count = 0
vowels = set("aeiou")
for letter in s:
    if letter in vowels:
        count += 1
print("Count of the vowels is:")
print(count)
 

Question 142

Question:

Write a program to check common letters in the two input strings.


Solution:

s1=input("Enter first string:")
s2=input("Enter second string:")
a=list(set(s1)&set(s2))
print("The common letters are:")
for i in a:
    print(i)
 

Question 143

Question:

Write a program to display which letters are in the first string but not in the second string.


Solution:

s1=input("Enter first string:")
s2=input("Enter second string:")
a=list(set(s1)-set(s2))
print("The letters are:")
for i in a:
    print(i)
 

Question 144

Question:

Write a program to display which letters is present in both the strings.


Solution:

s1=input("Enter first string:")
s2=input("Enter second string:")
a=list(set(s1)|set(s2))
print("The letters are:")
for i in a:
    print(i)
 

Question 145

Question:

Write a program to determine whether a given number is even or odd recursively.


Solution:

def check(n):
    if (n < 2):
        return (n % 2 == 0)
    return (check(n - 2))
n=int(input("Enter number:"))
if(check(n)==True):
      print("Number is even!")
else:
      print("Number is odd!")

 

Question 146

Question:

Write a program to determine how many times a given letter occurs in a string recursively.


Solution:

def check(string,ch):
      if not string:
        return 0
      elif string[0]==ch:
            return 1+check(string[1:],ch)
      else:
            return check(string[1:],ch)
string=input("Enter string:")
ch=input("Enter character to check:")
print("Count is:")
print(check(string,ch))

 

Question 147

Question:

Write a program to find the fibonacci series using recursion.


Solution:

def fibonacci(n):
    if(n <= 1):
        return n
    else:
        return(fibonacci(n-1) + fibonacci(n-2))
n = int(input("Enter number of terms:"))
print("Fibonacci sequence:")
for i in range(n):
    print (fibonacci(i))

 

Question 148

Question:

Write a program to find the factorial of a number using recursion.


Solution:

def factorial(n):
    if(n <= 1):
        return 1
    else:
        return(n*factorial(n-1))
n = int(input("Enter number:"))
print("Factorial:")
print(factorial(n))
 

Question 149

Question:

Write a program to find the sum of elements in a list recursively.


Solution:

def sum_arr(arr,size):
   if (size == 0):
     return 0
   else:
     return arr[size-1] + sum_arr(arr,size-1)
n=int(input("Enter the number of elements for list:"))
a=[]
for i in range(0,n):
    element=int(input("Enter element:"))
    a.append(element)
print("The list is:")
print(a)
print("Sum of items in list:")
b=sum_arr(a,n)
print(b)
 

Question 150

Question:

Write a program to find the binary equivalent of a number recursively.


Solution:

l=[]
def convert(b):
    if(b==0):
        return l
    dig=b%2
    l.append(dig)
    convert(b//2)
a=int(input("Enter a number: "))
convert(a)
l.reverse()
print("Binary equivalent:")
for i in l:
    print (i)
 

Question 151

Question:

Write a program to find the LCM of two numbers using recursion.


Solution:

def lcm(a,b):
    lcm.multiple=lcm.multiple+b
    if((lcm.multiple % a == 0) and (lcm.multiple % b == 0)):
        return lcm.multiple;
    else:
        lcm(a, b)
    return lcm.multiple
lcm.multiple=0
a=int(input("Enter first number:"))
b=int(input("Enter second number:"))
if(a>b):
    LCM=lcm(b,a)
else:
    LCM=lcm(a,b)
print(LCM)

 

Question 152

Question:

Write a program to find the GCD of two numbers using recursion.


Solution:

def gcd(a,b):
    if(b==0):
        return a
    else:
        return gcd(b,a%b)
a=int(input("Enter first number:"))
b=int(input("Enter second number:"))
GCD=gcd(a,b)
print("GCD is: ")
print(GCD)
 
 

Question 153

Question:

Write a program to read the contents of a file.


Solution:

 
a=str(input("Enter the name of the file with .txt extension:"))
file2=open(a,'r')
line=file2.readline()
while(line!=""):
    print(line)
    line=file2.readline()
file2.close()
 

Question 154

Question:

Write a program to count the number of words in a text file.


Solution:

 
fname = input("Enter file name: ")
 
num_words = 0
 
with open(fname, 'r') as f:
    for line in f:
        words = line.split()
        num_words += len(words)
print("Number of words:")
print(num_words)
 

Question 155

Question:

Write a program to count the number of lines in a text file.


Solution:

 
fname = input("Enter file name: ")
num_lines = 0
with open(fname, 'r') as f:
    for line in f:
        num_lines += 1
print("Number of lines:")
print(num_lines)
 

Question 156

Question:

Write a program to read a string from the user and appends it into a file.


Solution:

fname = input("Enter file name: ")
file3=open(fname,"a")
c=input("Enter string to append: \n");
file3.write("\n")
file3.write(c)
file3.close()
print("Contents of appended file:");
file4=open(fname,'r')
line1=file4.readline()
while(line1!=""):
    print(line1)
    line1=file4.readline()    
file4.close()
 

Question 157

Question:

Write a program to count the occurrences of a word in a text file.


Solution:

 
fname = input("Enter file name: ")
word=input("Enter word to be searched:")
k = 0
 
with open(fname, 'r') as f:
    for line in f:
        words = line.split()
        for i in words:
            if(i==word):
                k=k+1
print("Occurrences of the word:")
print(k)
 

Question 158

Question:

Write a program to copy the contents of one file into another.


Solution:

 
with open("test.txt") as f:
    with open("out.txt", "w") as f1:
        for line in f:
            f1.write(line)
 

Question 159

Question:

Write a program to count the occurrences of a letter in a text file.


Solution:

 
fname = input("Enter file name: ")
l=input("Enter letter to be searched:")
k = 0
 
with open(fname, 'r') as f:
    for line in f:
        words = line.split()
        for i in words:
            for letter in i:
                if(letter==l):
                    k=k+1
print("Occurrences of the letter:")
print(k)
 

Question 160

Question:

Write a program to read a text file and print all numbers present in the text file.


Solution:

fname = input("Enter file name: ")
 
with open(fname, 'r') as f:
    for line in f:
        words = line.split()
        for i in words:
            for letter in i:
                if(letter.isdigit()):
                    print(letter)
 

Question 161

Question:

Write a program to append the contents of one file to another file.


Solution:

name1 = input("Enter file to be read from: ")
name2 = input("Enter file to be appended to: ")
fin = open(name1, "r")
data2 = fin.read()
fin.close()
fout = open(name2, "a")
fout.write(data2)
fout.close()
 

Question 162

Question:

Write a program to count the number of blank spaces in a text file.


Solution:

fname = input("Enter file name: ")
k = 0
 
with open(fname, 'r') as f:
    for line in f:
        words = line.split()
        for i in words:
            for letter in i:
                if(letter.isspace):
                    k=k+1
print("Occurrences of blank spaces:")
print(k)
 

Question 163

Question:

Write a program to read a file and capitalize the first letter of every word in the file.


Solution:

fname = input("Enter file name: ")
 
with open(fname, 'r') as f:
    for line in f:
        l=line.title()
        print(l)

 

Question 164

Question:

Write a program to read the contents of a file in reverse order.


Solution:

filename=input("Enter file name: ")
for line in reversed(list(open(filename))):
    print(line.rstrip())

 

Question 165

Question:

Write a program to find the area of a rectangle using classes.


Solution:

class rectangle():
    def __init__(self,breadth,length):
        self.breadth=breadth
        self.length=length
    def area(self):
        return self.breadth*self.length
a=int(input("Enter length of rectangle: "))
b=int(input("Enter breadth of rectangle: "))
obj=rectangle(a,b)
print("Area of rectangle:",obj.area())
 
print()

 

Question 166

Question:

Write a program to append, delete and display elements of a list using classes.


Solution:

class check():
    def __init__(self):
        self.n=[]
    def add(self,a):
        return self.n.append(a)
    def remove(self,b):
        self.n.remove(b)
    def dis(self):
        return (self.n)
 
obj=check()
 
choice=1
while choice!=0:
    print("0. Exit")
    print("1. Add")
    print("2. Delete")
    print("3. Display")
    choice=int(input("Enter choice: "))
    if choice==1:
        n=int(input("Enter number to append: "))
        obj.add(n)
        print("List: ",obj.dis())
 
    elif choice==2:
        n=int(input("Enter number to remove: "))
        obj.remove(n)
        print("List: ",obj.dis())
 
    elif choice==3:
        print("List: ",obj.dis())
    elif choice==0:
        print("Exiting!")
    else:
        print("Invalid choice!!")
 
print()
 

Question 167

Question:

Write a program to implement a binary heap.


Solution:

class BinaryHeap:
    def __init__(self):
        self.items = []
 
    def size(self):
        return len(self.items)
 
    def parent(self, i):
        return (i - 1)//2
 
    def left(self, i):
        return 2*i + 1
 
    def right(self, i):
        return 2*i + 2
 
    def get(self, i):
        return self.items[i]
 
    def get_max(self):
        if self.size() == 0:
            return None
        return self.items[0]
 
    def extract_max(self):
        if self.size() == 0:
            return None
        largest = self.get_max()
        self.items[0] = self.items[-1]
        del self.items[-1]
        self.max_heapify(0)
        return largest
 
    def max_heapify(self, i):
        l = self.left(i)
        r = self.right(i)
        if (l <= self.size() - 1 and self.get(l) > self.get(i)):
            largest = l
        else:
            largest = i
        if (r <= self.size() - 1 and self.get(r) > self.get(largest)):
            largest = r
        if (largest != i):
            self.swap(largest, i)
            self.max_heapify(largest)
 
    def swap(self, i, j):
        self.items[i], self.items[j] = self.items[j], self.items[i]
 
    def insert(self, key):
        index = self.size()
        self.items.append(key)
 
        while (index != 0):
            p = self.parent(index)
            if self.get(p) < self.get(index):
                self.swap(p, index)
            index = p
 
 
bheap = BinaryHeap()
 
print('Menu')
print('insert <data>')
print('max get')
print('max extract')
print('quit')
 
while True:
    do = input('What would you like to do? ').split()
 
    operation = do[0].strip().lower()
    if operation == 'insert':
        data = int(do[1])
        bheap.insert(data)
    elif operation == 'max':
        suboperation = do[1].strip().lower()
        if suboperation == 'get':
            print('Maximum value: {}'.format(bheap.get_max()))
        elif suboperation == 'extract':
            print('Maximum value removed: {}'.format(bheap.extract_max()))
 
    elif operation == 'quit':
        break
 

Question 168

Question:

Write a program to implement a binomial tree.


Solution:

class BinomialTree:
    def __init__(self, key):
        self.key = key
        self.children = []
        self.order = 0
 
    def add_at_end(self, t):
        self.children.append(t)
        self.order = self.order + 1
 
 
trees = []
 
print('Menu')
print('create <key>')
print('combine <index1> <index2>')
print('quit')
 
while True:
    do = input('What would you like to do? ').split()
 
    operation = do[0].strip().lower()
    if operation == 'create':
        key = int(do[1])
        btree = BinomialTree(key)
        trees.append(btree)
        print('Binomial tree created.')
    elif operation == 'combine':
        index1 = int(do[1])
        index2 = int(do[2])
        if trees[index1].order == trees[index2].order:
            trees[index1].add_at_end(trees[index2])
            del trees[index2]
            print('Binomial trees combined.')
        else:
            print('Orders of the trees need to be the same.')
 
    elif operation == 'quit':
        break
 
    print('{:>8}{:>12}{:>8}'.format('Index', 'Root key', 'Order'))
    for index, t in enumerate(trees):
        print('{:8d}{:12d}{:8d}'.format(index, t.key, t.order))
 

Question 169

Question:

Write a program to implement Tower of Hanoi.


Solution:

def hanoi(disks, source, auxiliary, target):
    if disks == 1:
        print('Move disk 1 from peg {} to peg {}.'.format(source, target))
        return
 
    hanoi(disks - 1, source, target, auxiliary)
    print('Move disk {} from peg {} to peg {}.'.format(disks, source, target))
    hanoi(disks - 1, auxiliary, source, target)
 
 
disks = int(input('Enter number of disks: '))
hanoi(disks, 'A', 'B', 'C')

 

Question 170

Question:

Write a program to implement birthday dictionary.


Solution:

if __name__ == '__main__':

    birthdays = {
        'Albert Einstein': '03/14/1879',
        'Benjamin Franklin': '01/17/1706',
        'Ada Lovelace': '12/10/1815',
        'Donald Trump': '06/14/1946',
        'Rowan Atkinson': '01/6/1955'}

    print('Welcome to the birthday dictionary. We know the birthdays of:')
    for name in birthdays:
        print(name)

    print('Who\'s birthday do you want to look up?')
    name = input()
    if name in birthdays:
        print('{}\'s birthday is {}.'.format(name, birthdays[name]))
    else:
        print('Sadly, we don\'t have {}\'s birthday.'.format(name))
 

Question 171

Question:

Write a program to implement guess letters.


Solution:

 
if __name__ == '__main__':
	print("Welcome to hangman!!")
	word = "EVAPORATE"
	guessed = "_" * len(word)
	word = list(word)
	guessed = list(guessed)
	lstGuessed = []
	letter = input("guess letter: ")
	while True:
		if letter.upper() in lstGuessed:
			letter = ''
			print("Already guessed!!")
		elif letter.upper() in word:
			index = word.index(letter.upper())
			guessed[index] = letter.upper()
			word[index] = '_'
		else:
			print(''.join(guessed))
			if letter is not '':
				lstGuessed.append(letter.upper())
			letter = input("guess letter: ")

		if '_' not in guessed:
			print("You won!!")
			break
 

Question 172

Question:

Write a program to implement password generator.


Solution:

 
import random

s = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()?"
passlen = 8
p =  "".join(random.sample(s,passlen ))
print (p)
 

Question 173

Question:

Write a program to display calendar of the given month and year.


Solution:

 
# importing calendar module
import calendar

yy = 2014  # year
mm = 11    # month

# To take month and year input from the user
# yy = int(input("Enter year: "))
# mm = int(input("Enter month: "))

# display the calendar
print(calendar.month(yy, mm))
 

Question 174

Question:

Write a program to add two matrices.


Solution:

X = [[12,7,3],
    [4 ,5,6],
    [7 ,8,9]]

Y = [[5,8,1],
    [6,7,3],
    [4,5,9]]

result = [[0,0,0],
         [0,0,0],
         [0,0,0]]

# iterate through rows
for i in range(len(X)):
   # iterate through columns
   for j in range(len(X[0])):
       result[i][j] = X[i][j] + Y[i][j]

for r in result:
   print(r)
 

Question 175

Question:

Write a program to transpose a matrix.


Solution:

 
X = [[12,7],
    [4 ,5],
    [3 ,8]]

result = [[0,0,0],
         [0,0,0]]

# iterate through rows
for i in range(len(X)):
   # iterate through columns
   for j in range(len(X[0])):
       result[j][i] = X[i][j]

for r in result:
   print(r)
 

Question 176

Question:

***Write a program to multiply two matrices. ***


Solution:

 
# 3x3 matrix
X = [[12,7,3],
    [4 ,5,6],
    [7 ,8,9]]
# 3x4 matrix
Y = [[5,8,1,2],
    [6,7,3,0],
    [4,5,9,1]]
# result is 3x4
result = [[0,0,0,0],
         [0,0,0,0],
         [0,0,0,0]]

# iterate through rows of X
for i in range(len(X)):
   # iterate through columns of Y
   for j in range(len(Y[0])):
       # iterate through rows of Y
       for k in range(len(Y)):
           result[i][j] += X[i][k] * Y[k][j]

for r in result:
   print(r)
 

Question 177

Question:

Write a program to remove punctuations from a string.


Solution:

 
# define punctuation
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''

my_str = "Hello!!!, he said ---and went."

# To take input from the user
# my_str = input("Enter a string: ")

# remove punctuation from the string
no_punct = ""
for char in my_str:
   if char not in punctuations:
       no_punct = no_punct + char

# display the unpunctuated string
print(no_punct)
 

Question 178

Question:

Write a program to find the hash of a file and display it.


Solution:

import hashlib

def hash_file(filename):
   """"This function returns the SHA-1 hash
   of the file passed into it"""

   # make a hash object
   h = hashlib.sha1()

   # open file for reading in binary mode
   with open(filename,'rb') as file:

       # loop till the end of the file
       chunk = 0
       while chunk != b'':
           # read only 1024 bytes at a time
           chunk = file.read(1024)
           h.update(chunk)

   # return the hex representation of digest
   return h.hexdigest()

message = hash_file("languages.txt")
print(message)
 

Question 179

Question:

Write a program to find the size (resolution) of a image.


Solution:

def jpeg_res(filename):
   """"This function prints the resolution of the jpeg image file passed into it"""

   # open image for reading in binary mode
   with open(filename,'rb') as img_file:

       # height of image (in 2 bytes) is at 164th position
       img_file.seek(163)

       # read the 2 bytes
       a = img_file.read(2)

       # calculate height
       height = (a[0] << 8) + a[1]

       # next 2 bytes is width
       a = img_file.read(2)

       # calculate width
       width = (a[0] << 8) + a[1]

   print("The resolution of the image is",width,"x",height)

jpeg_res("img1.jpg")
 

Question 180

Question:

Write a program to read website source code.


Solution:

import sys

if sys.version_info[0] == 3:
    from urllib.request import urlopen
else:
    # Not Python 3 - today, it is most likely to be Python 2
    # But note that this might need an update when Python 4
    # might be around one day
    from urllib import urlopen


# Your code where you can use urlopen
with urlopen("http://www.myw3schools.com") as url:
    s = url.read()

print(s)

Question 181

Question:

Write a program to get IP address of your computer.


Solution:

import socket    
hostname = socket.gethostname()    
IPAddr = socket.gethostbyname(hostname)    
print("Your Computer Name is:" + hostname)    
print("Your Computer IP Address is:" + IPAddr) 

Question 182

Question:

Write a program to get all links from a webpage.


Solution:

from bs4 import BeautifulSoup
from urllib.request import Request, urlopen

req = Request("http://www.myw3schools.com")
html_page = urlopen(req)

soup = BeautifulSoup(html_page, "lxml")

links = []
for link in soup.findAll('a'):
    links.append(link.get('href'))

print(links)

Question 183

Question:

Write a program to illustrate Dice Roll Simulator.


Solution:

import random
min = 1
max = 6

roll_again = "yes"

while roll_again == "yes" or roll_again == "y":
    print ("Rolling the dices...")
    print ("The values are....")
    print (random.randint(min, max))
    print (random.randint(min, max))

    roll_again = input("Roll the dices again?")



↑Back

9 Interesting Python Facts

In python we can return multiple values:

def XYZ(): 
    p = 3 
    q = 2
    return p, q  
  
a, b = XYZ() 
print(a, b) 

Output on the screen:

 
3 2

Allows Negative Indexing:

my_list = ['apple', 'orange', 'grapes'] 
print(my_list[-2]) 

Output on the screen:

 
orange

Combine Multiple Strings:

my_list = ['I', 'Love', 'Python'] 
print(''.join(my_list)) 

Output on the screen:

 
ILovePython

We can swap two objects in Python:

a = 3
b = 2
  
print('Before Swapping') 
print(a, b) 
  
a, b = b, a 
print('After Swapping') 
print(a, b)  

Output on the screen:

 
Before Swapping
3 2
After Swapping
2 3

We can know about Python version:

import sys 
print("My Python version Number: {}".format(sys.version))

Output on the screen:

 
My Python version Number: 3.7.3 (default, Mar 27 2019, 17:13:21) [MSC v.1915 64 bit (AMD64)]

We can Store all values of List in new separate variables:

x = [1, 2, 3] 
a, b, c = x  
print(a) 
print(b) 
print(c)

Output on the screen:

 
1
2
3

We can convert nested list into one list:

import itertools  
x = [[1, 2], [3, 4], [5, 6]] 
print(list(itertools.chain.from_iterable(x))) 

Output on the screen:

 
[1, 2, 3, 4, 5, 6]

We can transpose a Matrix:

import numpy as np          
x = np.matrix('[5, 1; 14, 2]')             
y = x.transpose()   
print(y) 

Output on the screen:

 
[[ 5 14]
 [ 1  2]]

We can create small anonymous function:

x = lambda a, b, c : a + b + c

print(x(5, 6, 3))

Output on the screen:

 
14

↑Back

1day-of-python-learning-tutorial's People

Contributors

manjunath5496 avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.