- Introduction
- Python Indentation
- Python Comments
- Python Variables
- Python Data Types
- Python Numbers
- Python Casting
- Python Strings
- Python Booleans
- Python Operators
- Python Modules
- Python Lists
- Python Tuples
- Python Sets
- Python Dictionaries
- Python Lambda
- Python Arrays
- Python Classes
- Python Iterators
- Python Math
- Python JSON
- Python RegEx
- Python Try Exception
- Python String Formatting
- Python If ... Else
- Python Loops
- Python User Input
- File Handling
- Python PIP
- Python Remove List Duplicates
- Python Reverse a String
- Python Pandas Read CSV
- Python Datetime
- Python Pandas Series
- Python Pandas Read JSON
- Python Pandas Analyzing Data
- Python SciPy Constants
- Python SciPy Sparse Data
- Python Matplotlib Plotting
- Python Matplotlib Bars
- Python Matplotlib Pie Charts
- Python Statistics
- Python Requests
- Python NumPy
- Python Papers
- Python Books
- Python MySQL
- Python Global Keyword
- Python Raise an Exception
- Python Try Finally
- Python cmath
- Python Exercises with Solutions [183 Exercises]
- 9 Interesting Python Facts
Python is an interpreted, high-level and general-purpose programming language. It was created by
Guido van Rossum, and released in 1991. Python got its name from a BBC comedy series from seventies - "Monty Python's Flying Circus".
- 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.
- 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.
- 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 |
if 4 > 3:
print("Four is greater than three!")
Four is greater than three!
if 4 > 3:
print("Four is greater than three!")
print("Four is greater than three!") ^ IndentationError: expected an indented block
↑Back
#This is a comment
print("Hello, World!")
Hello, World!
↑Back
a = 5
b = "Python"
print(a)
print(b)
5 Python
a, b, c = "Tree", "Chair", "bench"
print(a)
print(b)
print(c)
Tree Chair bench
a = b = c = "Chair"
print(a)
print(b)
print(c)
Chair Chair Chair
a = "easy to understand"
print("Python is " + a)
Python is easy to understand
a = 4
b = 3
print(a + b)
7
a = 6
b = "Python"
print(a + b)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
a = "Hello"
b = "World"
c = a + b
print(c)
HelloWorld
a = "Hello"
b = "World"
c = a + " " + b
print(c)
Hello World
a = "easy to understand"
def myfunc():
print("Python is " + a)
myfunc()
Python is easy to understand
↑Back
# Print the data type of the variable a:
a = 5
print(type(a))
<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
# Display a random number between 1 and 9:
import random
print(random.randrange(1, 10))
7
↑Back
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)
1 2 3
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)
1.0 2.8 3.0
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)
s1 2 3.0
a = "Hello"
b = """Python """
c = '''Python'''
print(a)
print(b)
print(c)
Hello Python Python
# Replace a string with another string
a = "Ear"
print(a.replace("E", "F"))
Far
# Remove whitespace from the beginning or at the end of a string
a = " Hear, Far! "
print(a.strip())
Hear, Far!
# Split a string into substrings
x = "Hear, Far!"
y = x.split(",")
print(y)
['Hear', ' Far!']
# Get the character at position 0
a = "Hello, World!"
print(a[0])
H
for a in "Chair":
print(a)
C h a i r
# get the length of a string
a = "Hello"
print(len(a))
5
# Check if "was" is present in the following text:
txt = "Albert Einstein was a German-born theoretical physicist."
print("was" in txt)
True
# Print only if "Einstein" is present:
txt = "Albert Einstein was a German-born theoretical physicist."
if "Einstein" in txt:
print("Yes, 'Einstein' is present.")
Yes, 'Einstein' is present.
# Check if "newton" is NOT present in the following text:
txt = "Albert Einstein was a German-born theoretical physicist."
print("newton" not in txt)
True
# 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.")
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 |
b = "NEWTON"
print(b[4])
O
b = "NEWTON"
print(b[-3])
T
b = "NEWTON"
print(b[2:5])
WTO
b = "NEWTON"
print(b[:5])
print(b[2:])
NEWTO WTON
# count the number of times the character 'N' appears:
b = "NEWTON"
print(b.count("N"))
2
b = "Albert Einstein was a German-born theoretical physicist who developed the theory of relativity."
print(b.count("of"))
1
a = "ALBERT EINSTEIN"
print(a.lower())
b = "albert einstein"
print(b.upper())
albert einstein ALBERT EINSTEIN
↑Back
print(10 > 9)
print(10 == 9)
print(10 < 9)
True False False
↑Back
- 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 |
a = 2
b = 4
print(a ** b) #same as 2*2*2*2
16
x = 4
y = 2
print(x % y)
0
#the floor division // rounds the result down to the nearest whole number
a = 17
b = 2
print(a // b)
8
a = 4
print(a > 3 and a < 9)
# returns True because 4 is greater than 3 AND 4 is less than 9
True
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)
True
a = ["Chair", "bench"]
print("Car" not in a)
# returns True because a sequence with the value "Car" is not in the list
True
a = 6
a += 2 # same as a = a + 2
print(a)
8
↑Back
# 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)
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.
# importing the module
import wikipedia
# getting suggestions
result = wikipedia.search("Python", results = 4)
# printing the result
print(result)
['Python (programming language)', 'Python', 'Monty Python', 'Burmese python']
thislist = ["Car", "bench", "Chair"]
print(thislist)
['Car', 'bench', 'Chair']
thislist = ["Car", "bench", "Chair"]
print(thislist[1])
bench
# Print the number of items in the list:
thislist = ["Car", "bench", "Chair"]
print(len(thislist))
3
thislist = ["Car", "bench", "Chair"]
print(thislist[-1])
Chair
thislist = ["Chair", "bench", "Car"]
for a in thislist:
print(a)
Chair bench Car
# print the data type of a list
a = ["Chair", "bench", "Car"]
print(type(a))
<class 'list'>
thislist = ["Chair", "bench", "Car"]
if "Chair" in thislist:
print("Yes, 'Chair' is in the list")
Yes, 'Chair' is in the list
thislist = ["Car", "bench", "Chair"]
thislist[1] = "book"
print(thislist)
['Car', 'book', 'Chair']
# add an item to the end of the list
thislist = ["Chair", "bench", "Car"]
thislist.append("book")
print(thislist)
['Chair', 'bench', 'Car', 'book']
thislist = ["book", "Car", "bench"]
thislist.remove("Car")
print(thislist)
['book', 'bench']
thislist = ["book", "Car", "bench"]
thislist.clear()
print(thislist)
[]
a = ["a", "b", "c"]
b = [1, 2, 3]
c = a + b
print(c)
['a', 'b', 'c', 1, 2, 3]
# Append list2 into list1
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
for x in list2:
list1.append(x)
print(list1)
['a', 'b', 'c', 1, 2, 3]
# copy of a list with the copy() method
thislist = ["car", "bench", "chalk"]
mylist = thislist.copy()
print(mylist)
['car', 'bench', 'chalk']
# copy of a list with the list() method
thislist = ["car", "bench", "chalk"]
mylist = list(thislist)
print(mylist)
['car', 'bench', 'chalk']
# add list2 at the end of list1 using extend() method
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
list1.extend(list2)
print(list1)
['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 |
thistuple = ("chair", "bench", "car")
print(thistuple)
('chair', 'bench', 'car')
thistuple = ("chair", "bench", "car")
print(thistuple[1])
bench
thistuple = ("chair", "bench", "car")
print(thistuple[-1])
car
thistuple = ("chair", "bench", "car")
for x in thistuple:
print(x)
chair bench car
thistuple = ("chair", "bench", "car")
if "car" in thistuple:
print("Yes, 'car' is in the tuple")
Yes, 'car' is in the tuple
# Print the number of items in the tuple:
thistuple = ("chair", "bench", "car")
print(len(thistuple))
3
tuple1 = ("a", "b", "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)
('a', 'b', 'c', 1, 2, 3)
x = ("chair", "bench", "car")
y = list(x)
y[1] = "book"
x = tuple(y)
print(x)
('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 |
thisset = {"chair", "bench", "car"}
print(thisset)
{'bench', 'car', 'chair'}
thisset = {"chair", "bench", "car"}
print("book" in thisset)
False
thisset = {"chair", "bench", "car"}
thisset.add("book")
print(thisset)
{'bench', 'book', 'car', 'chair'}
thisset = {"chair", "bench", "car"}
thisset.update(["chalk", "pencil", "table"])
print(thisset)
{'table', 'chalk', 'bench', 'pencil', 'car', 'chair'}
# Get the number of items in a set:
thisset = {"chair", "bench", "car"}
print(len(thisset))
3
# print the data type of a set
thisset = {"chair", "bench", "car"}
print(type(thisset))
<class 'set'>
thisset = {"chair", "bench", "car"}
thisset.remove("bench")
print(thisset)
{'car', 'chair'}
thisset = {"chair", "bench", "car"}
thisset.discard("bench")
print(thisset)
{'car', 'chair'}
thisset = {"chair", "bench", "car"}
thisset.clear()
print(thisset)
set()
# 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)
{1, 2, 3, 'a', 'b', 'c'}
# The update() method inserts the items in set2 into set1:
set1 = {"a", "b", "c"}
set2 = {1, 2, 3}
set1.update(set2)
print(set1)
{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
thisdict={
"Name": "Albert Einstein",
"Theory": "Theory of relativity",
"year": 1905
}
print(thisdict)
{'Name': 'Albert Einstein', 'Theory': 'Theory of relativity', 'year': 1905}
thisdict={
"Name": "Albert Einstein",
"Theory": "Theory of relativity",
"year": 1905
}
x = thisdict["Name"]
print(x)
Albert Einstein
thisdict={
"Name": "Albert Einstein",
"Theory": "Theory of relativity",
"year": 1905
}
thisdict["year"] = 2020
print(thisdict)
{'Name': 'Albert Einstein', 'Theory': 'Theory of relativity', 'year': 2020}
thisdict={
"Name": "Albert Einstein",
"Theory": "Theory of relativity",
"year": 1905
}
for x in thisdict:
print(x)
Name Theory year
thisdict={
"Name": "Albert Einstein",
"Theory": "Theory of relativity",
"year": 1905
}
for x in thisdict:
print(thisdict[x])
Albert Einstein Theory of relativity 1905
thisdict={
"Name": "Albert Einstein",
"Theory": "Theory of relativity",
"year": 1905
}
for x in thisdict.values():
print(x)
Albert Einstein Theory of relativity 1905
thisdict={
"Name": "Albert Einstein",
"Theory": "Theory of relativity",
"year": 1905
}
for x, y in thisdict.items():
print(x, y)
Name Albert Einstein Theory Theory of relativity year 1905
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.")
Yes, 'Theory' is one of the keys in the thisdict dictionary.
# Print the number of items in the dictionary:
thisdict={
"Name": "Albert Einstein",
"Theory": "Theory of relativity",
"year": 1905
}
print(len(thisdict))
3
thisdict={
"Name": "Albert Einstein",
"Theory": "Theory of relativity",
"year": 1905
}
thisdict["best known"] = "mass–energy equivalence"
print(thisdict)
{'Name': 'Albert Einstein', 'Theory': 'Theory of relativity', 'year': 1905, 'best known': 'mass–energy equivalence'}
thisdict={
"Name": "Albert Einstein",
"Theory": "Theory of relativity",
"year": 1905
}
del thisdict["year"]
print(thisdict)
{'Name': 'Albert Einstein', 'Theory': 'Theory of relativity'}
thisdict={
"Name": "Albert Einstein",
"Theory": "Theory of relativity",
"year": 1905
}
thisdict.clear()
print(thisdict)
{}
- 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
# Add 10 to argument a, and return the result:
x = lambda a: a + 10
print(x(5))
15
# Multiply argument a with argument b and return the result:
x = lambda a, b: a * b
print(x(5, 6))
30
# Summarize argument a, b, and c and return the result:
x = lambda a, b, c: a + b + c
print(x(5, 6, 2))
13
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))
22
↑Back
# Create an array containing scientists names:
scientists = ["Aristotle", "Francis Bacon", "Niels Bohr"]
print(scientists)
['Aristotle', 'Francis Bacon', 'Niels Bohr']
# Get the value of the first array:
scientists = ["Aristotle", "Francis Bacon", "Niels Bohr"]
x = scientists[0]
print(x)
Aristotle
# Modify the value of the first array:
scientists = ["Aristotle", "Francis Bacon", "Niels Bohr"]
scientists[0] = "Newton"
print(scientists)
['Newton', 'Francis Bacon', 'Niels Bohr']
# Return the number of names in the scientists array:
scientists = ["Aristotle", "Francis Bacon", "Niels Bohr"]
x = len(scientists)
print(x)
3
scientists = ["Aristotle", "Francis Bacon", "Niels Bohr"]
for x in scientists:
print(x)
Aristotle Francis Bacon Niels Bohr
# Add one more name to the scientists array:
scientists = ["Aristotle", "Francis Bacon", "Niels Bohr"]
scientists.append("Newton")
print(scientists)
['Aristotle', 'Francis Bacon', 'Niels Bohr', 'Newton']
scientists = ["Aristotle", "Francis Bacon", "Niels Bohr"]
scientists.remove("Niels Bohr")
print(scientists)
['Aristotle', 'Francis Bacon']
# Delete the second name in the scientists array:
scientists = ["Aristotle", "Francis Bacon", "Niels Bohr"]
scientists.pop(1)
print(scientists)
['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
class MyClass: x = 5
p1 = MyClass()
print(p1.x)
5
# 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)
Albert 56
mytuple = ("bench", "pencil", "chalk")
myit = iter(mytuple)
print(next(myit))
print(next(myit))
print(next(myit))
bench pencil chalk
mystr = "newton"
myit = iter(mystr)
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
n e w t o n
mytuple = ("bench", "board", "book")
for x in mytuple:
print(x)
bench board book
mystr = "newton"
for x in mystr:
print(x)
n e w t o n
a = min(5, 10, 25)
b = max(5, 10, 25)
print(a)
print(b)
5 25
c = abs(-6.35)
print(c)
6.35
x = pow(2, 3)
print(x)
8
# Import math library
import math
x = math.sqrt(4)
print(x)
2
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)
3 2
import math
a = math.pi
print(a)
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 |
# 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))
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...) |
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"])
21
↑Back
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")
YES! We have a match!
↑Back
#The try block will generate an error, because x is not defined:
try:
print(x)
except:
print("An exception occurred")
An exception occurred
#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")
Variable x is not defined
#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")
Variable x is not defined
cost = 56
txt = "The cost is {} Rupees"
print(txt.format(cost))
The cost is 56 Rupees
cost = 56
txt = "The cost is {:.2f} Rupees"
print(txt.format(cost))
The cost is 56.00 Rupees
age = 16
name = "Albert"
txt = "His name is {1}. {1} is {0} years old."
print(txt.format(age, name))
His name is Albert. Albert is 16 years old.
a = 40
b = 60
if b > a:
print("b is greater than a")
b is greater than a
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")
a and b are equal
items = ["pencil", "rubber", "chalk"]
for x in items:
print(x)
pencil rubber chalk
items = ["pencil", "rubber", "chalk"]
for x in items:
print(x)
if x == "rubber":
break
pencil rubber
# 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)
pencil
# Do not print rubber:
items = ["pencil", "rubber", "chalk"]
for x in items:
if x == "rubber":
continue
print(x)
pencil chalk
# 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)
0 1 2 3 4
# range(1, 5), which means values from 1 to 5 (but not including 5):
for x in range(1, 5):
print(x)
1 2 3 4
# Increment the sequence with 2:
for x in range(2, 10, 2):
print(x)
2 4 6 8
# 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!")
0 1 2 3 Finally finished!
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.
0 1 2
adj = ["red", "big", "best"]
items = ["chalk", "board", "pencil"]
for x in adj:
for y in items:
print(x, y).
red chalk red board red pencil big chalk big board big pencil best chalk best board best pencil
# 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
# Print i as long as i is less than 5:
i = 0
while i < 5:
print(i)
i += 1
0 1 2 3 4
# Exit the loop when i is 3:
i = 1
while i < 5:
print(i)
if (i == 3):
break
i += 1
1 2 3
# 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
1 2 4 5 6
# 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")
1 2 3 4 5 i is no longer less than 6
# 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)
Enter username: If you enter the word "ram" Username is: ram will be outputted on the console screen.
↑Back
import os
if os.path.exists("demofile.txt"): os.remove("demofile.txt")
else:
print("The file does not exist")
The file does not exist
↑Back
# 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
# Display package information
pip show numpy
# Remove Duplicates From a Python List
mylist = ["a", "b", "a", "c", "c"]
mylist = list(dict.fromkeys(mylist))
print(mylist)
['a', 'b', 'c']
# Reverse the string "World":
txt = "World"[::-1]
print(txt)
dlroW
# Load the CSV into a DataFrame:
import pandas as pd
b = pd.read_csv('data.csv')
print(b.to_string())
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
# Import the datetime module and display the current date:
import datetime
x = datetime.datetime.now()
print(x)
2021-02-08 02:35:46.405410
# Return the year and name of weekday:
import datetime
x = datetime.datetime.now()
print(x.year)
print(x.strftime("%A"))
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
# Create a simple Pandas Series from a list:
import pandas as pd
x = [2, 8, 6]
var = pd.Series(x)
print(var)
0 2 1 8 2 6 dtype: int64
#Load the JSON file into a DataFrame:
import pandas as pd
x = pd.read_json('data.json')
print(x.to_string())
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
# print the first 5 rows of the DataFrame:
import pandas as pd
x = pd.read_csv('data.csv')
print(x.head(5))
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
# Print the constant value of PI:
from scipy import constants
print(constants.pi)
3.141592653589793
# 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))
(0, 5) 1 (0, 6) 1 (0, 8) 2
# 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()
# 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()
# 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()
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()
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()
# 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]))
37.5 43.7956204379562
# 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]))
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 |
# 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)
<!DOCTYPE html>
<html>
<body>
<h1>This is a Test Page</h1>
</body>
</html>
import numpy
arr = numpy.array([1, 2, 3, 4, 5])
print(arr)
[1 2 3 4 5]
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
[1 2 3 4 5]
# 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)
[4 5 6 7 8 9]
# 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)
[array([1, 2]), array([3, 4]), array([5, 6])]
# 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)
0.9035079029052513
# 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)
39.0
- A Peephole Optimizer for Python
- Compiling Little Languages in Python
- Securing Your Collaborative Jupyter Notebooks in the Cloud using Container and Load Balancing Services
- Quasi-orthonormal Encoding for Machine Learning Applications
- MatLab vs. Python vs. R
- modernizing PHCpack through phcpy
- Bloscpack: a compressed lightweight serialization format for numerical data
- CATOS: Computer Aided Training/Observing System
- High-Content Digital Microscopy with Python
- PySTEMM: Executable Concept Modeling for K-12 STEM Learning
- Performance of Python runtimes on a non-numeric scientific code
- Computing an Optimal Control Policy for an Energy Storage
- JyNI – Using native CPython-Extensions in Jython
- SfePy - Write Your Own FE Application
- Mining online social networks with Python to study urban mobility
- PyFAI: a Python library for high performance azimuthal integration on GPU
- Wyrm, A Pythonic Toolbox for Brain-Computer Interfacing
- SPySort: Neuronal Spike Sorting with Python
- Using Python to Dive into Signalling Data with CellNOpt and BioServices
- Py3DFreeHandUS: a library for voxel-array reconstruction using Ultrasonography and attitude sensors
- SClib, a hack for straightforward embedded C functions in Python
- Predictive Modelling of Toxicity Resulting from Radiotherapy Treatments of Head and Neck Cancer
- pyFRET: A Python Library for Single Molecule Fluorescence Data Analysis
- Enhancing SfePy with Isogeometric Analysis
- A Python-based Post-processing Toolset For Seismic Analyses
- Numerical simulation of liver perfusion: from CT scans to FE model
- Temperature diagnostics of the solar atmosphere using SunPy
- Python vs. R: A Text Mining Approach for analyzing the Research Trends in Scopus Database
- Partial Pole Placement via Delay Action: A Python Software for Delayed Feedback Stabilizing Design
- Meta-analysis parameters computation: a Python approach to facilitate the crossing of experimental conditions
- ExoTiC-ISM: A Python package for marginalised exoplanet transit parameters across a grid of systematic instrument models
- MKLpy: a python-based framework for Multiple Kernel Learning
- ARC 3.0: An expanded Python toolbox for atomic physics calculations
- PyR@TE 3
- PyXtal FF: a Python Library for Automated Force Field Generation
- multivar horner: a python package for computing Horner factorisations of multivariate polynomials
- DyPy: A Python Library for Simulating Matrix-Form Games
- Automated Unit Test Generation for Python
- PyKEEN 1.0: A Python Library for Training and Evaluating Knowledge Graph Embeddings
- Biomedical and Clinical English Model Packages in the Stanza Python NLP Library
- Towards a Sustainable Microgrid on Alderney Island Using a Python-based Energy Planning Tool
- FitsGeo: Python package for PHITS geometry development
- PyMGRIT: A Python Package for the parallel-in-time method MGRIT
- SEDBYS: A python-based SED Builder for Young Stars
- Introducing students to research codes: A short course on solving partial differential equations in Python
- TAPsolver: A Python package for the simulation and analysis of TAP reactor experiments
- SPInS, a pipeline for massive stellar parameter inference: A public Python tool to age-date, weigh, size up stars, and more
- reval: a Python package to determine the best number of clusters with stability-based relative clustering validation
- A Python Library for Exploratory Data Analysis and Knowledge Discovery on Twitter Data
- TB2J: a python package for computing magnetic interaction parameters
- SimpleSBML: A Python package for creating, editing, and interrogating SBML models: Verison 2.0
- PySAD: A Streaming Anomaly Detection Framework in Python
- TorchKGE: Knowledge Graph embedding in Python and PyTorch
- Development of a computational software in Python, used to study the materials resistance in beams
- Atomic Data Assessment with PyNeb
- MicroAnalyzer: A Python Tool for Automated Bacterial Analysis with Fluorescence Microscopy
- munuSSM: A python package for the μ-from-ν Supersymmetric Standard Model
- BOML: A Modularized Bilevel Optimization Library in Python for Meta Learning
- Extendible and Efficient Python Framework for Solving Evolution Equations with Stabilized Discontinuous Galerkin Methods
- PyROQ: a Python-based Reduced Order Quadrature Building Code for Fast Gravitational Wave Inference
- EZFF: Python Library for Multi-Objective Parameterization and Uncertainty Quantification of Interatomic Forcefields for Molecular Dynamics
- Scipp: Scientific data handling with labeled multi-dimensional arrays for C++ and Python
- Fast fully-reproducible streamlined serial/parallel Monte Carlo/MCMC simulations and visualizations via ParaMonte::Python library
- DIETERpy: a Python framework for The Dispatch and Investment Evaluation Tool with Endogenous Renewables
- Pyg4ometry: a Python library for the creation of Monte Carlo radiation transport physical geometries
- TextAttack: Lessons learned in designing Python frameworks for NLP
- The Dusty Evolved Star Kit (DESK): A Python package for fitting the Spectral Energy Distribution of Evolved Stars
- PYMT5: multi-mode translation of natural language and PYTHON code with transformers
- Network Security using Python
- On the performance of the Python programming language for serial and parallel scientific computations
- A Primer on Python for Life Science Researchers
- Introducing Python Programming for Engineering Scholars
- A facility for creating Python extensions in C++
- A Python Based Production System for High Volume Electronic Publishing
- Parallel High Performance Bootstrapping in Python
- A Computational Framework for Plasmonic Nanobiosensing
- Cloudknot: A Python Library to Run your Existing Code on AWS Batch
- Expert RF Feature Extraction to Win the Army RCO AI Signal Classification Challenge
- Deep and Ensemble Learning to Win the Army RCO AI Signal Classification Challenge
- Keeping the Chandra Satellite Cool with Python
- Fitting Human Decision Making Models using Python
- Astrodata
- Will Millennials Ever Get Married?
- Accelerating the Advancement of Data Science Education
- A Technical Anatomy of SPM.Python, a Scalable, Parallel Version of Python
- Dynamic Social Network Modeling of Diffuse Subcellular Morphologies
- Functional Uncertainty Constrained by Law and Experiment
- pgmpy: Probabilistic Graphical Models using Python
- Total Recall: flmake and the Quest for Reproducibility
- Equity, Scalability, and Sustainability of Data Science Infrastructure
- Fluctuation X-ray Scattering real-time app
- Composable Multi-Threading and Multi-Processing for Numeric Libraries
- Divisi: Learning from Semantic Networks and Sparse SVD
- DMTCP: Bringing Checkpoint-Restart to Python
- Converting Python Virtual Machine Code to C
- Scientific Computing with SciPy for Undergraduate Physics Majors
- Multidimensional Data Exploration with Glue
- Generalized earthquake classification
- Theano: A CPU and GPU Math Compiler in Python
- Hyperopt: A Python Library for Optimizing the Hyperparameters of Machine Learning Algorithms
- SkData: Data Sets and Algorithm Evaluation Protocols in Python
- Analyzing Particle Systems for Machine Learning and Data Visualization with freud
- Using Python to Study Rotational Velocity Distributions of Hot Stars
- HOOMD-blue version 3.0 A Modern, Extensible, Flexible, Object-Oriented API for Molecular Simulations
- Fitting and Estimating Parameter Confidence Limits with Sherpa
- SPORCO: A Python package for standard and convolutional sparse representations
- cesium: Open-Source Platform for Time-Series Inference
- Python as a First Programming Language for Biomedical Scientists
- librosa: Audio and Music Signal Analysis in Python
- UConnRCMPy: Python-based data analysis for Rapid Compression Machines
- Crab: A Recommendation Engine Framework for Python
- The Econ-ARK and HARK: Open Source Tools for Computational Economics
- CAF Implementation on FPGA Using Python Tools
- PyEDA: Data Structures and Algorithms for Electronic Design Automation
- Developing a Graph Convolution-Based Analysis Pipeline for Multi-Modal Neuroimage Data: An Application to Parkinson’s Disease
- Storing Reproducible Results from Computational Experiments using Scientific Python Packages
- Python Tools for Reproducible Research on Hyperbolic Problems
- BCE: Berkeley's Common Scientific Compute Environment for Research and Education
- A High Performance Robot Vision Algorithm Implemented in Python
- Measuring rainshafts: Bringing Python to bear on remote sensing data
- Compyle: a Python package for parallel computing
- Scientific Data Analysis and Visualization with Python, VTK, and ParaView
- gpustats: GPU Library for Statistical Computing in Python
- Python's Role in VisIt
- Using the Global Arrays Toolkit to Reimplement NumPy for Distributed Computation
- Netlist Analysis and Transformations Using SpyDrNet
- datreant: persistent, Pythonic trees for heterogeneous data
- Creating a Real-Time Recommendation Engine using Modified K-Means Clustering and Remote Sensing Signature Matching Algorithms
- Comparison of machine learning methods applied to birdsong element classification
- Practical Applications of Astropy
- Vision Spreadsheet: An Environment for Computer Vision
- Unusual Relationships: Python and Weaver Birds
- Constructing scientific programs using SymPy
- EarthSim: Flexible Environmental Simulation Workflows Entirely Within Jupyter Notebooks
- Safe handling instructions for missing data
- Java vs. Python Coverage of Introductory Programming Concepts: A Textbook Analysis
- Text and data mining scientific articles with allofplos
- pyjanitor: A Cleaner API for Cleaning Data
- Evolutionary Prototyping: "Add Later" Static Types for Python
- Automating Quantitative Confocal Microscopy Analysis
- Weather Forecast Accuracy Analysis
- Detection and characterization of interactions of genetic risk factors in disease
- Exploring Network Structure, Dynamics, and Function using NetworkX
- Interval Arithmetic: Python Implementation and Applications
- Experiences Using SciPy for Computer Vision Research
- The SciPy Documentation Project (Technical Overview)
- Matplotlib Solves the Riddle of the Sphinx
- The SciPy Documentation Project
- Pysynphot: A Python Re-Implementation of a Legacy App in Astronomy
- How the Large Synoptic Survey Telescope (LSST) is using Python
- Realtime Astronomical Time-series Classification and Broadcast Pipeline
- Analysis and Visualization of Multi-Scale Astrophysical Simulations Using Python and NumPy
- Mayavi: Making 3D Data Visualization Reusable
- Finite Element Modeling of Contact and Impact Problems Using Python
- Circuitscape: A Tool for Landscape Ecology
- Summarizing Complexity in High Dimensional Spaces
- Converting Python Functions to Dynamically Compiled C
- unPython: Converting Python Numerical Programs into C
- Cython tutorial
- Fast numerical computations with Cython
- High-Performance Code Generation Using CorePy
- Convert-XY: type-safe interchange of C++ and Python containers for NumPy extensions
- Parallel Kernels: An Architecture for Distributed Parallel Computing
- PaPy: Parallel and distributed data-processing pipelines in Python
- PMI - Parallel Method Invocation
- Sherpa: 1D/2D modeling and fitting in Python
- The FEMhub Project and Classroom Teaching of Numerical Methods
- Exploring the future of bioinformatics data sharing and mining with Pygr and Worldbase
- Nitime: time-series analysis for neuroimaging data
- Multiprocess System for Virtual Instruments in Python
- Neutron-scattering data acquisition and experiment automation with Python
- Progress Report: NumPy and SciPy Documentation in 2009
- The State of SciPy
- Python as a Discrete Event Simulation environment
- Codebraid: Live Code in Pandoc Markdown
- Introduction to Geometric Learning in Python with Geomstats
- Network visualizations with Pyvis and VisJS
- Rebuilding the Hubble Exposure Time Calculator
- Pythran: Enabling Static Optimization of Scientific Python Programs
- Using Python with Smoke and JWST Mirrors
- Sparse: A more modern sparse array library
- Adapted G-mode Clustering Method applied to Asteroid Taxonomy
- Modeling Sudoku Puzzles with Python
- Boost-histogram: High-Performance Histograms as Objects
- Case study: Real-world machine learning application for hardware failure detection
- LabbookDB: A Wet-Work-Tracking Database Application Framework
- The James Webb Space Telescope Data Calibration Pipeline
- Circumventing The Linker: Using SciPy's BLAS and LAPACK Within Cython
- Is Python an Appropriate Programming Language for Teaching Programming in Secondary Schools?
- Python – The Fastest Growing Programming Language
- Self-driving Lego Mindstorms Robot
- Bitmap Indices for Data Warehouses
- PyModel: Model-based testing in Python
- The Reference Model for Disease Progression
- Fcm - A python library for flow cytometry
- Learning from evolving data streams
- Mesa: An Agent-Based Modeling Framework
- PyHRF: A Python Library for the Analysis of fMRI Data Based on Local Estimation of the Hemodynamic Response Function
- Solving Polynomial Systems with phcpy
- HoloViews: Building Complex Visualizations Easily for Reproducible Science
- Ginga: an open-source astronomical image viewer and toolkit
- AI Based Voice Assistant Using Python
- Awkward Array: JSON-like data, NumPy-like idioms
- Bringing ipywidgets Support to plotly.py
- MONTE Python for Deep Space Navigation
- Structural Cohesion: Visualization and Heuristics for Fast Computation with NetworkX and matplotlib
- SciSheets: Providing the Power of Programming With The Simplicity of Spreadsheets
- Automated Image Quality Monitoring with IQMon
- The Climate Modelling Toolkit
- Beyond: A Portable Virtual World Simulation Framework
- Tell Me Something I Don't Know: Analyzing OkCupid Profiles
- PyRK: A Python Package For Nuclear Reactor Kinetics
- Teaching numerical methods with IPython notebooks and inquiry-based learning
- The Sacred Infrastructure for Computational Research
- Project-based introduction to scientific computing for physics majors
- Hyperopt-Sklearn: Automatic Hyperparameter Configuration for Scikit-Learn
- Automation of Inertial Fusion Target Design with Python
- Exploring Collaborative HPC Visualization Workflows using VisIt and Python
- Python Coding of Geospatial Processing in Web-based Mapping Applications
- PyTeCK: a Python-based automatic testing package for chemical kinetic models
- WrightSim: Using PyCUDA to Simulate Multidimensional Spectra
- Python Vuh: Mayan Calendrical Mathematics with Python
- Scaling Polygon Adjacency Algorithms to Big Data Geospatial Analysis
- Optimizing Python-Based Spectroscopic Data Processing on NERSC Supercomputers
- Hurricane Prediction with Python
- High-performance operator evaluations with ease of use: libCEED's Python interface
- FigureFirst: A Layout-first Approach for Scientific Figures
- IMUSim - Simulating inertial and magnetic sensor systems in Python
- VisPy: Harnessing The GPU For Fast, High-Level Visualization
- Python Machine Learning Projects
- Parallel Analysis in MDAnalysis using the Dask Parallel Computing Library
- Mailman – An Extensible Mailing List Manager Using Python
- Using Python to Construct a Scalable Parallel Nonlinear Wave Solver
- MatchPy: A Pattern Matching Library
- Spectral Analysis of Mitochondrial Dynamics: A Graph-Theoretic Approach to Understanding Subcellular Pathology
- White Noise Test: detecting autocorrelation and nonstationarities in long time series after ARIMA modeling
- A Real-Time 3D Audio Simulator for Cognitive Hearing Science
- Matched Filter Mismatch Losses in MPSK and MQAM Using Semi-Analytic BEP Modeling
- Exploring the Extended Kalman Filter for GPS Positioning Using Simulated User and Satellite Track Data
- Real-Time Digital Signal Processing Using pyaudio_helper and the ipywidgets
- pyDEM: Global Digital Elevation Model Analysis
- Widgets and Astropy: Accomplishing Productive Research with Undergraduates
- Dask: Parallel Computation with Blocked algorithms and Task Scheduling
- Organic Molecules in Space: Insights from the NASA Ames Molecular Database in the era of the James Webb Space Telescope
- Having your cake and eating it: Exploiting Python for programmer productivity and performance on micro-core architectures using ePython
- Building a Framework for Predictive Science
- Data Structures for Statistical Computing in Python
- Protein Folding with Python on Supercomputers
- PySPLIT: a Package for the Generation, Analysis, and Visualization of HYSPLIT Air Parcel Trajectories
- TrendVis: an Elegant Interface for dense, sparkline-like, quantitative visualizations of multiple series using matplotlib
- pulse2percept: A Python-based simulation framework for bionic vision
- Optimised finite difference computation from symbolic equations
- Causal Bayesian NetworkX
- Linting science prose and the science of prose linting
- SpacePy - A Python-based Library of Tools for the Space Sciences
- Campaign for IT literacy through FOSS and Spoken Tutorials
- SunPy: Python for Solar Physicists
- Harnessing the Power of Scientific Python to Investigate Biogeochemistry and Metaproteomes of the Central Pacific Ocean
- An intelligent shopping list based on the application of partitioning and machine learning algorithms
- Python meets systems neuroscience: affordable, scalable and open-source electrophysiology in awake, behaving rodents
- Python: a programming language for software integration and development
- PyStream: Compiling Python onto the GPU
- Geodynamic simulations in HPC with Python
- pandera: Statistical Data Validation of Pandas Dataframes
- Accelerating Scientific Python with Intel Optimizations
- MDAnalysis: A Python Package for the Rapid Analysis of Molecular Dynamics Simulations
- Combining Physics-Based and Data-Driven Modeling for Pressure Prediction in Well Construction
- Numerical Pyromaniacs: The Use of Python in Fire Research
- Validating Function Arguments in Python Signal Processing Applications
- Parameter Estimation Using the Python Package pymcmcstat
- Scikit-learn: Machine Learning in Python
- Reproducible Documents with PythonTeX
- Spreading the Adoption of Python in India: the FOSSEE Python Project
- PySPH: a reproducible and high-performance framework for smoothed particle hydrodynamics
- Binder 2.0 - Reproducible, interactive, sharable environments for science at scale
- Python for research and teaching economics
- Pydra - a flexible and lightweight dataflow engine for scientific analyses
- PyFront: Conversion of Python to C Extension Modules
- PyLZJD: An Easy to Use Tool for Machine Learning
- Python for Unified Research in Econometrics and Statistics
- Qiita: report of progress towards an open access microbiome data analysis and visualization platform
- A Programmatic Interface for Particle Plasma Simulation in Python
- Parkinson's Classification and Feature Extraction from Diffusion Tensor Images
- Leading magnetic fusion energy science into the big-and-fast data lane
- PySPH: A Python Framework for Smoothed Particle Hydrodynamics
- Python in Data Science Research and Education
- Audio-Visual Speech Recognition using SciPy
- lpEdit: an editor to facilitate reproducible analysis via literate programming
- PyDDA: A new Pythonic Wind Retrieval Package
- QuTiP: A framework for the dynamics of open quantum systems using SciPy and Cython
- SHADOW: A workflow scheduling algorithm reference and testing framework
- Validated numerics with Python: the ValidiPy package
- Creating a browser-based virtual computer lab for classroom instruction
- Relation: The Missing Container
- Better and faster hyperparameter optimization with Dask
- Statsmodels: Econometric and Statistical Modeling with Python
- Software Engineering as Research Method: Aligning Roles in Econ-ARK
- Visualizing physiological signals in real-time
- Spatio-temporal analysis of socioeconomic neighborhoods: The Open Source Longitudinal Neighborhood Analysis Package (OSLNAP)
- Visualization of Bioinformatics Data with Dash Bio
- Bringing Parallel Performance to Python with Domain-Specific Selective Embedded Just-in-Time Specialization
- PMDA - Parallel Molecular Dynamics Analysis
- cphVB: A System for Automated Runtime Optimization and Parallelization of Vectorized Applications
- N-th-order Accurate, Distributed Interpolation Library
- Implementing the SMS server, or why I switched from Tcl to Python
- Google App Engine Python
- Statistics and Machine Learning in Python
- TracPy: Wrapping the Fortran Lagrangian trajectory model TRACMASS
- OpenMG: A New Multigrid Implementation in Python
- Design and Implementation of pyPRISM: A Polymer Liquid-State Theory Framework
- Improving efficiency and repeatability of lake volume estimates using Python
- Modeling the Earth with Fatiando a Terra
- A Bayesian's journey to a better research workflow
- Frequentism and Bayesianism: A Python-driven Primer
- Scalable Feature Extraction with Aerial and Satellite Imagery
- Virtual Method Tables in Python
- signac: A Python framework for data and workflow management
- Blaze: Building A Foundation for Array-Oriented Computing in Python
- ChiantiPy: a Python package for Astrophysical Spectroscopy
- Yaksh: Facilitating Learning by Doing
- Building a Cloud Service for Reproducible Simulation Management
- Launching Python Applications on Peta-scale Massively Parallel Systems
- Falsify your Software: validating scientific code with property-based testing
- Towards an Unsupervised Spatiotemporal Representation of Cilia Video Using A Modular Generative Pipeline
- Simulating X-ray Observations with Python
- Time Series Analysis in Python with statsmodels
↑Back
- How To Code in Python 3
- Python for Everybody: Exploring Data Using Python 3
- Automate the Boring Stuff with Python: Practical Programming for Total Beginners
- Introduction to Scientific Programming with Python
- Python Machine Learning Projects
- Building Skills in Object-Oriented Design
- Learning Computing with Robots
- Python 3 Patterns, Recipes and Idioms
- Programming for Computations – Python: A Gentle Introduction to Numerical Simulations with Python 3.6
- Annotated Algorithms in Python: with Applications in Physics, Biology, and Finance
- How to Think Like a Computer Scientist: Learning with Python
- The Coder's Apprentice: Learning Programming with Python 3
- Non-Programmer's Tutorial for Python
- Python and Coding Theory
- Hands-On Python: A Tutorial Introduction for Beginners
- Python Notes for Professionals
- Fast Lane to Python: A quick, sensible route to the joys of Python coding
- Programming for Computations – Python: A Gentle Introduction to Numerical Simulations with Python
- Solving PDEs in Python: The FEniCS Tutorial I
- Guide to NumPy
- Scipy Lecture Notes
- Python Scripting for Spatial Data Processing
- Modeling Creativity: Case Studies in Python
- Python for Informatics: Exploring Information
- Algorithmic Problem Solving with Python
- Think Stats: Exploratory Data Analysis in Python
- Think Python: How to Think Like a Computer Scientist
- Open Data Structures (in C++)
- Problem Solving with Algorithms and Data Structures
- Think Bayes: Bayesian Statistics Made Simple
- Programming Computer Vision with Python
- Python for you and me
- Create Your Own Entertainment With Raspberry Pi
- Programming and Mathematical Thinking: A Gentle Introduction to Discrete Math Featuring Python
- A Byte of Python
- Think Complexity
- Modeling and Simulation in Python
- Python In Hydrology
- Basic Data Analysis and More − A Guided Tour Using python
- Building Skills in Object-Oriented Design: Step-by-Step Construction of A Complete Application
↑Back
# 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")
# 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))")
# 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.")
# 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
def myfunc():
global z
z = 5
myfunc()
print(z)
5
a = -2
if a < 0:
raise Exception("Sorry, no numbers below zero")
raise Exception("Sorry, no numbers below zero")Exception: Sorry, no numbers below zero
#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")
Something went wrong The 'try except' is finished
#import cmath for complex number operations
import cmath
#find the arc cosine of a complex number
print (cmath.acos(3+2j))
(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...) |
#Import cmath Library
import cmath
# Print complex infinity
print (cmath.infj)
infj
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)
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.")
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")
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))
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)
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)
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.")
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)
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)
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)
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]])
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)
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)
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")
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)
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()
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()
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)
Write a program to split the characters of the given string into a list.
Solution:
s = "mystring"
l = list(s)
print (l)
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)
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)
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)
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))
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)
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)
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")
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)
Write a program To add an item to the end of the list.
Solution:
list1 = ["pen", "book", "ball"]
list1.append("bat")
print(list1)
Write a program To remove an item from the list.
Solution:
list1 = ["pen", "book", "ball"]
list1.remove("ball")
print(list1)
Write a program To print the number of elements in an array.
Solution:
list1 = ["pen", "book", "ball"]
a = len(list1)
print(a)
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)
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)))
Write a program to select an item randomly from a list.
Solution:
import random
list = ['Paper', 'Pencil', 'Book', 'Bag', 'Pen']
print(random.choice(list))
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)
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())
Write a program to check whether a string starts with specified characters.
Solution:
string = "myw3schools.com"
print(string.startswith("w3s"))
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)
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")
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)
Write a program to convert degree to radian.
Solution:
pi=22/7
degree = int(input("Input degrees: "))
radian = degree*(pi/180)
print(radian)
Write a program to Generate a Random Number.
Solution:
import random
print(random.randint(0,9))
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)
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)
Write a program to Multiply all numbers in the list.
Solution:
import numpy
list = [1, 2, 3]
result = numpy.prod(list)
print(result)
Write a program to print ASCII Value of a character.
Solution:
a = 'j'
print("The ASCII value of '" + a + "' is", ord(a))
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)
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()
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
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)
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")
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")
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))
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)
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)
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")
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)
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)
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])
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)
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])
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)
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()
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()
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()
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 * '*')
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()
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])
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])
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)
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)
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])
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)
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)
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)
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)
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)
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))
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)
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)
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)
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))
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))
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))
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)
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)
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)
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!")
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
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)
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)
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. ")
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()
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!")
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
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))
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)
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!')
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))
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")
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))
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))
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)
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))
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
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)
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)
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))
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))
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)
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)
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)
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)
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)
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))
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.")
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))
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)
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)
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)
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))
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)
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)
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)
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)
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)
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)
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)
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!")
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)
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)
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)
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)
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!")
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()))
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)
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)
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__)
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)
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)))
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)
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)
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)
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)
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)
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!")
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))
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))
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))
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)
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)
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)
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)
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()
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)
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)
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()
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)
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)
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)
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)
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()
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)
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)
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())
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()
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()
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
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))
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')
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))
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
Write a program to implement password generator.
Solution:
import random
s = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()?"
passlen = 8
p = "".join(random.sample(s,passlen ))
print (p)
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))
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)
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)
***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)
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)
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)
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")
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)
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)
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)
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?")
def XYZ():
p = 3
q = 2
return p, q
a, b = XYZ()
print(a, b)
3 2
my_list = ['apple', 'orange', 'grapes']
print(my_list[-2])
orange
my_list = ['I', 'Love', 'Python']
print(''.join(my_list))
ILovePython
a = 3
b = 2
print('Before Swapping')
print(a, b)
a, b = b, a
print('After Swapping')
print(a, b)
Before Swapping 3 2 After Swapping 2 3
import sys
print("My Python version Number: {}".format(sys.version))
My Python version Number: 3.7.3 (default, Mar 27 2019, 17:13:21) [MSC v.1915 64 bit (AMD64)]
x = [1, 2, 3]
a, b, c = x
print(a)
print(b)
print(c)
1 2 3
import itertools
x = [[1, 2], [3, 4], [5, 6]]
print(list(itertools.chain.from_iterable(x)))
[1, 2, 3, 4, 5, 6]
import numpy as np
x = np.matrix('[5, 1; 14, 2]')
y = x.transpose()
print(y)
[[ 5 14] [ 1 2]]
x = lambda a, b, c : a + b + c
print(x(5, 6, 3))
14