A concise tutorial to a concise language
YDP
21st August 2016
print "Hello World!"
hello.py
one = 1
two = 2
three = one + two
hello = "hello"
world = "world"
helloworld = hello + world
Mixing operators between numbers and strings is not supported
mylist = []
mylist.append(1)
mylist.append("hello")
print(mylist[1])
colors = ['red', 'brown', 'blue', 'green', 'white']
colors[1]
#brown
colors[2:4]
#['blue', 'green']
number = 1 + 2 * 10 / 5.0
remainder = 11 % 5
squared = 5 ** 2
cubed = 5 ** 3
#string operations
helloworld = "hello" + "world"
lotsofhellos = "hello" * 10
#list operations
even_numbers = [2,4,6,8]
odd_numbers = [1,3,5,7]
all_numbers = odd_numbers + even_numbers
print [1,2,3] * 3
The Meal
You've finished eating at a restaurant, and received this bill:
Cost of meal: $44.50
Restaurant tax: 6.75%
Tip: 15%
You'll apply the tip to the overall cost of the meal (including tax). Display the tip calculated.
number = 1 + 2 * 10 / 5.0
remainder = 11 % 5
squared = 5 ** 2
cubed = 5 ** 3
#string operations
helloworld = "hello" + "world"
lotsofhellos = "hello" * 10
#list operations
even_numbers = [2,4,6,8]
odd_numbers = [1,3,5,7]
all_numbers = odd_numbers + even_numbers
print [1,2,3] * 3
name = "John"
age = 23
print "%s is %d years old." % (name, age)
# John is 23 years old
# This prints out: A list: [1, 2, 3]
mylist = [1,2,3]
print "A list: %s" % mylist
s = "Hey there! what should this string be?"
print "Length of s = %d" % len(s)
print "The first occurrence of the letter a = %d" % s.index("a")
print "a occurs %d times" % s.count("a")
# Slicing the string into bits
print "The first five characters are '%s'" % s[:5] # Start to 5
print "The next five characters are '%s'" % s[5:10] # 5 to 10
print "The twelfth character is '%s'" % s[12] # Just number 12
print "The characters with odd index are '%s' " %s[1::2] #(0-based indexing)
print "The last five characters are '%s'" % s[-5:] # 5th-from-last to end
# Convert everything to uppercase
print "String in uppercase: %s" % s.upper()
# Convert everything to lowercase
print "String in lowercase: %s" % s.lower()
# Check how a string starts
if s.startswith("Str"):
print "String starts with 'Str'. Good!"
# Check how a string ends
if s.endswith("ome!"):
print "String ends with 'ome!'. Good!"
# Split the string into three separate strings,
# each containing only a word
print "Split the words of the string: %s" % s.split(" ")
You will need to write a format string which prints out the data using the following syntax:
Hello John Doe! Your current balance is 53.44$.
name = "Ram"
if name in ["Ram", "Bharat"]:
print "Your name is either Ram or Bharat."
people = 30
cars = 40
if cars > people:
print "We should take the cars."
elif cars < people:
print "We should not take the cars."
else:
print "We can't decide."
print not False # Prints out True
primes = [2, 3, 5, 7]
for prime in primes:
print prime #prime acts as iterator
# we can also build lists, first start with an empty one
elements = []
for i in range(0, 6):
elements.append(i)
for x in range(3, 6):
print x
count = 0
while count < 5:
print count
count += 1
# Prints out only odd numbers - 1,3,5,7,9
for x in xrange(10):
# Check if x is even
if x % 2 == 0:
continue
print x
#Two types - input() and raw_input()
username = raw_input('What is your name? ')
#only for strings
myage = input("What is your age? ")
#all types except string
In this exercise, you have to write a Pig Latin translator.
Pig Latin is a language game, where you move the first letter of the word to the end and add "ay." If a word begins with a vowel, just add “way” in the end. So "Python" becomes "ythonpay." “object” becomes “objectway”, and so on.
To write a Pig Latin translator in Python, here are the steps we'll need to take:
Ask the user to input a word in English.
Convert the word from English to Pig Latin.
def my_function():
print "Hello there!"
def sum_two_numbers(a, b):
return a + b
#Prints "Hello there!"
my_function()
x=sum_two_numbers(10,15)
#x now holds the sum of 10 and 15
print x
Twin prime numbers are a pair of prime numbers that have a difference of 2 between them. For example, (3,5), (5,7), (11,13), (29,31), etc.
Given a number n, display the first n pairs of twin primes
To do the above,
Create a function prime(n) that checks if a number is prime or not
Find a prime number and check if a twin prime exists for it
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:
f = open("test.txt", "r")
#opens file with name of "test.txt" for read-only
print(f.read(10))
#Reads 10 characters and prints them or the entire line if number of characters is not specified
print(f.readLine())
#Reads an entire line and prints it
my_list = [i**2 for i in range(1,11)]
# Generates a list of squares of the numbers 1 - 10
f = open("output.txt", "w")
#opens file with name of "output.txt" in read-write
for item in my_list:
f.write(str(item) + "\n")
f.close()
f = open("output.txt", "a")
#opens file with name of "output.txt" in append mode
f.write("Goodbye!")
#Appends "Goodbye!" to the end of the file
f.close()
phonebook = {
"John" : 938477566,
"Jack" : 938377264,
"Jill" : 947662781
"Jake" : 998833221
}
#Prints all the phone numbers in the dictionary
for name, number in phonebook.iteritems():
print "Phone number of %s is %d" % (name, number)
#Deletes the entries of John and Jake from the phonebook
if "John" not in phonebook:
print "John is not listed in the phonebook."
else:
del phonebook["John"]
phonebook.pop("Jake")
Given a list containing the key-words searched on Google by a user, count the number of occurrences of each key-word and display in the form of an array
For example, given this input -
Key_word_list = [‘cricket’, ‘india’, ‘football’, ‘cricket’, ‘yahoo’, ‘google’, ‘india’, ‘cricket’]
We should get this as the output:
cricket - 3, india - 2, football - 1, yahoo - 1, google -1
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
Questions?
Resources used: