0% found this document useful (0 votes)
10 views18 pages

PYTHON

The document provides a series of Python programming examples covering various concepts such as output, data types, arithmetic operations, relational and logical operators, as well as data structures like lists, sets, tuples, and dictionaries. Each example includes code snippets along with their expected output. The document serves as a comprehensive guide for beginners to understand fundamental Python programming concepts.

Uploaded by

Meera Desai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views18 pages

PYTHON

The document provides a series of Python programming examples covering various concepts such as output, data types, arithmetic operations, relational and logical operators, as well as data structures like lists, sets, tuples, and dictionaries. Each example includes code snippets along with their expected output. The document serves as a comprehensive guide for beginners to understand fundamental Python programming concepts.

Uploaded by

Meera Desai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

SR PROGRAM OUTPUT

1 print("Hello World") Hello World


2 # Python program showing
# indentation Logging on to geeksforgeeks...
All set !
site = 'gfg'

if site == 'gfg':
print('Logging on to geeksforgeeks...')
else:
print('retype the URL.')
print('All set !')

3 # An integer assignment
age = 45 45
1456.8
# A floating point John
salary = 1456.8

# A string
name = "John"

print(age)
print(salary)
print(name)

4 # Examples of Arithmetic Operator


a=9 13
b=4 5
36
# Addition of numbers 2.25
add = a + b 2
# Subtraction of numbers 1
sub = a - b
# Multiplication of number
mul = a * b
# Division(float) of number
div1 = a / b
# Division(floor) of number
div2 = a // b
# Modulo of both number
mod = a % b

# print results
print(add)
print(sub)
print(mul)
print(div1)
print(div2)
print(mod)
5 # Examples of Relational Operators
a = 13 False
b = 33 True
False
# a > b is False True
print(a > b) False
True
# a < b is True
print(a < b)
# a == b is False
print(a == b)

# a != b is True
print(a != b)

# a >= b is False
print(a >= b)

# a <= b is True
print(a <= b)

6 # Examples of Logical Operator


a = True False
b = False True
False
# Print a and b is False
print(a and b)

# Print a or b is True
print(a or b)

# Print not a is False


print(not a)

7 # Examples of Bitwise operators


a = 10 0
b=4 14
-11
# Print bitwise AND operation 14
print(a & b) 2
40
# Print bitwise OR operation
print(a | b)

# Print bitwise NOT operation


print(~a)

# print bitwise XOR operation


print(a ^ b)

# print bitwise right shift operation


print(a >> 2)

# print bitwise left shift operation


print(a << 2)

8 # Examples of Identity and


# Membership operator False
True
True
a1 = 'GeeksforGeeks' True
b1 = 'GeeksforGeeks'

# Identity operator
print(a1 is not b1)
print(a1 is b1)
# Membership operator
print("G" in a1)
print("N" not in b1)

9 # Python program showing


# a use of raw_input() VISUAL
VISUAL
g = raw_input("Enter your name : ")
print g
10 # Python program showing
# a use of input() 5
5
val = input("Enter your value: ")
print(val)

11 # Python 3.x program showing


# how to print data on GeeksForGeeks
# a screen x=5
GFG
# One object is passed Python@GeeksforGeeks
print("GeeksForGeeks")

x=5
# Two objects are passed
print("x =", x)

# code for disabling the softspace feature


print('G', 'F', 'G', sep ='')

# using end argument


print("Python", end = '@')
print("GeeksforGeeks")

12 # Python program to
# demonstrate numeric value Type of a: <class 'int'>

print("Type of a: ", type(5)) Type of b: <class 'float'>

print("\nType of b: ", type(5.0)) Type of c: <class 'complex'>

c = 2 + 4j
print("\nType of c: ", type(c))

13 # Python Program for


# Creation of String Welcome to the Geeks World
I'm a Geek
# String with single quotes I'm a Geek and I live in a world of "Geeks"
print('Welcome to the Geeks World')

# String with double quotes


print("I'm a Geek")

# String with triple quotes


print('''I'm a Geek and I live in a world of "Geeks"''')
14 # Python Program to Access
# characters of String G
s
String1 = "GeeksForGeeks"
# Printing First character
print(String1[0])

# Printing Last character


print(String1[-1])

15 # Python Program to Update / delete


# character of a String Traceback (most recent call last):
File
String1 = "Hello, I'm a Geek" “/home/360bb1830c83a918fc78aa8979195653.py”,
line 6, in
# Updating a character String1[2] = ‘p’
String1[2] = 'p' TypeError: ‘str’ object does not support item
assignment
# Deleting a character
del String1[2] Traceback (most recent call last):
File
“/home/499e96a61e19944e7e45b7a6e1276742.py”,
line 8, in
del String1[2]
TypeError: ‘str’ object doesn’t support item deletion

16 # Python program to demonstrate


# Creation of List []
['GeeksForGeeks', 'Geeks']
# Creating a List [['Geeks', 'For'], ['Geeks']]
List = []
print(List)

# Creating a list of strings


List = ['GeeksForGeeks', 'Geeks']
print(List)

# Creating a Multi-Dimensional List


List = [['Geeks', 'For'], ['Geeks']]
print(List)

17 # Python program to demonstrate


# Addition of elements in a List [1, 2]
['Geeks', 1, 2, 12]
# Creating a List ['Geeks', 1, 2, 12, 8, 'Geeks', 'Always']
List = []

# Using append()
List.append(1)
List.append(2)
print(List)

# Using insert()
List.insert(3, 12)
List.insert(0, 'Geeks')
print(List)

# Using extend()
List.extend([8, 'Geeks', 'Always'])
print(List)

18 # Python program to demonstrate


# accessing of element from list 1
3
6
List = [1, 2, 3, 4, 5, 6] 4

# accessing a element
print(List[0])
print(List[2])

# Negative indexing
# print the last element of list
print(List[-1])
# print the third last element of list
print(List[-3])
19 # Python program to demonstrate
# Removal of elements in a List [1, 2, 3, 4, 7, 8, 9, 10, 11, 12]
[1, 2, 3, 4, 7, 8, 9, 10, 11]
# Creating a List
List = [1, 2, 3, 4, 5, 6,
7, 8, 9, 10, 11, 12]

# using Remove() method


List.remove(5)
List.remove(6)
print(List)

# using pop()
List.pop()
print(List)
20 # Python program to demonstrate
# creation of Set ()
('Geeks', 'For')
# Creating an empty tuple (1, 2, 4, 5, 6)
Tuple1 = () ((0, 1, 2, 3), ('python', 'geek'))
print (Tuple1)

# Creating a tuple of strings


print(('Geeks', 'For'))

# Creating a Tuple of list


print(tuple([1, 2, 4, 5, 6]))

# Creating a nested Tuple


Tuple1 = (0, 1, 2, 3)
Tuple2 = ('python', 'geek')
Tuple3 = (Tuple1, Tuple2)
print(Tuple3)

21 # Python program to
# demonstrate accessing tuple 1
5
tuple1 = tuple([1, 2, 3, 4, 5])

# Accessing element using indexing


print(tuple1[0])

# Accessing element using Negative


# Indexing
print(tuple1[-1])
22 # Python program to
# demonstrate updation / deletion Traceback (most recent call last):
# from a tuple File
"/home/084519a8889e9b0103b874bbbb93e1fb.py",
tuple1 = tuple([1, 2, 3, 4, 5]) line 11, in
tuple1[0] = -1
# Updating an element TypeError: 'tuple' object does not support item
tuple1[0] = -1 assignment

# Deleting an element Traceback (most recent call last):


del tuple1[2] File
"/home/ffb3f8be85dd393bde5d0483ff191343.py",
line 12, in
del tuple1[2]
TypeError: 'tuple' object doesn't support item
deletion

23 # Python program to
# demonstrate boolean type <class 'bool'>
False
print(type(True)) True
print(1>2)
print('a'=='a')

24 # Python program to demonstrate


# Creation of Set in Python {'o', 'r', 'k', 'G', 'e', 's', 'F'}
{'Geeks', 'For'}
# Creating a Set
set1 = set()

# Creating a Set of String


set1 = set("GeeksForGeeks")
print(set1)

# Creating a Set of List


set1 = set(["Geeks", "For", "Geeks"])
print(set1)
25 # Python program to demonstrate
# Addition of elements in a Set {8, (6, 7)}
{8, 10, 11, (6, 7)}

set1 = set()

# Adding to the Set using add()


set1.add(8)
set1.add((6, 7))
print(set1)

# Additio to the Set using Update()


set1.update([10, 11])
print(set1)
26 # Python program to demonstrate
# Accessing of elements in a set Geeks For

# Creating a set
set1 = set(["Geeks", "For", "Geeks"])

# Accessing using for loop


for i in set1:
print(i, end =" ")

27 # Python program to demonstrate


# Deletion of elements in a Set {1, 2, 3, 4, 7, 8, 9, 10, 11, 12}
{1, 2, 3, 4, 7, 10, 11, 12}
set1 = set([1, 2, 3, 4, 5, 6, {2, 3, 4, 7, 10, 11, 12}
7, 8, 9, 10, 11, 12]) set()

# using Remove() method


set1.remove(5)
set1.remove(6)
print(set1)

# using Discard() method


set1.discard(8)
set1.discard(9)
print(set1)

# Set using the pop() method


set1.pop()
print(set1)

# Set using clear() method


set1.clear()
print(set1)

28 # Creating an empty Dictionary


Dict = {} {}
print(Dict) {1: 'Geeks', 2: 'For', 3: 'Geeks'}
{1: [1, 2, 3, 4], 'Name': 'Geeks'}
# with Integer Keys
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print(Dict)

# with Mixed keys


Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}
print(Dict)
29 # Creating a Nested Dictionary
# as shown in the below image {1: 'Geeks', 2: 'For', 3: {'A': 'Welcome', 'B': 'To', 'C':
Dict = {1: 'Geeks', 2: 'For', 'Geeks'}}
3:{'A' : 'Welcome', 'B' : 'To', 'C' : 'Geeks'}}

print(Dict)

30 # Creating an empty Dictionary {0: 'Geeks', 2: 'For', 3: 1}


Dict = {} {0: 'Geeks', 2: 'Welcome', 3: 1}

# Adding elements one at a time


Dict[0] = 'Geeks'
Dict[2] = 'For'
Dict[3] = 1
print(Dict)

# Updating existing Key's Value


Dict[2] = 'Welcome'
print(Dict)

31 # Python program to demonstrate For


# accessing an element from a Dictionary Geeks

# Creating a Dictionary
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}

# accessing a element using key


print(Dict['name'])

# accessing a element using get()


print(Dict.get(3))

32 # Initial Dictionary {'A': {1: 'Geeks', 2: 'For', 3: 'Geeks'}, 6: 'To', 7: 'Geeks'}


Dict = { 5 : 'Welcome', 6 : 'To', 7 : 'Geeks', {6: 'To', 7: 'Geeks'}
'A' : {1 : 'Geeks', 2 : 'For', 3 : 'Geeks'},
}

# using pop()
Dict.pop(5)
print(Dict)

# using popitem()
Dict.popitem()
print(Dict)

33 # Python program to demonstrate Even Number


# decision making Odd Number

a = 10
b = 15

# if to check even number


if a % 2 == 0:
print("Even Number")

# if-else to check even or odd


if b % 2 == 0:
print("Even Number")
else:
print("Odd Number")

34 # Python program to demonstrate Number is divisible by both 2 and 5


# decision making a is 10

a = 10

# Nested if to check whether a


# number is divisible by both 2 and 5
if a % 2 == 0:
if a % 5 == 0:
print("Number is divisible by both 2 and 5")

# is-elif
if (a == 11):
print ("a is 11")
elif (a == 10):
print ("a is 10")
else:
print ("a is not present")
35 # Python program to illustrate Hello Geek
# while and while-else loop Hello Geek
i=0 Hello Geek
while (i < 3): 4
i=i+1 3
print("Hello Geek") 2
1
# checks if list still 11
# contains any element
a = [1, 2, 3, 4]
while a:
print(a.pop())

i = 10
while i < 12:
i += 1
print(i)
break
else: # Not executed as there is a break
print("No Break")

36 # Python program to illustrate List Iteration


# Iterating over a list geeks
print("List Iteration") for
l = ["geeks", "for", "geeks"] geeks
for i in l:
print(i) String Iteration
G
# Iterating over a String e
print("\nString Iteration") e
s = "Geeks" k
for i in s : s
print(i)
For-else loop
print("\nFor-else loop") G
for i in s: e
print(i) e
else: # Executed because no break in for k
print("No Break\n") s
No Break
for i in s:
print(i) G
break
else: # Not executed as there is a break
print("No Break")

37 # Python program to demonstrate 01234


# range() function 2345678
15 18 21 24

for i in range(5):
print(i, end =" ")
print()

for i in range(2, 9):


print(i, end =" ")
print()

# incremented by 3
for i in range(15, 25, 3):
print(i, end =" ")

38 # Python program to demonstrate g


# break, continue and pass gkforgk
geeksforgeeks
s = 'geeksforgeeks'

for letter in s:
if letter == 'e' or letter == 's':
break
print(letter, end = " ")
print()

for letter in s:
if letter == 'e' or letter == 's':
continue
print(letter, end = " ")
print()

for letter in s:
if letter == 'e' or letter == 's':
pass
print(letter, end = " ")

39 # Python program to demonstrate Hello Geeks


# functions 55

# Defining functions
def ask_user():
print("Hello Geeks")

# Function that returns sum


# of first 10 numbers
def my_func():
a=0
for i in range(1, 11):
a=a+i
return a

# Calling functions
ask_user()
res = my_func()
print(res)

40 # Python program to demonstrate ('x: ', 10)


# default arguments ('y: ', 50)

def myFun(x, y = 50):


print("x: ", x)
print("y: ", y)

# Driver code
myFun(10)

41 # Python program to demonstrate Keyword Arguments ('Geeks', 'Practice')


def student(firstname, lastname): ('Geeks', 'Practice')
print(firstname, lastname)

# Keyword arguments
student(firstname ='Geeks', lastname ='Practice')
student(lastname ='Practice', firstname ='Geeks')

42 # Python program to demonstrate Hello Welcome to GeeksforGeeks


# variable length arguments first == Geeks
last == Geeks
mid == for
# variable arguments
def myFun1(*argv):
for arg in argv:
print(arg, end =" ")

# variable keyword arguments


def myFun2(**kwargs):
for key, value in kwargs.items():
print ("% s == % s" %(key, value))

# Driver code
myFun1('Hello', 'Welcome', 'to', 'GeeksforGeeks')
print()
myFun2(first ='Geeks', mid ='for', last ='Geeks')

43 # Python code to demonstrate 343


# labmda function [0, 2, 4, 6, 8]

# Cube using lambda


cube = lambda x: x * x*x
print(cube(7))

# List comprehension using lambda


a = [(lambda x: x * 2)(x) for x in range(5)]
print(a)

44 # Python program to demonstrate mamal


# classes and objects I'm a mamal
I'm a dog
class Dog:

# A simple class attribute


attr1 = "mamal"
attr2 = "dog"

# A sample method
def fun(self):
print("I'm a", self.attr1)
print("I'm a", self.attr2)

# Driver code
# Object instantiation
Rodger = Dog()

# Accessing class attributes


# and method through objects
print(Rodger.attr1)
Rodger.fun()
45 # Python program to demonstrate 3000
# constructors

class Addition:
# parameterized constructor
def __init__(self, f, s):
self.first = f
self.second = s

def calculate(self):
print(self.first + self.second)

# Invoking parameterized constructor


obj = Addition(1000, 2000)

# perform Addition
obj.calculate()

46 # Python program to illustrate destructor Employee created.


class Employee: Destructor called, Employee deleted.

# Initializing
def __init__(self):
print('Employee created.')

# Deleting (Calling destructor)


def __del__(self):
print('Destructor called, Employee deleted.')

obj = Employee()
del obj

47 # A Python program to demonstrate inheritance Geek1 False


Geek2 True

class Person():

# Constructor
def __init__(self, name):
self.name = name

# To get name
def getName(self):
return self.name

# To check if this person is employee


def isEmployee(self):
return False

# Inherited or Sub class (Note Person in bracket)


class Employee(Person):

# Here we return true


def isEmployee(self):
return True
# Driver code
emp = Person("Geek1") # An Object of Person
print(emp.getName(), emp.isEmployee())

emp = Employee("Geek2") # An Object of Employee


print(emp.getName(), emp.isEmployee())

48 # Python program to demonstrate Traceback (most recent call last):


# encapsulation File
"/home/5a605c59b5b88751d2b93dd5f932dbd5.py",
# Creating a Base class line 20, in
class Base: obj = Derived()
def __init__(self): File
self.a = "GeeksforGeeks" "/home/5a605c59b5b88751d2b93dd5f932dbd5.py",
self.__c = "GeeksforGeeks" line 18, in __init__
print(self.__a)
# Creating a derived class AttributeError: 'Derived' object has no attribute
class Derived(Base): '_Derived__a'
def __init__(self):

# Calling constructor of
# Base class
Base.__init__(self)
print("Calling private member of base class: ")
print(self.__a)
# Driver code
obj = Derived()

49 # Python program to demonstrate Inside A


# Polymorphism Inside B

class A():
def show(self):
print("Inside A")

class B():
def show(self):
print("Inside B")

# Driver's code
a = A()
a.show()
b = B()
b.show()

ACCESS MODE DESCRIPTION


Read Only (‘r’) Open text file for reading. The handle is positioned at the beginning of the file.
Read and Write (‘r+’) Open the file for reading and writing. The handle is positioned at the beginning of the file.
Write Only (‘w’) Open the file for writing. For existing file, the data is truncated and over-written. The handle is positioned at
the beginning of the file.
Write and Read (‘w+’) Open the file for reading and writing. For existing file, data is truncated and over-written. The
handle is positioned at the beginning of the file.
Append Only (‘a’) Open the file for writing. The handle is positioned at the end of the file.
Append and Read (‘a+’) Open the file for reading and writing. The handle is positioned at the end of the file.

50 # Open function to open the file "MyFile1.txt"


# (same directory) in read mode and
file1 = open("MyFile.txt", "r")
# store its reference in the variable file1
# and "MyFile2.txt" in D:\Text in file2
file2 = open(r"D:\Text\MyFile2.txt", "r+")
51 # Opening and Closing a file "MyFile.txt"
# for object name file1.
file1 = open("MyFile.txt", "a")
file1.close()

52 # Program to show various ways to Output of Read function is


# read data from a file. Code is like humor. When you have to explain it, its
bad.
file1 = open("data.txt", "r+")
Output of Readline function is
print("Output of Read function is ") Code is like humor. When you have to explain it, its
print(file1.read()) bad.
print()
Output of Readlines function is
# seek(n) takes the file handle to the nth ['Code is like humor. When you have to explain it, its
# bite from the beginning. bad.']
file1.seek(0)

print("Output of Readline function is ")


print(file1.readline())
print()

file1.seek(0)

# readlines function
print("Output of Readlines function is ")
print(file1.readlines())
print()
file1.close()

53 # Python program to demonstrate

# writing to file

# Opening a file

file1 = open('myfile.txt', 'w')

L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]

s = "Hello\n"

# Writing a string to file

file1.write(s)

# Writing multiple strings

# at a time

file1.writelines(L)
# Closing file

file1.close()

54 # Python program to demonstrate


# modules

# Defining a function
def Geeks():
print("GeeksforGeeks")

# Defining a variable
location = "Noida"

# Defining a class
class Employee():

def __init__(self, name, position):


self. name = name
self.position = position

def show(self):
print("Employee name:", self.name)
print("Employee position:", self.position)

55 # Python program to demonstrate GeeksforGeeks


# modules Noida
Employee name: Nikhil
Employee position: Developer
import GFG

# Use the function created


GFG.Geeks()

# Print the variable declared


print(GFG.location)

# Use the class created


emp = GFG.Employee("Nikhil", "Developer")
emp.show()

56 # Python code to illustrate the Modules


class Bmw:

def __init__(self):
self.models = ['i8', 'x1', 'x5', 'x6']

def outModels(self):
print('These are the available models for BMW')
for model in self.models:
print('\t % s ' % model)

57 # Python code to illustrate the Module


class Audi:

def __init__(self):
self.models = ['q7', 'a6', 'a8', 'a3']
def outModels(self):
print('These are the available models for Audi')
for model in self.models:
print('\t % s ' % model)

58 # Import classes from your brand new package


from Cars import Bmw
from Cars import Audi

# Create an object of Bmw class & call its method


ModBMW = Bmw()
ModBMW.outModels()

# Create an object of Audi class & call its method


ModAudi = Audi()
ModAudi.outModels()

59 re.findall(): Return all non-overlapping matches of pattern in ['123456789', '987654321']


string, as a list of strings. The string is scanned left-to-right,
and matches are returned in the order found.
# A Python program to demonstrate working of

# findall()

import re

string = """Hello my Number is 123456789 and

my friend's number is 987654321"""

# A sample regular expression to find digits.

regex = '\d+'

match = re.findall(regex, string)

print(match)

60 # A Python program to demonstrate working of ['e', 'a', 'd', 'b', 'e', 'a']
# compile()
import re

# it is equivalent to [abcde].
p = re.compile('[a-e]')

print(p.findall("Aye, said Mr. Gibenson Stark"))

61 # A Python program to demonstrate working Given Data: Jun 24


# of re.match(). Month: Jun
import re Day: 24

Not a valid date


def findMonthAndDate(string):

regex = r"([a-zA-Z]+) (\d+)"


match = re.match(regex, string)

if match == None:
print("Not a valid date")
return

print("Given Data: % s" % (match.group()))


print("Month: % s" % (match.group(1)))
print("Day: % s" % (match.group(2)))

# Driver Code
findMonthAndDate("Jun 24")
print("")
findMonthAndDate("I was born on June 24")

62 # A Python program to demonstrate working of re.match(). Match at index 14, 21


import re Full match: June 24
Month: June
regex = r"([a-zA-Z]+) (\d+)" Day: 24

match = re.search(regex, "I was born on June 24")

if match != None:

print("Match at index % s, % s" % (match.start(),


match.end()))

# this will print "June 24"


print("Full match: % s" % (match.group(0)))

# this will print "June"


print("Month: % s" % (match.group(1)))

# this will print "24"


print("Day: % s" % (match.group(2)))

else:
print("The regex pattern does not match.")

63 # Python code to illustrate Yeah! Your answer is : 1

# working of try()

def divide(x, y):

try:

result = x // y

print("Yeah ! Your answer is :", result)

except ZeroDivisionError:

print("Sorry ! You are dividing by zero ")

# Look at parameters and note the working of Program

divide(3, 2)
64 # Python code to illustrate Sorry! You are dividing by zero
# working of try()
def divide(x, y):
try:
result = x // y
print("Yeah ! Your answer is :", result)
except:
print("Sorry ! You are dividing by zero ")

# Look at parameters and note the working of Program


divide(3, 0)

65 # Python code to illustrate Yeah ! Your answer is : 1


# working of try() No exception raised
def divide(x, y):
try:
result = x // y
print("Yeah ! Your answer is :", result)
except:
print("Sorry ! You are dividing by zero ")
else:
print("No exception raised")

# Look at parameters and note the working of Program


divide(3, 2)

66 # Program to depict Raising Exception Traceback (most recent call last):


File
try: "/home/4678cd3d633b2ddf9d19fde6283f987b.py",
raise NameError("Hi there") # Raise Error line 4, in
except NameError: raise NameError("Hi there") # Raise Error
print("An exception") NameError: Hi there
raise # To determine whether the exception was raised or
not

You might also like