45B AIML Practical0
45B AIML Practical0
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.
Click on "New Notebook" to create a new Python notebook. Notebooks are organizedinto cells, which can
contain code, text, or visualizations.
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.
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.
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.
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.
You can install external Python libraries using !pip install directly in a code cell.
You can read data from Google Drive, GitHub, or any other online source directly into your Colab notebook.
If you need to access files on your local machine, you can upload them to Colab using the file upload feature.
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
Numeric Types:
Sequence Types:
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:
Mapping Type:
dict: Dictionary data type, e.g., {'name': 'John', 'age': 25}, {'key1':10, 'key2': 20}.
Boolean Type:
None Type:
NoneType: The type of the None object, representing the absence of a value or a null value.
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
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 names can contain letters (a-z, A-Z), digits (0- 9), and underscores (_).
•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
• 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
• Variable Reassignment: You can change the value of a variable by assigning a new value to it.
Code
Code
a, b, c = 1, 2, 3
• Variable Types: Variables can hold different types of data, such as integers, floats, strings, lists, etc.
Code
= [1, 2, 3] # list
Printing Variables: You can print the value of a variable using the print()function.
Code
• Variable Scope: The scope of a variable determines where it can be accessed. Variables can have global
or local scope.
• 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.
else:
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:
Example:
python
age = 20
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
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:
8
Ahmed Shaikh / 45 AIM FYMCA-B
L
Comparison Operators:
● == (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:
Logical Operators:
Logical operators (and, or, not) allow you to combine multiple conditions.
Example:
python age = 25
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:
print(i)
While Loop:
print(count)count += 1
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.
python
10
Ahmed Shaikh / 45 AIM FYMCA-B
L
Example 3: Iterate over characters in a string.
python
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.
count = 0
i = 0
continue # Skips the rest of the code inside the loop forthis iteration
print(i) if i == 8:
break # Exits the loop prematurely
while True:
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.
return a + b
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):
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
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
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
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)
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):
return "Odd"
15
Ahmed Shaikh / 45 AIM FYMCA-B
L
return True
16
Ahmed Shaikh / 45 AIM FYMCA-B
L
Print a pattern
def fact(n):
if n == 0 or n == 1:return 1
else:
return n * fact(n - 1)
17
Ahmed Shaikh / 45 AIM FYMCA-B
L
largest = num[0]
return largest
list1 = [int(x) for x in input("Enter a list of numbers separated by spaces: ").split()] ans = large(list1)
18
Ahmed Shaikh / 45 AIM FYMCA-B
L
def sum1(num):
num_str = str(num)
digit_sum = 0
return digit_sum
19
Ahmed Shaikh / 45 AIM FYMCA-B
L
Calculator
if choice == '1':
20
Ahmed Shaikh / 45 AIM FYMCA-B
L
def gross(basic_salary, allowances):
bonus_percentage = 0.10
try:
basic_salary = float(input("Enter the basic salary: "))allowances = float(input("Enter the allowances: "))
21
Ahmed Shaikh / 45 AIM FYMCA-B
L
Fibonnacci series
return series1[:n]
try:
if num <= 0:
result = fib(num)
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
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
a=8**5print(a)
32768
Splitting Of String
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)
25
Ahmed Shaikh / 45 AIM FYMCA-B
L
Use case Used for immutable sequences Used for mutable sequences
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
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):
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!')
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:**
['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'
31