A concise tutorial to a concise language
Prakat Solutions
9th July 2016
class MyClass(object):
variable = "blah"
def function(self):
print "This is a message inside the class."
myobjectx = MyClass()
myobjecty = MyClass()
myobjecty.variable = "yackity"
print myobjectx.variable # This would print "blah".
print myobjecty.variable # This would print "yackity".
myobjectx.function()
print type(myobjectx)
In this exercise, we are going to create a banking system.
Create a class called Account that represents a customer account. It must contain the following variables and functions:
Create two objects of type Account:
‘Acct1’ is a savings account that belongs to “Mishra” and has a current balance of Rs. 10000.00. He makes a deposit of Rs. 1500.00 into it, followed by a withdrawal of Rs. 7000.
‘Acct2’ is a personal account that belongs to “Chopra” and has a current balance of Rs. 5000. He makes 2 withdrawals of Rs. 4000 and Rs. 2000 each.
myList = [1,2,3]
myList.append(4)
print (myList)
myTuple = (1,2,3)
print (myTuple)
myTuple.append(4)
#Generates an error!
print (myTuple)
# Fibonacci numbers module
# write Fibonacci series up to n
def fib(n):
a, b = 0, 1
while b < n:
print b,
a, b = b, a+b
# return Fibonacci series up to n
def fib2(n):
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
return result
>>> import fibo
>>> fibo.fib(1000)
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
>>> fibo.fib2(100)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>> fibo.__name__
'fibo'
#Package foo
#Defines packages & modules in foo
__init__.py:
#a list of packages and modules
__all__ = ["bar"]
>>> import foo.bar
>>> from foo import bar
import sys
try:
numerator = int(input("Enter the numerator: "))
denominator = int(input("Enter the denominator: "))
ans = numerator/denominator
except ZeroDivisionError: #when division by zero occurs
print "answer is undefined"
print "Oops!",sys.exc_info()[0],"occured :("
print "Please try again!"
except ValueError: #when incorrect value is entered
print "Incorrect value entered"
print "Oops!",sys.exc_info()[0],"occured :("
print "Please try again!"
except: #Handles all other exceptions
print "Oops!",sys.exc_info()[0],"occured :("
print "Please try again!"
else:
ans= numerator/denominator
print ans
finally:
print "This is in the finally block"
You need to iterate over the list of 20 numbers, but the list is made from user input, and might not have 20 numbers in it.
Ask the user to input a list of integers. Iterate over a list of 20 numbers and display it. Check for Index errors(index value out of range) and any other errors encountered during user input.
In the case of index errors, make the rest of the numbers as a 0 for display.
In the case of any other errors, print “Exception has been handled”
string = 'This is a\nnormal string'
rawString = r'and this is a\nraw string'
print string
#This is a
#normal string
print rawString
#and this is a\nraw string
import re
match = re.match(r'dog', 'dog cat dog')
print match.group(0)
#dog
match = re.match(r'cat', 'dog cat dog')
print match.group(0)
#NoneType object error
match = re.search(r'cat', 'dog cat dog')
print match.group(0)
#cat
re.findall(r'dog', 'dog cat dog')
#['dog', 'dog']
re.findall(r'cat', 'dog cat dog')
#['cat']
import re
match = re.match(r'dog', 'dog cat dog')
print match.group(0)
#dog
print match.start()
#0
print match.end()
#3
import re
regex = r"([0-9]{1,3}\.){3}[0-9]{1,3}"
IP = raw_input ("Please, enter your IP address: ")
if re.match(regex, IP):
match = re.search(regex, IP)
print match.group(0)
else:
print "Invalid IP address!"
import re
# Lets use a regular expression to match a date string.
regex = r"(\w+) (\d+)"
if re.search(regex, "June 24"):
match = re.search(regex, "June 24")
# This will print [0, 7), since it matches at the beginning and end of the string
print "Match at index %s, %s" % (match.start(), match.end())
# So this will print "June 24"
print "Full match: %s" % (match.group(0))
# So this will print "June"
print "Month: %s" % (match.group(1))
# So this will print "24"
print "Day: %s" % (match.group(2))
else:
# If re.search() does not match, then None is returned
print "The regex pattern does not match. :("
Write a program that inputs an email ID from a user and checks if it is a valid one using regular expressions
Also, extract the domain name of each matched string
Mike Cohn's test automation pyramid
So, where does Python fit in?
help()
dir()
hasattr()
id()
type()
repr()
callable()
issubclass()
isinstance()
__doc__
__name__
>>> help(len)
Help on built-in function len in module __builtin__:
len(...)
len(object) -> integer
Return the number of items of a sequence or collection.
>>> dir()
>>> x = 10
>>> id(x)
>>> callable(x)
False
>>> callable(len)
True
>>>
import random
def lottery():
# returns 6 numbers between 1 and 40
for i in range(6):
yield random.randint(1, 40)
lottery_list = lottery()
for random_number in lottery_list:
print "And the next number is... %d!" % random_number
goweb/
├── bin
├── docs
├── goweb
│ └── __init__.py
├── templates
└── tests
└── __init__.py
import web
urls = (
'/', 'index'
)
app = web.application(urls, globals())
class index:
def GET(self):
greeting = "Hello World"
return greeting
if __name__ == "__main__":
app.run()
[abhiram@localhost goweb]$ python bin/app.py
http://0.0.0.0:8080/
127.0.0.1:58504 - - [08/Jul/2016 20:25:49] "HTTP/1.1 GET /" - 200 OK
127.0.0.1:58504 - - [08/Jul/2016 20:25:49] "HTTP/1.1 GET /favicon.ico" - 404 Not Found
$def with (greeting)
<html>
<head>
<title>Python at Prakat</title>
</head>
<body>
$if greeting:
I just wanted to say <em style="color: green; font-size: 2em;">$greeting</em>.
$else:
<em>Hello</em>, world!
</body>
</html>
import web
urls = (
'/', 'index'
)
app = web.application(urls, globals())
render = web.template.render('templates/')
class index:
def GET(self):
greeting = "Hello World"
return render.index(greeting= greeting)
if __name__ == "__main__":
app.run()
>>> python guess_number.py
Hello! What is your name?
Abhiram
Well, Abhiram, I am thinking of a number between 1 and 20.
Take a guess.
10
Your guess is too low.
Take a guess.
19
Your guess is too high.
Take a guess.
18
Good job, Abhiram! You guessed my number in 3 guesses!
Write a program able to play the "Guess the number"-game, where the number to be guessed is randomly chosen between 1 and 20. This is how it should work when run in a terminal:
The International Civil Aviation Organization (ICAO) alphabet assigns code words to the letters of the English alphabet acrophonically (Alfa for A, Bravo for B, etc.) so that critical combinations of letters (and numbers) can be pronounced and understood by those who transmit and receive voice messages by radio or telephone regardless of their native language, especially when the safety of navigation or persons is essential. Here is a Python dictionary covering one version of the ICAO alphabet:
d = {'a':'alfa', 'b':'bravo', 'c':'charlie', 'd':'delta', 'e':'echo', 'f':'foxtrot',
'g':'golf', 'h':'hotel', 'i':'india', 'j':'juliett', 'k':'kilo', 'l':'lima',
'm':'mike', 'n':'november', 'o':'oscar', 'p':'papa', 'q':'quebec', 'r':'romeo',
's':'sierra', 't':'tango', 'u':'uniform', 'v':'victor', 'w':'whiskey',
'x':'x-ray', 'y':'yankee', 'z':'zulu'}
Your task in this exercise is to write a procedure speak_ICAO() able to translate any text (i.e. any string) into spoken ICAO words. You need to import at least two libraries: os and time. On Linux, you have access to the system TTS (Text-To-Speech) as follows: os.system('say ' + msg), where msg is the string to be spoken. (pyttsx)(Under Windows and Mac, something similar might exist.) Apart from the text to be spoken, your procedure also needs to accept two additional parameters: a float indicating the length of the pause between each spoken ICAO word, and a float indicating the length of the pause between each word spoken.
Questions?