0% found this document useful (0 votes)
4 views

python_assaignment[1]

This document is an assignment on Python fundamentals for the course CSE-251, submitted by Md.Rakibul Islam. It covers various topics including print methods, data types, conditionals, loops, data structures, functions, modules, and file handling in Python. The document includes code examples and their outputs to illustrate the concepts discussed.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

python_assaignment[1]

This document is an assignment on Python fundamentals for the course CSE-251, submitted by Md.Rakibul Islam. It covers various topics including print methods, data types, conditionals, loops, data structures, functions, modules, and file handling in Python. The document includes code examples and their outputs to illustrate the concepts discussed.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Introduction to Probability and Statistics

Assignment: 01

Topic: Python Fundamentals

Course Code: CSE-251

Date of Submission: 28.11.2024

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

Printing Multiple Items:

Code:
print("Hello", "World", 123)

Output:
Hello World 123

Using sep Parameter:

Code:
print("python", "is", "fun", sep="-")

Output:
python-is-fun

Using end Parameter:

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

Formatted String (f-strings):

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.

Printing Unicode Characters:

Code:
print("Unicode example: 😊, ©, 𝜋")

Output:
print("Unicode example: 😊, ©, 𝜋")

Printing with Escape Characters:

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}

Printing with Custom Formatting (repr):

Code:
value = 3.14159
print(f"The value is {repr(value)}")

Output:
The value is 3.14159

Variables, data types:

# Integer (int):

Code:
age=25
print("Age:",age,"Type:",type(age))

Output:
Age: 25 Type: <class 'int'>

Floating-point number (float):

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'>

Condition and Loops:

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

Using logical operators And :

code:
a=7
b = 15
if a > 5 and b > 10:
print("Both conditions are True")

output:
Both conditions are True

Using logical operators OR:

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

Looping using range:

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']

for index, fruit in enumerate(fruits):


print(f" Index{index}:{fruit}")

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

Looping Reverse order:

Code:
fruits=['apple','banana','cherry','date']
for fruit in reversed(fruits):
print(fruit)

output:
date
cherry
banana
apple

using zip to iterate two lists:

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

Use While loop:


Code:
Fruits=[‘apple’,’banana’,’cherry’]
index = 0
while index < len(fruits):
print(fruits[index])
index += 1

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

Python Data Structur:

Tuple declare and print:

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'])

Accessing tuple element:

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)

'''Accessing dictionary element'''

print(employee['Favourite Language'])

'''add an item'''

employee["Age"] = 38

print(employee)

'''Delete an item'''
del employee["Age"]

print(employee)

'''Access the dictionary item'''

employee.items()

""" Access the dictionary keys """

employee.keys()

""" Access the dictionary values """

employee.values()

""" Looping dictionary items """

for key, value in employee.items():


print(key, value)

Output:
{'Name': 'joe', 'Country': 'USA', 'Profession': 'SoftwareEngineer', 'Salary': 12000, 'Favourite
Language': ['c/c++', 'java', 'Python']}

['c/c++', 'java', 'Python']

{'Name': 'joe', 'Country': 'USA', 'Profession': 'SoftwareEngineer', 'Salary': 12000, 'Favourite


Language': ['c/c++', 'java', 'Python'], 'Age': 38}

{'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

Find last element:


Code:
favourite_language=['c/c++','java','python']

print(favourite_language[len(favourite_language)-1])

output:
python

output:

python

slicing list:

Code:
favourite_language=['c/c++','java','python']
print(favourite_language[:])

output:

['c/c++', 'java', 'python']

add element to list:

Code:

favourite_language=['c/c++','java','python']
favourite_language.append('javaScript')

output:

['c/c++', 'java', 'python 3', 'javaScript']

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

clear Entire list:

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]

Count frequency of an item:


Code:
number=[4,2,8,5,2]
print(number.count(2))

output:
2

Index of item:

code:
number=[4,2,8,5,2]
print(number.index(8))

output:
2

sort list ,ReverseList, and Copy List:

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]

2D List, Looping in 2D list, Access a 2D list, and matrix slicing:

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:

double= lambda x: x*2


print(f"Doube of 5 is :{double(5)}")

output:
Double of 5 is: 10

File Handling: Write to a File:

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")

print(f"Data has been written to {file_path}.")

Output:
Data has been written to sample.txt.

File Handling: Reading from a File:


Code:
file_path = "sample.txt"
try:
with open(file_path, "r") as file:
content = file.read()
print("File Content:\n")
print(content)
except FileNotFoundError:
print(f"File {file_path} not found.")

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.

You might also like