0% found this document useful (0 votes)
19 views77 pages

Asm - Artificial Intelligence - 130470

Uploaded by

Gaurav Gupta
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)
19 views77 pages

Asm - Artificial Intelligence - 130470

Uploaded by

Gaurav Gupta
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/ 77

INTRODUCTION TO PYTHON

WHAT IS PYTHON?

• Python is a popular programming language.


• It was created by Guido van Rossum, and released in 1991.
• It is used for:
• web development (server-side),
• software development,
• mathematics,
• system scripting.
W HERE IS P YTHON USED ?
PYTHON -POSITIVES

EASY TO USE INTERPRETED CROSS


EXPRESSIVE COMPLETENESS
LANGUAGE LANGUAGE PLATFORM

VARIETY OF
OPEN SOURCE
USAGE
PYTHON - NEGATIVES

NOT THE LESSER NOT STRONG


NOT EASILY
FASTEST LIBRARIES ON TYPE
CONVERTIBLE
LANG. THAN C, JAVA BINDING
WHERE TO WRITE PYTHON PROGRAMS?

• To write and run Python program, we need to have Python interpreter installed in our
computer. IDLE (GUI integrated) is the standard, most popular Python development
environment.
• IDLE is an acronym of Integrated Development Environment. It lets edit, run,
browse and debug Python Programs from a single interface. This environment makes it
easy to write programs.
• Python shell can be used in two ways, viz., interactive mode and script mode.

• Now, we will first start with interactive mode. Here, we type a Python statement and the
interpreter displays the result(s) immediately.
INTERACTIVE MODE SCRIPT MODE

❖ Allows us to interact with OS. ❖ Let us create and edit python source file.
❖ Helpful when your script is extremely short ❖ In script mode, You write your code in a
and you want immediate results. text file then save it with a .py extension
❖ Faster as you only have to type a command which stands for "Python". Note that you
and then press the enter key to get the can use any text editor for this, including
results. Sublime, Atom, notepad++, etc.
❖ Good for beginners who need to ❖ It is easy to run large pieces of code.
understand Python basics. ❖ Editing your script is easier in script mode.
❖ Good for both beginners and experts.
STARTING IDLE
NOTE :
PYTHON IS A CASE-
SENSITIVE LANGUAGE
PRACTICAL QUESTIONS

Ques 1) Use Python IDLE to print your name and class.


Ques 2) Try the following codes and check the outputs :
i) print 5+7
ii) 5+7
iii) 6*250+9
iv) print 5-7

v) vi)
PRACTICAL #1

Ques 3) Use IDLE to calculate :


• 6*(4+10)
• 6*4+10
Ques 4) Try the following code on python shell and evaluate the output generated:
• print(3.14*7)
• print(‘I am a class 10’ + ‘student’)
• print (‘I’, ‘am’)
• print(“Learning Python”)
• print(“I “am”, “15”,”years old”)
PYTHON COMME NTS

• Comments can be used to explain Python code.


• Comments can be used to make the code more readable.
• Comments can be used to prevent execution when testing code.
DATA TYPES IN PYTHON
PRACTICAL #2

QUES 1) WRITE A PYTHON PROGRAM TO ACCEPT TWO NUMBERS FROM THE USER AND ADD THEM.

#program to add two numbers

#taking user input

num1=int(input("Enter the first number: "))

num2=int(input("Enter the second number: "))

#adding the numbers

num3=num1+num2

#displaying the result

print("The sum is ", num3)


QUES 2) WRITE A PYTHON PROGRAM TO SWAP TWO NUMBERS

a = 10
b = 20
print(“Before swapping\na=", a, " b=", b)
temp = a
a=b
b = temp
print("\n After swapping\n a=", a, " b=", b)

a=45
b=78
a,b=b,a
print("\n After swapping\n a=", a, " b=", b)
QUES 3) WRITE A PYTHON PROGRAM TO PRINT A STRING 10 TIMES.

X="PYTHON ! "
print (X*10)
QUES 4) WRITE A PYTHON PROGRAM TO DEMONSTRATE ARITHMETIC OPERATORS.

#to show the various arithmetic operators

x=int(input("enter first number"))

y=int(input("enter second number"))

print('x + y =',x+y)

print('x - y =',x-y)

print('x * y =',x*y)

print('x / y =',x/y)

print('x // y =',x//y)

print('x ** y =',x**y)
QUES 5) WRITE A PYTHON PROGRAM TO CALCULATE AND DISPLAY SIMPLE INTEREST TAKING
PRINCIPLE,RATE AND TIME AS USER INPUT.

#simple interest
P = float(input("enter amount"))
R = float(input("enter rate"))
T = float(input("enter time"))
# Calculates simple interest
SI = (P * R * T) / 100
# Print the value of SI
print("simple interest is", SI)
QUES 6) WRITE A PYTHON PROGRAM TO DEMONSTRATE VARIOUS RELATIONAL OPERATORS.
#to show the various relational operators
x=int(input("enter first number"))
y=int(input("enter second number"))
print('x > y is‘ , x>y)
print('x < y is', x<y)
print('x == y is', x==y)
enter first number78
enter second number90
print('x != y is', x!=y)
x > y is False
print('x >= y is', x>=y)
print('x <= y is', x<=y)
x < y is True
x == y is False
x != y is True
x >= y is False
x <= y is True
>>>
Write a Python program to calculate surface volume and area of a cylinder .

pi=22/7
height = float(input('Height of cylinder: '))
radius= float(input('Radius of cylinder: '))
volume = pi * radius * radius * height
sur_area = ((2*pi*radius) * height) + ((pi*radius**2)*2)
print("Volume is: ", volume)
print("Surface Area is: ", sur_area)
Write a Python program to calculate and display
the percentage of a student. Take user input for 5
subjects.
• #to calculate percentage of 5 subjects taken from the user assuming out of 50

• x1=int(input("enter the marks in sub 1: "))


• x2=int(input("enter the marks in sub 2: "))
• x3=int(input("enter the marks in sub 3: "))
• x4=int(input("enter the marks in sub 4: "))
• x5=int(input("enter the marks in sub 5: "))
• percentage=float((x1+x2+x3+x4+x5)*100/250)
• print(percentage,"%")
LISTS IN PYTHON
LISTS IN PYTHON

• List is a sequence of values of any type. It can have any number of items and
they may be of different types (integer, float, string etc.).
• Values in the list are called elements / items.
• List is enclosed in square brackets.
• Example: a = [1,2.3,"Hello"]
HOW TO CREATE A LIST?

#empty list
empty_list = []
#list of integers
age = [15,12,18]
#list with mixed data types
student_height_weight = ["Ansh", 5.7, 60]
HOW TO ACCESS ELEMENTS OF A LIST?

There are two ways to access an individual element of a list:


1) List Index
2) Negative Indexing
List Index-- A list index is the position at which any element is present in the list. Index in
the list starts from 0, so if a list has 5 elements the index will start from 0 and go on till 4. In
order to access an element in a list we need to use index operator [].
Negative Indexing-- Python allows negative indexing for its sequences. The index of -1
refers to the last item, -2 to the second last item and so on.
my_list = ['p',‘r’,‘o',‘b',‘e']
p
print(my_list[0]) e
print(my_list[4]) Error: only integer indexes can be used
e
print(my_list[4.0])
Error : list index out of bounds
print(my_list[-1])
HOW TO ADD ELEMENTS TO A LIST?
HOW TO RE MOVE ITE MS FROM THE LIST?

The remove( ) method removes the specified item BY VALUE.

thislist = ["apple", "banana", "cherry”, “mango”]


thislist.remove("banana")
print(thislist)

The pop() method removes the specified index, (or the last item if index is not specified):
thislist = ["apple", "banana", "cherry", "mango"]
thislist.pop(2)
thislist.pop()
print(thislist)
SLICING A LIST
Python List Methods
append() - Add an element to the end of the list
extend() - Add all elements of a list to the another list
insert(i,x) - Insert an item at the defined index Insert an item at a given
position. The first argument is the index of the element before which to
insert, so a.insert(0, x) inserts at the front of the list,
and a.insert(len(a), x) is equivalent to a.append(x)
remove() - Removes an item from the list
pop() - Removes and returns an element at the given index
Python List Methods

clear() - Removes all items from the list


index() - Returns the index of the first matched item
>>> my_list=['a','b','d',89,78]
>>> my_list.index('a')
0

count() - Returns the count of number of items passed as an argument


sort() - Sort items in a list in ascending order
reverse() - Reverse the order of items in the list
copy() - Returns a shallow copy of the list
>>> my_list.copy()
['a', 'b', 'd', 89, 78]
A N E X A M P L E T H AT U S E S M O S T O F T H E L I S T M E T H OD S :

>>> fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']

.
>>> fruits count('apple')
2

.
>>> fruits count('tangerine')
0

.
>>> fruits index('banana')
3

.
>>> fruits index('banana', 4) # Find next banana starting a position 4
6

.
>>> fruits reverse()
>>> fruits ['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']

.
>>> fruits append ('grape')
>>> fruits ['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape']

.
>>> fruits sort()
>>> fruits ['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear']

.
>>> fruits pop () 'pear' # removes the specified item in the given index or removes the last item
The index() method searches an element in the list and returns its index.
TUPLES IN PYTHON
Tuple is a collection of Python objects which is ordered and unchangeable.

The sequence of values stored in a tuple can be of any type, and they are
indexed by integers.

Values of a tuple are syntactically separated by ‘commas’

Example :
thistuple = ("apple", "banana", "cherry")
print(thistuple)
ACCESSING OF TUPLES

❑ We can use the index operator [] to access an item in a tuple where the index starts
from 0.

❑ So, a tuple having 6 elements will have indices from 0 to 5.

❑ Trying to access an element outside of tuple (for example, 6, 7,...) will raise an
IndexError.

❑ The index must be an integer; so, we cannot use float or other types. This will result in
TypeError.

❑ Example fruits = ("apple", "banana", "cherry") print(fruits[1]) The above code will give the
output as "banana"
DELETING A TUPLE

Tuples are immutable and hence they do not allow deletion of a part of it. Entire tuple
gets deleted by the use of del() method.

Example :
num = (0, 1, 2, 3, 4)
del num
Range of Indexes

You can specify a range of indexes by specifying where to start and where to end the
range.

When specifying a range, the return value will be a new tuple with the specified items.
DECISION MAKING STATEMENTS

Decision making statements in programming languages decide


the direction of flow of program execution.

Decision making statements available in Python are:


● if statement
● if. Else statements
● if-elif ladder
Python if...else Statement
Syntax of if...else
if test expression:
Body of if
else:
Body of else

The if..else statement evaluates test expression and will execute body of if only when test
condition is True. If the condition is False, body of else is executed. Indentation is used to
separate the blocks.

#A program to check if a person can vote


age = input(“Enter Your Age”)
if age >= 18:
print(“You are eligible to vote”)
else:
print(“You are not eligible to vote”)
#PRACTIC AL
Write a Python program to find whether a given number (accept from
the user) is even or odd, print out an appropriate message to the
user.

num = int(input("Enter a number: "))


mod = num % 2
if mod > 0:
print("This is an odd number.")
else:
print("This is an even number.")
Python if...elif…else Statement
Syntax of if...elif...else
if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else

#To check the grade of a student


Marks = 60
if marks > 75:
print("You get an A grade")
elif marks > 60:
print("You get a B grade")
else:
print("You get a C grade")
Python Nested if statements

# In this program, we input a number


# check if the number is positive or
# negative or zero and display
# an appropriate message
# This time we use nested if

num = float(input("Enter a number: "))


if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
LOOPS/ ITERATION STATEMENTS
FOR LOOP
The for..in statement is a looping statement which iterates over a sequence of objects i.e. go through each item
in a sequence.
Loop continues until we reach the last item in the sequence.
The body of for loop is separated from the rest of the code using indentation.

# Program to find the sum of all numbers stored in a list


# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
# variable to store the sum
sum = 0
# iterate over the list
for val in numbers:
sum = sum+val
# Output:The sum is 48
print("The sum is", sum)
#PRACTIC AL

2. Print all elements of a list using for loop.


3. Print a list using input from the user Print all elements of a list using
4. for loop.
1. # Program to print squares of all numbers present in a list
list1=[34,23,56,76,45,56,12]
for i in list1:
# List of integer numbers print(i)
numbers = [1, 2, 4, 6, 11, 20]

# variable to store the square of each num


3. Print a list using input from the user
sq = 0
# iterating over the given list list1=[]
for num in numbers: print(list1)
n=int(input("enter the items in a list"))
# calculating square of each number
for i in range(0,n):
sq = num * num x=input()
# displaying the squares list1.append(x)
print(list1)
print(sq)
WHILE LOOP

➢ The while statement allows you to repeatedly execute a block of statements as long as a condition is true.
➢ A while statement can have an optional else clause.

➢ Syntax of while Loop in Python


while test_expression:
Body of while

➢ In while loop, test expression is checked first.


➢ The body of the loop is entered only if the test_expression evaluates to True.After one iteration, the test
expression is checked again.This process continues until the test_expression evaluates to False.

➢ In Python, the body of the while loop is determined through indentation. Body starts with indentation and
the first unindented line marks the end.

➢ Python interprets any non-zero value as True. None and 0 are interpreted as False.
# Program to add natural numbers upto sum = 1+2+3+...+n
# To take input from the user,
n = int(input("Enter n: "))
#n = 10
# initialize sum and counter
sum = 0
i=1
while i <= n:
sum = sum + i
i = i+1 # update counter
# print the sum
print("The sum is", sum)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy