public class HelloWorld { public static void main (String[] args) { System.out.println("Hello, world!"); } }
print("Hello, world!")
>>> print("Hello, world!") Hello, world! >>> 31234 * (762 + 181) 29453662Note that in Python 2 the print statement would be:
>>> print "Hello, world!"
def check_tense(sentence, tns): if not tns: print('Warning: no tense associated with', sentence, '!') return False else: print(sentence, 'has tense', tns) return sentence
>>> 'Expecting the world to treat you fairly because you are good ' + \ 'is like expecting the bull not to charge because you are a vegetarian.' 'Expecting the world to treat you fairly because you are good is like expecting the bull not to charge because you are a vegetarian.'
>>> input('A number? '); input('Try again? ') A number? 11 '11' Try again? no 'no'
>>> x = 3
>>> x = "three"
>>> int(5.0) 5 >>> float(5) 5.0 >>> str(5) '5' >>> int('5') 5
str
), tuples (tuple
),
and lists(list
)
>>> goodbye_jp = 'さようなら' >>> goodbye_jp[1] 'よ' >>> goodbye_jp[-2] 'な' >>> goodbye_ls = ['до свидания', 'adiós', 'さようなら'] >>> goodbye_ls[0] 'до свидания' >>> goodbye_ls[0][3] 'с' >>> hello_tup = 'أهلاً', '你好', 'नमस्ते' >>> type(hello_tup[2]) <class 'str'> >>> hello_tup[0][0] 'أ' >>> tuple(goodbye_ls[-1]) ('さ', 'よ', 'う', 'な', 'ら')
>>> goodbye_ls[1] = 'hasta luego' >>> goodbye_ls ['до свидания', 'hasta luego', 'さようなら'] >>> goodbye_ls[1][0] = 'H' Traceback (most recent call last): File "<pyshell#8>", line 1, in <module> goodbye_ls[1][0] = 'H' TypeError: 'str' object does not support item assignment
==
tests whether two objects "look" the same; is
tests
whether they are the same object.)
>>> x = [] >>> y = [] >>> x == y True >>> x is y False
[index1:index2]
; this accesses the elements in the sequence starting with index1 and up to, but not including index2.
The number before the colon defaults to 0, and the number after the colon defaults to the length of the sequence, so you can leave either of these out.
>>> l = 'linguistics' >>> l[1:5] 'ingu' >>> l[5:-1] 'istic' >>> l[5:] 'istics' >>> l[:5] 'lingu'
>>> l[::2] 'lnusis' >>> l[1::2] 'igitc' >>> l[-1::-1] 'scitsiugnil'
>>> l = ['computational', 'linguistics'] >>> l[:] ['computational', 'linguistics'] >>> l is l[:] False
append
method.
To concatenate another list onto a list, use the extend
method.
Both are mutating functions that return nothing.
>>> l.append('is') >>> l ['computational', 'linguistics', 'is'] >>> l.extend(['a', 'lot', 'of', 'fun']) >>> l ['computational', 'linguistics', 'is', 'a', 'lot', 'of', 'fun']
>>> l = 'linguistics is a lot of fun' >>> l.split() ['linguistics', 'is', 'a', 'lot', 'of', 'fun'] >>> l.replace('is', 'was') 'linguwastics was a lot of fun' >>> ' '.join(['linguistics', 'is', 'a', 'lot', 'of', 'fun']) 'linguistics is a lot of fun'
>>> verb_feats = {'tns': 'past', 'asp': 'prog', 'pers': 3, 'num': 'plur'} >>> verb_feats['asp'] 'prog' >>> verb_feats['gen'] = 'fem'
in
operator tests whether an object is a member of a collection
(in the case of dictionaries, one of the keys)
>>> 'ó' in 'adiós' True >>> 'di' in 'adiós' True >>> 'di' in ['adiós'] False >>> 'asp' in verb_feats True
len
returns the length of a collection.def find_sent(word, sentences): """Returns the first sentence in sentences containing word. word: str sentences: list of lists of strs return: list of strs """ for sentence in sentences: if word in sentence: return sentence return []
>>> help(find_sent) Help on function find_sent in module __main__: find_sent(word, sentences) Returns the first sentence in sentences containing word. word: str sentences: list of lists of strs return: list of strs
=
default_value after the parameter name.
def read_data(filename="data"): ...
def conjugate(verb, tense="present", person="3", number="singular"): ...
>>> conjugate('pedir') >>> conjugate('pedir', 'past') >>> conjugate('pedir', 'past', '1', 'plural') >>> conjugate('pedir', person='1') >>> conjugate('pedir', number='singular', person='1', tense='past')
EN2ES_ADJ = {'happy': {'s': {'m': 'contento', 'f': 'contenta'}, 'p': {'m': 'contentos', 'f': 'contentas'}}, 'sad': {'s': 'triste', 'p': 'tristes'}, 'poor': {'s': 'pobre', 'p': 'pobres'}, 'rich': {'s': {'m': 'rico', 'f': 'rica'}, 'p': {'m': 'ricos', 'f': 'ricas'}}}
>>> en2es_adj('poor') 'pobre' >>> en2es_adj('rich') 'rico' >>> en2es_adj('rich', number='p') 'ricos' >>> en2es_adj('rich', number='p', gender='f') 'ricas' >>> en2es_adj('good') There is no entry for good
while
loops
while condition: statements
for
loops
for var in seq: statements
>>> nums = [('one', 'uno', 'peteĩ'), ('two', 'dos', 'mokõi'), ('three', 'tres', 'mbohapy')] >>> for en, es, gn in nums: print(en, '=', es, '/', gn) one = uno / peteĩ two = dos / mokõi three = tres / mbohapy
import
statement.Import
statements take two forms.
>>> import math >>> math.exp(5.0) 148.4131591025766 >>> from math import * >>> exp(5.0) 148.4131591025766
class Sentence: """Simple representation of a sentence.""" def __init__(self, words, verb='', sbj=''): """Assign basic attributes. words: list of strings verb: string sbj: string """ self.words = words self.verb = verb self.sbj = sbj def __repr__(self): return "<" + ' '.join(self.words) + '>' def search_verb(self, lexicon): """Look for the verb in a lexicon (a dictionary).""" return lexicon.get(self.verb) def n_grams(self, n): """List of n-grams within the sentence.""" words = [''] + self.words + [''] return [words[i:i+n] for i in range(len(words)-n+1)] # result = [] # for i in range(len(words)-n+1): # result.append(words[i:i+n]) # return result class TransitiveSentence(Sentence): """Sentence with an object.""" def __init__(self, words, verb='', sbj='', obj=''): """Assign object as well as other attributes.""" Sentence.__init__(self, words, verb=verb, sbj=sbj) self.obj = obj
open
, which takes a string representing the path to the file, and
an argument representing what to do with the file: 'r'
for read (the default),
'w'
for write, 'a'
for append.
encoding='utf8'
.
for
loop.
>>> file1 = open('am2.txt', encoding='utf8') >>> for line in file1: print(line.strip()) ምአራፍ 6 ነጻነት በዛብህ ወላጆቹን ከድቶ ማንኩሳን አንደለቀቀ ዋሸራ ወደምትባል አገር ሄዶ ቅኔ ቤት ገባ። በዋሸራም አንድ ዓመት እንደቆየ ቅኔ ተቀኝቶ ዝማሬ መዋሲት ለማካሄድ ወደ ዙር አምባ ሄደ። ዙር አምባ ሁለት ዓመት ያክል ቆይቶ ዝማሬ መዋሲትና ጽህፈት አወቀ። በመጨረሻ ደብረወርቅ አምትባል አገር አዲስ የመጽሃፍ መምህር ከጎንደር መምጣታችውን ስለስማ፣ ወደዚያ ሄዶ መጽሓፍ ለመቀጸል ወሰነ። >>> file.close()
>>> file2 = open('es1.txt', 'w', encoding='utf8') >>> print("¿Cómo estás?", file=file2) >>> file2.write("Muy bien. ¿Y tú?\n") 17 >>> file2.close() >>> file3 = open('es1.txt', encoding='utf8') >>> file3.readline() '¿Cómo estás?\n' >>> file3.close() >>> file4 = open('es1.txt', encoding='utf8') >>> file4.read() '¿Cómo estás?\nMuy bien. ¿Y tú?\n'
if
statement with a condition that checks whether the current name space is __main__
:
if __name__ == '__main__': <stuff to do>
python3.2
.)
#! /usr/bin/env pythonand we need to make the module file executable. In Unix we do this as follows:
chmod a+x <module name>
sys.argv
; the program (module) name is the first element of this list.
Note that the sys
library must be imported.
#! /usr/bin/env python3.2 import sys, math if __name__ == '__main__': angle = int(input('Type in an angle: ')) if len(sys.argv) > 1 and sys.argv[1] == 'degrees': angle = math.radians(angle) print('Cosine: ', math.cos(angle))
% ./cos.py Type in an angle: 45 Cosine: 0.5253219888177297