Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Â
Python tutorial
1. Python Basics
- python is a dynamic, interpreted, object
oriented programming language
- source code does not declare the types
of variables, or parameters or methods
Static: Dynamic:
static int a_number; a_number = 42
a_number = 42;
2. Python Basics
- readable, flexible code
- lose the compile-time type checking in
the source code; higher productivity
- code is checked at runtime
3. Python Interpreter
- good for learning the language
- good for experimenting with the library
- helpful functions: dir(), help()
7. Python If Statement
- python does not use { } to enclose blocks of code for
if/loops/function etc.
- uses the colon “:” and indentation/whitespace to
group statements
- '==' is overloaded to work correctly with strings
if speed > 80:
print 'License and registration please'
if mood == 'terrible' or speed >= 100:
print 'You have the right to remain silent'
elif mood == 'bad' or speed >=90:
print “I'm going to have to give you a ticket”
else:
print “Let's keep it under 80, ok?”
8. Python For Statement
for x in range(5):
print x
for x in xrange(10):
if x % 2 == 0:
continue
print x
primes = [2, 3, 5, 7]
for prime in primes:
print prime
9. Python For Statement
for x in range(2, n):
if n % x == 0:
print n, 'equals', x, '*', n/x
break
else:
print n, 'is a prime number'
10. Exercises:
1. Write a program that asks two people for their names;
stores the names in variables; says hello to both of them.
Use "raw_input". Don't use "+" for string concatenation.
2. Write a program that asks users for their favorite color.
Create the following output (assuming "red" is the chosen
color).
red red red red red red red red red red
red red
red red
red red red red red red red red red red
3 .print all multiples of 13 that are smaller than 100.
13. Exercises
1. Create a list that contains the names of 5 students.
Create a for loop that asks the user for every name whether
they would like to keep the name or delete it. Delete the
names which the user no longer wants
2. Given a list of strings, return the count of the number of
strings where the string length is 2 or more and the first
and last chars of the string are the same.
3 . Given a list of strings, return a list with the strings
in sorted order, except group all the strings that begin with
'x' first.
eg. ['mix', 'xyz', 'apple', 'xanadu', 'aardvark'] >>>
['xanadu', 'xyz', 'aardvark', 'apple', 'mix']
14. Python Dictionaries
- also known as associative arrays or
hash tables
- dictionaries consist of pairs of keys and
their corresponding values.
- strings, numbers, and tuples work as
keys, and any type can be a value