[go: up one dir, main page]

0% found this document useful (0 votes)
24 views31 pages

45B AIML Practical0

Uploaded by

Ahmed Shaikh
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)
24 views31 pages

45B AIML Practical0

Uploaded by

Ahmed Shaikh
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/ 31

Name of Student : Ahmed Mobin Ahmed Shaikh

Roll Number : 45 LAB Assignment Number : 0

Title of LAB Assignment : Practical 0

DOP : 17th January 2024 DOS : 22nd January 2024

CO Mapped : PO Signature :
Mapped :

1
Ahmed Shaikh / 45 AIM FYMCA-B
L

Python
Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-
level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive
for Rapid Application Development, as well as for use as a scripting or glue language to connect existing
components together. Python's simple, easy tolearn syntax emphasizes readability and therefore reduces
the cost of program maintenance. Python supports modules and packages, which encourages program
modularity and code reuse. The Python interpreter and the extensive standard library are available in
source or binary form without charge for all major platforms, and can be freely distributed.

Google Colab (short for Colaboratory) is a free, cloud-based platform provided by Google that allows you to
write and execute Python code in a web-based environment. It's particularly popular for its integration with
Jupyter notebooks and provides free access to GPU and TPU (Tensor Processing Unit) resources.

Here's a brief explanation of how to use Google Colab with Python:

Accessing Google Colab:

Go to Google Colab. Sign in with your Google account.

Creating a New Notebook:

Click on "New Notebook" to create a new Python notebook. Notebooks are organizedinto cells, which can
contain code, text, or visualizations.

Writing and Executing Code:

In code cells, you can write and execute Python code. To execute a cell, press Shift + Enter. The output of the
code will be displayed below the cell.

Adding Text and Documentation:

Use text cells (Markdown cells) to add explanations, documentation, and comments to your code. You can
change a cell type to Markdown by selecting the cell and choosing"Markdown" from the dropdown menu
in the toolbar.

Uploading and Downloading Files:

You can upload files to your Colab environment using the file upload button. To
download the notebook or any file, go to File > Download.

2
Ahmed Shaikh / 45 AIM FYMCA-B
L

Using GPU/TPU:

Colab provides free access to GPU and TPU resources, which can be utilized to accelerate computations,
especially useful for machine learning tasks. You can enable GPU/TPU by going to Runtime > Change
runtime type and selecting GPU or TPU.

Saving and Sharing Notebooks:

Colab notebooks are automatically saved to your Google Drive. You can also save acopy to GitHub, or
download it as a Jupyter notebook or other formats. Share your notebook by clicking on the Share button
in the top right.

Installing External Libraries:

You can install external Python libraries using !pip install directly in a code cell.

Using External Data:

You can read data from Google Drive, GitHub, or any other online source directly into your Colab notebook.

Accessing Local Files:

If you need to access files on your local machine, you can upload them to Colab using the file upload feature.

Disconnecting and Reconnecting:

If you're inactive for too long, Colab may disconnect. You can reconnect by clicking on the "Connect" button.

Magic Commands:

Colab supports various Jupyter magic commands (e.g., %run, %load, %time, etc.) for enhanced functionality.

Colab is a powerful tool, especially for data science, machine learning, and collaborative coding. It provides a
convenient environment for running Python code without the need for local installations.

3
Ahmed Shaikh / 45 AIM FYMCA-B
L

Data Types in Python


Python supports various data types that allow you to store and manipulate different kinds of data. Here are
some of the commonly used data types in Python:

Numeric Types:

int: Integer data type, e.g., 10, -5.

float: Floating-point data type, e.g., 3.14, -2.5.

Sequence Types:

str: String data type, e.g., 'hello', "Python".

list: List data type, e.g., [1, 2, 3], ['apple', 'orange', 'banana'].

tuple: Tuple data type, e.g., (1, 2, 3), ('red', 'green', 'blue').

Set Types:

set: Unordered collection of unique elements, e.g., {1, 2, 3}, {'apple','orange'}.

Mapping Type:

dict: Dictionary data type, e.g., {'name': 'John', 'age': 25}, {'key1':10, 'key2': 20}.

Boolean Type:

bool: Boolean data type, either True or False.

None Type:

NoneType: The type of the None object, representing the absence of a value or a null value.

Sequence Types for Binary Data:

bytes: Immutable sequence of bytes, e.g., b'hello'.

bytearray: Mutable sequence of bytes, e.g., bytearray([65, 66, 67]).

Date and Time Types:

datetime: Date and time representation, part of the datetime module.

Other Built-in Types:

complex: Complex number data type, e.g., 1 + 2j.

range: Represents a range of numbers, e.g., range(5).

4
Ahmed Shaikh / 45 AIM FYMCA-B
L

Variables:
A variable is a named location in the memory where you can store values. In Python, you don't need to
explicitly declare the type of a variable; Python dynamically determines the type at runtime.

# Variable assignmentx = 10
name = "John"pi = 3.14
is_student = True

Rules for variable names:


Must start with a letter (a-z, A-Z) or underscore (_).
The remaining characters can be letters, underscores, or digits (0-9).
Case-sensitive (myVar and myvar are different variables).

In Python, a variable is a symbolic name assigned to a value. Variables are used to store and manage data in
your programs. Here are some key points about variables in Python:

Variable Naming Rules:

• Variable names can contain letters (a-z, A-Z), digits (0- 9), and underscores (_).

•They cannot start with a digit.

•Python is case-sensitive, so myVariable and myvariablewould be different variables.

•Variable names should be descriptive and reflect the purpose of the stored data.

• Variable Assignment: To assign a value to a variable, you use the equal sign (=).

5
Ahmed Shaikh / 45 AIM FYMCA-B
L
Code

my_variable = 10 text = "Hello, World!"

Data Type Inference:

• Python is dynamically typed, so you don't need to explicitly declare the data type of a variable. The
interpreter infers the type based on the assigned value.

Code

x = 5 # x is an integer y = "Hello" # y is a string

• Variable Reassignment: You can change the value of a variable by assigning a new value to it.

Code

count = 10 count = count + 1 # Now count is 11

• Multiple Assignment: You can assign multiple variables in a single line.

Code

a, b, c = 1, 2, 3

• Variable Types: Variables can hold different types of data, such as integers, floats, strings, lists, etc.

Code

num = 42 # integer pi = 3.14 # float name = "John" # string my_list

= [1, 2, 3] # list

Printing Variables: You can print the value of a variable using the print()function.

Code

print(name) # Output: John

• Variable Scope: The scope of a variable determines where it can be accessed. Variables can have global
or local scope.

global_variable = 10 # Global variable def my_function(): local_variable = 5 # Local variable


print(global_variable) # Access global variable my_function()

• Constants: Although Python doesn't have constants in the same way as some other languages, it is a
convention to use uppercase letters for variables whose values should not be changed.

Code

PI = 3.14

6
Ahmed Shaikh / 45 AIM FYMCA-B
L

Conditionals:
Conditionals are used to make decisions in your code based on certain conditions. In Python, you typically use
the if, elif (else if), and else statements.

# Example of conditional statementsage = 20

if age < 18:

print("You are a minor.")elif age >= 18 and age < 21:


print("You are an adult but not allowed to drink.")

else:

print("You are an adult.")

Logical Operators:
and: Logical AND
or: Logical OR
not: Logical NOT

In Python, conditionals are used to make decisions in your code based on certain conditions. The main
conditional statements in Python are if, elif (else if), and else.

if Statement:

The if statement is used to execute a block of code if a specified condition is true.

Example:
python

age = 20

if age < 18:

print("You are a minor.")

else:
print("You are an adult.")

7
Ahmed Shaikh / 45 AIM FYMCA-B
L

if-elif-else Statement:

The if-elif-else statement allows you to handle multiple conditions in a structured way.Each elif (else
if) block is evaluated only if the previous conditions are false.

Example:

python

grade = 85

if grade >= 90:print("A")


elif grade >= 80:print("B")
elif grade >= 70:print("C")
else:

print("D")

Nested if Statements:

You can nest if statements within each other to handle more complex conditions.

Example:
python

x = 10

if x > 0:

if x % 2 == 0:

print("Positive even number.")else:


print("Positive odd number.")elif x < 0:
print("Negative number.")else:
print("Zero.")

8
Ahmed Shaikh / 45 AIM FYMCA-B
L

Comparison Operators:

Comparison operators are used in conditions to compare values. They include:

● == (equal to)
!= (not equal to)
< (less than)
> (greater than)
<= (less than or equal to)
>= (greater than or equal to)python
x = 5

if x == 5:

print("x is equal to 5")elif x < 0:


print("x is negative")else:
print("x is neither 5 nor negative")

Logical Operators:

Logical operators (and, or, not) allow you to combine multiple conditions.

Example:
python age = 25

if age >= 18 and age <= 60:

print("You are in the working age group.")else:


print("You are either too young or too old to work.")

9
Ahmed Shaikh / 45 AIM FYMCA-B
L

Loops:
Loops allow you to repeat a block of code multiple times. In Python, there are two main types of loops: for
and while.

For Loop:

# Example of a for loopfor i in range(5):

print(i)

While Loop:

# Example of a while loopcount = 0

while count < 5:

print(count)count += 1

Break and Continue:

break: Exits the loop prematurely.

continue: Skips the rest of the code inside the loop for the currentiteration.

In Python, loops are used to execute a block of code repeatedly. There are two main types of loops: for and
while.

For Loop:

A for loop is used when you know the number of iterations in advance.

Example 1: Iterate over a sequence of numbers.


python

for i in range(5): # Range generates numbers from 0 to 4print(i)

Example 2: Iterate over elements in a list.

python

fruits = ["apple", "banana", "cherry"]for fruit in fruits:


print(fruit)

10
Ahmed Shaikh / 45 AIM FYMCA-B
L
Example 3: Iterate over characters in a string.
python

for char in "Python":print(char)

While Loop:

A while loop is used when you don't know the number of iterations in advance and the loop continues as
long as a certain condition is true.

Example 1: Basic while loop.


python

count = 0

while count < 5:print(count)count += 1

Example 2: Using break and continue.


python

i = 0

while i < 10:i += 1


if i == 5:

continue # Skips the rest of the code inside the loop forthis iteration
print(i) if i == 8:
break # Exits the loop prematurely

Example 3: Infinite loop (use with caution).


python

while True:

print("This is an infinite loop!")

break # This break statement is necessary to avoid an infiniteloop

Loop Control Statements:

break: Terminates the loop and transfers control to the statement immediately following the loop.
continue: Skips the rest of the code inside the loop for the current iteration and goes to the next iteration.
pass: Acts as a placeholder; it does nothing but avoids an error.python
for i in range(5):if i == 3:
continueelif i == 4:
breakelse:
pass # Placeholderprint(i)

11
Ahmed Shaikh / 45 AIM FYMCA-B
L

Functions:
Functions are blocks of reusable code. They allow you to modularize your code andavoid redundancy.

# Example of a functiondef greet(name):


"""This function greets the person passed in as a parameter."""print("Hello, " + name + "!")

# Call the functiongreet("Alice")


Parameters and Arguments:
Parameters are variables that are used in the function definition.
Arguments are the actual values passed to the function when it is called.
Return Statement:
A function can return a value using the return statement. # Example of a function with a return statement
def add(a, b):

return a + b

result = add(3, 4) print(result) # Output: 7


Functions in Python are blocks of reusable code that perform a specific task. They allow you to break down
your code into smaller, modular pieces, making it more organized, readable, and easier to maintain. Here's
an overview of functions in Python:

Defining a Function:

You can define a function using the def keyword followed by the function name and a pair ofparentheses. If
the function takes parameters, they are specified within the parentheses. The function body is indented.

python

def greet(name):

"""This function greets the person passed in as a parameter."""print("Hello, " +


name + "!")

The triple double-quoted string is a docstring that provides documentation for the function.

Calling a Function:

To use a function, you call it by its name and provide any necessary arguments.python
greet("Alice")

12
Ahmed Shaikh / 45 AIM FYMCA-B
L
Function Parameters:

Parameters are values that are passed into a function when it is called. A function can take zero or more
parameters.

python

def add(x, y):

"""This function adds two numbers."""return x + y

Return Statement:

A function can return a value using the return statement. If no return statement is provided, the function
returns None by default.
python

def add(x, y):

"""This function adds two numbers and returns the result."""

return x + y

Default Values:

You can provide default values for function parameters. If a value is not passed for a parameter, the default
value is used.

python

def power(base, exponent=2):

"""This function calculates the power of a number with a defaultexponent of 2."""


return base ** exponent

13
Ahmed Shaikh / 45 AIM FYMCA-B
L
Variable Scope:

Variables defined inside a function are local to that function and cannot be accessed outside of it. Variables
defined outside of any function have a global scope.

python

global_variable = 10
def my_function(): local_variable = 5
print(global_variable) # Accessing a global variable inside thefunction
print(local_variable)

my_function() print(global_variable)

# print(local_variable) # This would result in an error sincelocal_variable is


not defined in this scope

Lambda Functions:

Lambda functions, also known as anonymous functions, are concise functions defined using the
lambda keyword. They are often used for short, simple operations.python
multiply = lambda x, y: x * y print(multiply(3, 4)) # Output: 12

14
Ahmed Shaikh / 45 AIM FYMCA-B
L
To find if number is odd or even

def fun(num):

if num % 2 == 0:return "Even"


else:

return "Odd"

a = int(input("Enter a number: "))result = fun(a)


print(f"The number {a} is {result}.")

15
Ahmed Shaikh / 45 AIM FYMCA-B
L

To find if number is prime or not

def prime(num):if num <= 1:


return False

for i in range(2, int(num**0.5) + 1):if num % i == 0:


return False

return True

a = int(input("Enter a number: "))if prime(a):


print(f"The number {a} is prime.")else:
print(f"The number {a} is not prime.")

16
Ahmed Shaikh / 45 AIM FYMCA-B
L

Print a pattern

Find a factorial of a number

def fact(n):

if n == 0 or n == 1:return 1
else:

return n * fact(n - 1)

a = int(input("Enter a number: "))result = fact(a)


print(f"The factorial of {a} is {result}.")

17
Ahmed Shaikh / 45 AIM FYMCA-B
L

Find the largest of n

def large(num):if not num:


return "List is empty"

largest = num[0]

for num in num:

if num > largest:largest = num

return largest

list1 = [int(x) for x in input("Enter a list of numbers separated by spaces: ").split()] ans = large(list1)

print(f"The largest number is: {ans}")

18
Ahmed Shaikh / 45 AIM FYMCA-B
L

Sum of digits of a number

def sum1(num):

num_str = str(num)

digit_sum = 0

for digit in num_str: digit_sum += int(digit)

return digit_sum

a = int(input("Enter a num: "))ans = sum1(a)


print(f"The sum of the digits of {a} is: {ans}")

19
Ahmed Shaikh / 45 AIM FYMCA-B
L
Calculator

def add(x, y): return x + y


def subtract(x, y):return x – y
def multiply(x, y):return x * y
def divide(x, y):if y != 0:
return x / yelse:
return "Cannot divide by zero"
def calculator(): print("Select operation:")print("1. Add")
print("2. Subtract")print("3. Multiply") print("4. Divide")
choice = input("Enter choice (1/2/3/4): ")

num1 = float(input("Enter first number: "))


num2 = float(input("Enter second number: "))

if choice == '1':

print(f"{num1} + {num2} = {add(num1, num2)}")elif choice == '2':


print(f"{num1} - {num2} = {subtract(num1, num2)}")elif choice == '3':
print(f"{num1} * {num2} = {multiply(num1, num2)}")elif choice == '4':
print(f"{num1} / {num2} = {divide(num1, num2)}")else:

20
Ahmed Shaikh / 45 AIM FYMCA-B
L
def gross(basic_salary, allowances):

bonus_percentage = 0.10

bonus = basic_salary * bonus_percentage

gross_salary = basic_salary + allowances + bonusreturn gross_salary

try:

basic_salary = float(input("Enter the basic salary: "))allowances = float(input("Enter the allowances: "))

if basic_salary < 0 or allowances < 0:

raise ValueError("Salary and allowances should be non-negative.")

result = gross(basic_salary, allowances)print(f"The gross salary is: {result}")


except ValueError as ve:print(f"Error: {ve}")

21
Ahmed Shaikh / 45 AIM FYMCA-B
L

Fibonnacci series

def fib(n): series1 = [0, 1]

while len(series1) < n: series1.append(series1[-1] + series1[-2])

return series1[:n]

try:

num = int(input("Enter the number of terms in the fib series: "))

if num <= 0:

raise ValueError("Number of terms should be a positive integer.")

result = fib(num)

print(f"The fib series up to {num} terms is: {result}")except ValueError as ve:


print(f"Error: {ve}")

22
Ahmed Shaikh / 45 AIM FYMCA-B
L
First n prime numbers?

def prime1(num):
if num < 2:
return False
for i in range(2, int(num**0.5) + 1):if num % i == 0:
return False
return True

def gen1(n):
primes = []num = 2

while len(primes) < n:if prime1(num): primes.append(num) num += 1


return primes

try:
num1 = int(input("Enter the number of prime numbers to generate: "))
if num1 <= 0:
raise ValueError("Number of primes should be a positive integer.")

result = gen1(num1)
print(f"The first {num1} prime numbers are: {result}")except ValueError as ve:
print(f"Error: {ve}")

23
Ahmed Shaikh / 45 AIM FYMCA-B
L

Exercises Python Data Type Exercises

What is 8 to the power of 5?

a=8**5print(a)
32768

Splitting Of String

a="Hi There Pradeep"b=a.split()


print(b)

['Hi', 'There', 'Pradeep']

24
Ahmed Shaikh / 45 AIM FYMCA-B
L

Format In Python

planet="earth" diameter=12742
a="The Diameter Of Planet {} is {}".format(planet,diameter)print(a)

The Diameter Of Planet earth is 12742

What is the main difference between a tuple and a list?

Feature Tuple List

Syntax (element1, element2, [element1,


...) element2,
...]

Mutabilit Immutable (cannot be changed) Mutable (can be


y changed)

25
Ahmed Shaikh / 45 AIM FYMCA-B
L

Methods Limited methods compared to lists More methods available

Performance Generally faster than lists Generally slower than tuples

Use case Used for immutable sequences Used for mutable sequences

Memory Less memory overhead compared tolists More memory overhead


Overhead

Brackets Parentheses () Square brackets []

Iteration Faster iteration Slightly slower iteration

Applicability Suitable for fixed collections Suitable for dynamic


collections

Create a function that grabs the email website domain from a string in the form: **tushar@ves.ac.in
So for example, passing "tushar@ves.ac.in" would return: ves.ac.in

def sub(a):

parts = a.split('@')

if len(parts) == 2:

26
Ahmed Shaikh / 45 AIM FYMCA-B
L
return parts[1]else:
return None

email = "2023.pradeep.varun@ves.ac.in"domain = sub(email)

if domain:

print("Domain:", domain)else:
print("Invalid email address format.")

Domain: ves.ac.in

27
Ahmed Shaikh / 45 AIM FYMCA-B
L

Create a basic function that returns True if the word 'cat' is contained in the input string. Do account for
capitalization.

def cat(a):

return 'cat' in a.lower()

a = "The Cat is on the mat."result = cat(a)

# Print the resultprint(result)

28
Ahmed Shaikh / 45 AIM FYMCA-B
L

True

Create a function that counts the number of times the word "cat" occurs in a string. Again ignore edge cases.
** countDog('This cat runs faster than the other cats dude!')

def count_cat(a): lowercase_input = a.lower()

cat_count = lowercase_input.count('cat')

return cat_count

input_str = 'This cat runs faster than the other cats dude!' b = count_cat(input_str)

print(b)

29
Ahmed Shaikh / 45 AIM FYMCA-B
L

Use lambda expressions and the filter() function to filter out words from a list that don't start with the letter 's'.
For example:**

seq = ['soup','dog','salad','cat','great']should be filtered down to: ['soup','salad']

['soup', 'salad']

30
Ahmed Shaikh / 45 AIM FYMCA-B
L
You are driving a little too fast, and a police officer stops you. Write a function to return one of 3 possible \
results: "No ticket", "Small ticket", or "Big Ticket". If your speed is 40 or less, the result is "No Ticket". If speed
is between 41 and 80 inclusive, the result is "Small Ticket".
If speed is 81 or more, the result is "Large Ticket". Unless it is your birthday (encoded as a boolean value in
the parameters of the function) -- on your birthday, your speed can be 10 higher in all cases. * def caught
speeding( speed, is_birthday): pass caught_speeding(81,True) 'Small Ticket' caught_speeding(81,False) 'Big
Ticket'

Small TicketBig Ticket

31

You might also like