python_assaignment[1]
python_assaignment[1]
Assignment: 01
Submitted by:
Md.Rakibul Islam
Roll: 2134
Session: 2021-22
Submitted to:
Md.Masum Bhuiyan
Lecturer
Department of Computer Science & Engineering
Jahangirnagar University
Jahangirnagar University
Savar, Dhaka-1342
Various use of print methods:
Basic Print:
Code:
print("Hellow, World")
output:
Hellow, World
Code:
print("Hello", "World", 123)
Output:
Hello World 123
Code:
print("python", "is", "fun", sep="-")
Output:
python-is-fun
Code:
print("Hello", end=" ")
print("World!")
Output:
Hello World!
Printing Variables:
Code:
name="alice"
age=25
print("Name:", name,"Age:",age)
Output:
Name: alice Age: 25
Code:
name="Dipu"
age=22
print(f"MY name is {name} and i am {age} years old.")
Output:
MY name is Dipu and i am 22 years old.
Using str.format():
Code:
name="Dipu"
age=22
print("MY name is {} and i am {} years old.".format(name,age))
Output:
MY name is Dipu and i am 22 years old.
Code:
print("Unicode example: 😊, ©, 𝜋")
Output:
print("Unicode example: 😊, ©, 𝜋")
Code:
print("Hello\nWorld")
print("Tab\tSpace")
print("Backslash: \\")
Output:
Hello
World
Tab Space
Backslash: \
Raw Strings:
Code:
print(r"Path: C:\Users\Name")
Output:
Path: C:\Users\Name
Printing Objects:
Code:
data = {"name": "Alice", "age": 25}
print(data)
Output:
{'name': 'Alice', 'age': 25}
Code:
value = 3.14159
print(f"The value is {repr(value)}")
Output:
The value is 3.14159
# Integer (int):
Code:
age=25
print("Age:",age,"Type:",type(age))
Output:
Age: 25 Type: <class 'int'>
Code:
height = 5.9 print("Height:", height, "Type:", type(height))
output:
Height: 5.9 Type: <class 'float'>
String (str):
code:
name = "Alice"
print("Name:", name, "Type:", type(name))
output:
Name: Alice Type: <class 'str'>
Boolean (bool):
Code:
is_student = True
print("Is Student:", is_student, "Type:", type(is_student))
output:
Is Student: True Type: <class 'bool'>
List:
codet:
fruits = ["apple", "banana", "cherry"]
print("Fruits:", fruits, "Type:", type(fruits))
output:
Fruits: ['apple', 'banana', 'cherry'] Type: <class 'list'>
Tuple:
code:
coordinates = (10.5, 25.3)
print("Coordinates:", coordinates, "Type:", type(coordinates))
output:
Coordinates: (10.5, 25.3) Type: <class 'tuple'>
Dictionary:
code:
person = {"name": "Alice", "age": 25}
print("Person:", person, "Type:", type(person))
output:
Person: {'name': 'Alice', 'age': 25} Type: <class 'dict'>
Set:
code:
unique_numbers = {1, 2, 3, 3, 4}
print("Unique Numbers:", unique_numbers, "Type:", type(unique_numbers))
output:
Unique Numbers: {1, 2, 3, 4} Type: <class 'set'>
If condition:
Code:
x = 10
if x > 5:
print("x is greater than 5")
output:
x is greater than 5
if-else statement:
code:
y=3
if y % 2 == 0:
print("y is even")
else:
print("y is odd")
output:
y is odd
if-elif-else statement:
code:
z = -1
if z > 0:
print("z is positive")
elif z < 0:
print("z is negative")
else:
print("z is zero")
output:
z is negative
code:
a=7
b = 15
if a > 5 and b > 10:
print("Both conditions are True")
output:
Both conditions are True
output:
if a < 5 or b > 10:
print("At least one condition is True")
output:
a is not greater than 10
For Loop:
code:
fruits=['apple','banana','cherry','date']
for fruit in fruits:
print(fruit)
output:
apple
banana
cherry
date
code:
fruits=['apple','banana','cherry','date']
no_of_fruit=len(fruits)
for i in range(no_of_fruit):
print(f"Index{i}:{fruits[i]}")
output:
Index0:apple
Index1:banana
Index2:cherry
Index3:date
Using enumerate:
code:
fruits=['apple','banana','cherry','date']
output:
Index0:apple
Index1:banana
Index2:cherry
Index3:date
Accessing 2D list:
code:
nested_list=[['red','blue'],['circle','square'],['cat','dog']]
for sublist in nested_list:
for item in sublist:
print(item,end=' ')
print()
output:
red
blue
circle
square
cat
dog
Code:
fruits=['apple','banana','cherry','date']
for fruit in reversed(fruits):
print(fruit)
output:
date
cherry
banana
apple
Code:
fruits=['apple','banana','cherry','date']
colors=['red','yellow','pink','brown']
for fruit,color in zip(fruits,colors):
print(f"the color of {fruit} is {color}")
output:
the color of apple is red
the color of banana is yellow
the color of cherry is pink
the color of date is brown
Output:
apple
banana
cherry
continue:
Code:
for i in range(10):
if i == 7:
continue
print("The Number is :" , i)
Output:
The Number is : 0
The Number is : 1
The Number is : 2
The Number is : 3
The Number is : 4
The Number is : 5
The Number is : 6
The Number is : 8
The Number is : 9
Code:
my_tuple = (
"joe",
"USA",
"Software Engineer",
12000,
["c/c++","Java","Python"]
)
print(my_tuple)
output:
('joe', 'USA', 'Software Engineer', 12000, ['c/c++', 'Java', 'Python'])
Code:
my_tuple = (
"joe",
"USA",
"Software Engineer",
12000,
["c/c++","Java","Python"]
)
print(my_tuple[0])
output:
'Joe'
Slicing tuple:
code:
my_tuple = (
"joe",
"USA",
"Software Engineer",
12000,
["c/c++","Java","Python"]
)
print(my_tuple[1:3])
output:
‘USA’
‘Software Enigineer’
tuple unpacking :
Code:
my_tuple = (
"joe",
"USA",
"Software Engineer",
12000,
["c/c++","Java","Python"]
)
name,country,profession,salary,favourite_language=my_tuple
print(name)
print(profession)
print(salary)
output:
joe
Software Engineer
12000
Dictionary:
Code:
employee ={
"Name":"joe",
"Country":"USA",
"Profession":"SoftwareEngineer",
"Salary":12000,
"Favourite Language":["c/c++","java","Python"]
}
print(employee)
print(employee['Favourite Language'])
'''add an item'''
employee["Age"] = 38
print(employee)
'''Delete an item'''
del employee["Age"]
print(employee)
employee.items()
employee.keys()
employee.values()
Output:
{'Name': 'joe', 'Country': 'USA', 'Profession': 'SoftwareEngineer', 'Salary': 12000, 'Favourite
Language': ['c/c++', 'java', 'Python']}
Name joe
Country USA
Profession SoftwareEngineer
Salary 12000
Favourite Language ['c/c++', 'java', 'Python']
List:
code:
favourite_language=['c/c++','java','python']
print(favourite_language)
output:
['c/c++', 'java', 'python']
Code full:
'''accessing element'''
print(favourite_language[1])
Output:
java
[1, 2, 3]
6
[[4, 5, 6], [7, 8, 9]]
[4, 5, 6]
6
[[4, 5, 6], [7, 8, 9]]
[7, 8, 9]
6
[[4, 5, 6], [7, 8, 9]]
lenght of list:
Code:
favourite_language=['c/c++','java','python']
print(len(favourite_language))
output:
3
print(favourite_language[len(favourite_language)-1])
output:
python
output:
python
slicing list:
Code:
favourite_language=['c/c++','java','python']
print(favourite_language[:])
output:
Code:
favourite_language=['c/c++','java','python']
favourite_language.append('javaScript')
output:
update element:
code:
favourite_language=['c/c++','java','python']
favourite_language[2]='python 3'
print(favourite_language)
Output:
javaScript
Remove the last Element:
Code:
favourite_language=['c/c++','java','python']
last_element=favourite_language.pop()
print(last_element)
Output:
None
Code:
favourite_language=['c/c++','java','python']
print(favourite_language.clear())
output:
List Method:
number=[4,2,8,5,2]
print(number)
[4, 2, 8, 5, 2]
output:
2
Index of item:
code:
number=[4,2,8,5,2]
print(number.index(8))
output:
2
Code:
number=[4,2,8,5,2]
number.sort()
print(number)
number.reverse()
print(number)
number_copy=number.copy()
print(number_copy)
output:
[2, 2, 4, 5, 8]
[8, 5, 4, 2, 2]
[8, 5, 4, 2, 2]
Code:
matrix=[
[1,2,3],
[4,5,6],
[7,8,9]
]
for row in matrix:
print(row)
Output:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
Code:
matrix=[
[1,2,3],
[4,5,6],
[7,8,9]
]print(matrix[1][2])
print(matrix[1:3])
Functions, Exceptions:
Code:
def square(x):
return x*x
def cube(x):
return x*x*x
print(square(5))
def multiply(x,y):
return x*y
print(multiply(2,3))
Output:
25
6
Modules:
Code:
import math
num=25
print(f"Square root of {num}:{math.sqrt(num)}")
print(f"Factorial of 5:{math.factorial(5)}")
Output:
Square root of 25:5.0
Factorial of 5:120
Lambda Functions :
Code:
output:
Double of 5 is: 10
Code:
file_path = "sample.txt"
with open(file_path, "w") as file:
file.write("This is a sample text written to the file.\n")
file.write("Python File Handling is easy!\n")
Output:
Data has been written to sample.txt.
Output:
This is a sample text written to the file.
Python File Handling is easy!
Exception Handling:
code:
def divide_number(a,b):
try:
result=a/b
except ZeroDivisionError:
return "Error:Divission by Zero is not allower."
except TypeError:
return "Error:Invalid input type."
return result
print(divide_number(3,5))
print(divide_number(3,0))
print(divide_number('a',5))
Output:
0.6
Error:Divission by Zero is not allower.
Error:Invalid input type.