0% found this document useful (0 votes)
91 views7 pages

Python Functions and Oop

The document contains code examples demonstrating various Python concepts like string processing, classes, exceptions, file handling, testing, and more. It defines a Point class with methods for initialization, string representation, distance calculation and addition of points. It also shows examples of grouping items in a list based on a condition, checking input values, finding months with at least 5 days, defining and running unit tests, and more.
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
Download as txt, pdf, or txt
0% found this document useful (0 votes)
91 views7 pages

Python Functions and Oop

The document contains code examples demonstrating various Python concepts like string processing, classes, exceptions, file handling, testing, and more. It defines a Point class with methods for initialization, string representation, distance calculation and addition of points. It also shows examples of grouping items in a list based on a condition, checking input values, finding months with at least 5 days, defining and running unit tests, and more.
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1/ 7

# Hands On 1

zenPython = '''
The Zen of Python, by Tim Peters

Beautiful is better than ugly.


Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
'''

words = zenPython.split()
print(len(words))

words = [ i.strip(',.-*! ') for i in words]


print(words[3])

words = [ i.lower() for i in words]


print(words[3])

unique_words = set(words)
print(len(unique_words))

word_frequency = { x:len( [y for y in words if y == x] ) for x in unique_words }


print(word_frequency['the'])

frequent_words = { x:word_frequency[x] for x in list(word_frequency.keys()) if


word_frequency[x] > 5}
print(len(frequent_words))

import math

class Point:
def __init__(self, x,y,z):
self.x, self.y, self.z = x,y,z
def __str__(self):
return "point : (%d, %d, %d)"%(self.x, self.y, self.z)
def distance(self, point):
return math.sqrt( (point.x - self.x)**2 + (point.y - self.y)**2 +
(point.z - self.z)**2 )
def __add__(self,punto):
return Point( self.x + punto.x, self.y + punto.y, self.z + punto.z)
p1 = Point(4, 2, 9)
print(p1)

p2 = Point(4, 5, 6)
p3 = Point(-2, -1, 4)
print(p2.distance(p3))

print(p2 + p3)

############################################333

import itertools

def even_or_odd(entero):
if entero % 2 == 0:
return 'even'
return 'odd'

n = [10, 14, 16, 22, 9, 3 , 37]

agrupado = itertools.groupby(n, key= even_or_odd)

for clave, valor in agrupado:


print( "%s %s"%(clave,str(list(valor))) )

#############################3333333

valor = input()
try:
entero = int(valor)
if not (entero in list(range(0,101)) ):
raise ValueError()
except ValueError as ex:
print('Input integer value must be between 0 and 100.')

#########################################3

import os
import os.path

def imprimirPYs(ruta):
for root, dirs, files in os.walk(path, topdown=False ):
files1 = [ x for x in files if x.endswith('.py') ]
for file in files1:
print(file)
for directorio in dirs:
imprimirPYs(directorio)

path = os.path.abspath(os.curdir)
imprimirPYs(path)

##################

valor = input()
try:
if len (valor) > 10:
raise ValueError()
print(valor)
except ValueError as ex:
print('Input String contains more than 10 characters.')

###########################

import calendar

c = calendar.Calendar(0)

lista = [ calendar.month_abbr[x] for x in range(1,13) if len([ y for y in


c.itermonthdays2(2018,x) if y[0]!=0 and y[1] == 0 ]) >= 5 ]

print(lista)

###############################
def isEven(numero):
return ( numero % 2 ) == 0

print (isEven(43))

import unittest

class TestIsEventMethod(unittest.TestCase):
def test_isEven1(self):
self.assertEqual( isEven(5), False)
def test_isEven2(self):
self.assertEqual( isEven(10), True)
def test_isEven3(self):
with self.assertRaises( TypeError ):
isEven('hello')

unittest.main()

#############################################

The output of the expression '2' == 2 is _________.


Results in TypeError
Results in ValueError
False *
True

Which methods are defined in an iterator class?


iter, next
iter, has_next, next
__iter__, __next__ *
iter, has_next, next

Which keyword is used for defining a function?


define
function
def *
func

Which of the following function call is correct?


f(a=1, b=1, c=2, d)
f(a=1, b=1, c=2) *
f(a=1, b)
f(a=1, b, c=2)

###################################3333333333
#What is the output of the following code?
class A:
def __init__(self, x=5, y=4):
self.x = x
self.y = y
def __str__(self):
return 'A(x: {}, y: {})'.format(self.x, self.y)
def __eq__(self, other):
return self.x * self.y == other.x * other.y

def f1():
a = A(12, 3)
b = A(3, 12)
if (a == b):
print(b != a)
print(a)

f1()

############################################33
False

True
A(x: 12, y: 3)

True

False
A(x: 12, y: 3) ## Esta es la salida

################################################3
#What is the output of the following code?
class grandpa(object):
pass
class father(grandpa):
pass
class mother(object):
pass
class child(mother, father):
pass
print(child.__mro__)
####################################3333333

(<class '__main__.object'>, <class '__main__.grandpa'>, <class


'__main__.father'>, <class '__main__.mother'>, <class 'child'>)
(<class '__main__.mother'>, <class '__main__.father'>, <class
'__main__.grandpa'>, <class '__main__.child'>, <class 'object'>)
* (<class '__main__.child'>, <class '__main__.mother'>, <class '__main__.father'>,
<class '__main__.grandpa'>, <class 'object'>)
(<class 'object'>, <class '__main__.child'>, <class '__main__.mother'>, <class
'__main__.father'>, <class '__main__.grandpa'>)

How are variable length non-keyword arguments specified in the function heading?
* Two stars followed by a valid identifier
Two underscores followed by a valid identifier
One underscore followed by a valid identifier
One star followed by a valid identifier

Which of the following statement is not true about Python functions?


Keyword arguments can be passed after non-keyword arguments
* Non-keyword arguments can be passed after keyword arguments
Variable number of arguments can be passed to Python functions
It is not mandatory to write a return expression in a Python function

Which of the following modules are used to deal with Data compression and
archiving?
lzma
* All the options
tarfile
zlib

Which of the following module is not used for parsing command-line arguments
automatically?
* cmdparse
argparse
getopt
optparse

Which of the following keyword is used for creating a method inside a class?
method
sub
* def
class

Which of the following execption occurs, when a number is divided by zero?


* ZeroDivisionError
NonDivisibleError
DivisionError
ArithmeticError

Which of the following method is used by a user defined class to support '+'
operator?
plus
__plus__
* __add__
add

Which of the following statement retrieves names of all builtin module names?
import builtins; builtins.builtins_names
import builtins; builtins.module_names
import sys; sys.builtins_names
* import sys; sys.builtin_module_names

The output of the expression 'itertools.dropwhile(lambda x: x<5, [1,4,6,4,1])' is


_______.
[6]
? [1,4]
[1, 4,6,4,1]
[6,4,1]

Which of the following brackets are used to define a set comprehension?


* {}
<>
[]
()
###############################################333
What is the output of the following code?
class A:
def __init__(self):
print('one')

def f(self):
print(float())
print(hex(-255))

class B(A):
def __init__(self):
print('two')

def f(self):
print(float())
print(hex(-42))
########################
x = B()
x.f()

one
0.0
-0xff

two
0.0
-0xff

one
0.0
-0x2a

* two
0.0
-0x2a

#############################################33
What is the output of the following code?
class A:
x = 0

def __init__(self, a, b):


self.a = a
self.b = b
A.x += 1

def __init__(self):
A.x += 1

def displayCount(self):
print('Count : %d' % A.x)

def display(self):
print('a :', self.a, ' b :', self.b)

a1 = A('George', 25000)
a2 = A('John', 30000)
a3 = A()
a1.display()
a2.display()
print(A.x)

a : George b : 25000
a : John b : 30000
3

a : George b : 25000
a : John b : 30000

Results in Error

a : George b : 25000
a : John b : 30000
2

Which of the following is not a way to import the module 'm1' or the functions 'f1'
and 'f2' defined in it?
* import f1, f2 from m1
from m1 import *
import m1
from m1 import f1, f2

Which of the following error occurs, if an iterator is accessed, when it has no


elements?
* StopIteration
Exhausted
DoneIteration
NoElements

You might also like