Hylang tutorial

change list value

players = ['charles', 'martina', 'michael', 'florence', 'eli']
plyaers[0] = 'Half' 
(setv players  ["charles", "martina", "michael", "florence", "eli"])
(setv (get players 0) "ducati") # method 1
(setv (.  players [0]) "ducati") # method 2
(.__setitem__  players  0 "ducati") # method 3
(assoc players 0 "ducati") #method 4

slice list

>>> players = ['charles', 'martina', 'michael', 'florence', 'eli']
>>> players[1:3]
['martina', 'michael']
=> (setv players ["charles"  "martina"  "michael"  "florence"  "eli"])
=> (cut players 1 3)
['martina', 'michael']

copy list

>>> players = ['charles', 'martina', 'michael', 'florence', 'eli']
>>> copy_player = players[:]
>>> copy_player
['charles', 'martina', 'michael', 'florence', 'eli']
=> (setv players ["charles"  "martina"  "michael"  "florence"  "eli"])
=> (setv copy_player (list-comp x [x players]))
=> copy_player
['charles', 'martina', 'michael', 'florence', 'eli']

if statement

  cars = ['audi', 'bmw', 'subaru', 'toyota']
  for car in cars:
     if car == 'bmw':
          print(car.upper())
      else:
          print(car.title())
(setv cars ["audi" "bmw" "subaru" "toyota"])
(for [car cars]
    (if (= car "bmw")
        (print (.upper car)) ;;True
        (print (.title car)) ;;False
        ))

dictionary

>>> alien_0 = {'color': 'green', 'points': 5}
>>> alien_0['color']
'green'
>>> alien_0['x'] = 0
>>> alien_0['y'] = 25
>>> alien_0
{'y': 25, 'color': 'green', 'points': 5, 'x': 0}
>>> alien_0['x'] = 13
>>> del alien_0['x']
>>> alien_0
{'y': 25, 'color': 'green', 'points': 5}

=> (setv alien_0 {"color" "green" "points" 5})
=> (get alien_0 "color")
'green'
=> (assoc alien_0 "x" 0)
=> (assoc alien_0 "y" 25)
=> alien_0
{'points': 5, 'y': 25, 'color': 'green', 'x': 0}
=> (assoc alien_0 "x" 13)
=> (del (get alien_0 "x"))
=> alien_0
{'points': 5, 'y': 25, 'color': 'green'}

travel dictionary

>>> alien_0 = {"color": "green" ,"points": 5}
>>> for i in alien_0:
...   print(i,alien_0[i])
...
color green
points 5
(setv alien_0 {"color" "green" "points" 5})
(for [key alien_0]
    (print key (get alien_0 key)))

input

>>> age = int(input("How old are you?"))
How old are you?12
>>> age
12
>>> type(age)
<class 'int'>
=>  (setv age (int (input "How old are you?")))
How old are you?12
=> age
12
=> (type age)
<class 'int'>

while

prompt = "\nPlease enter the name of a city you have visited:"
prompt += "\n(Enter 'quit' when you are finished.) "
while True:
    city = input(prompt)
    if city == 'quit':
        break
    else:
        print("I'd love to go to " + city.title() + "!")
(setv prompt "Please enter the name of a city you have visited:")
(+ prompt "\n(Enter 'quit' when you are finished.) " )
(while True
    (setv city (input prompt))
    (if (= city "quit")
        (break)
        (print "I'd love to go to " (.title city) "!")))

define function

pizza.py
def make_pizza(size,*toppings):
    print("\nMaking a " + str(size) +
        "-inch pizza with the following toppings:")
    for topping in toppings:
        print("- " + topping)
making_pizzas.py
import pizza
pizza.make_pizza(16,'pepperoni')
pizza.make_pizza(12,'mushrooms','green_peppers','extra_cheese')

pizza.hy
(defn make_pizza [size &rest toppings]
    (print "\nMaking a " (str size) 
      "-inch pizza with the following toppings:")
    (for [topping toppings]
        (print topping)))
making_pizzas.hy
(import pizza)
(.make_pizza pizza 16 "pepperoni" "中华街") ;;特意添加了一个中文
(.make_pizza pizza 12 "mushrooms" "green_peppers" "extra_cheese")

define class

class Dog():
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def sit(self):
        print(self.name.title() + " is now sitting.")

    def roll_over(self):
        print(self.name.title() + " rolled over!")


my_dog = Dog('willie',6)        
print("My dog's name is " + my_dog.name.title() + ".")
print("My dog's is " + str(my_dog.age) + " years old.")

(defclass Dog [object]
    (defn --init-- [self name age]
        (setv self.name name)
        (setv self.age age))
    (defn sit [self]
        (print (.title self.name) " is now sitting"))
    (defn roll_over(self)
        (print (.title self.name " rolled over!"))))

(setv my_dog (Dog "willie" 6))
(print "My dog's name is " (.title my_dog.name) ".")
(print "My dog's is " (str my_dog.age) " years old.")

import module

from collection import OrderedDict
fk = OrederedDict()
fk['jen'] = "python"
fk['sarah'] = 'c'
fk['edward'] = 'ruby'
fk['phil'] = 'python'
print(fk)
=> (import [collections [OrderedDict]])
=> (setv fk (OrderedDict))
=> (assoc fk "jen" "python")
=> (assoc fk "sarah" "c")
=> (assoc fk "edward" "ruby")
=> (assoc fk "phil" "python")
=> fk
OrderedDict([('jen', 'python'), ('sarah', 'c'), ('edward', 'ruby'), ('phil', 'python')])

read file

pi_digits.txt

3.1415926535
8979323846
2643383279

file_reader.py
filename = 'pi_digits.txt'

with open(filename) as file_object:
    for line in file_object:
        print(line.rstrip())
file_reader.hy
(setv filename "pi_digits.txt")
(with [file_object (open filename)]
    (for [line file_object]
        (print (.rstrip line))))

try_except_else

alice.txt
Alice is the main character of the story “Alice’s Adventures in Wonderland” and the sequel “Through the Looking Glass and what Alice found there”.

She is a seven-year-old English girl with lots of imagination and is fond of showing off her knowledge. Alice is polite, well raised and interested in others, although she sometimes makes the wrong remarks and upsets the creatures in Wonderland. She is easily put off by abruptness and rudeness of others.

In Through the Looking Glass, she is 6 months older and more sure of her identity.
word_count.py
def count_words(filename):
     """计算一个文件大致包含多少个单词"""
      try:
          with open(filename) as f_obj:
              contents = f_obj.read()
      except FileNotFoundError:
          msg = "Sorry, the file " + filename + " does not exist."
          print(msg)
      else:
          # 计算文件大致包含多少个单词
          words = contents.split()
          num_words = len(words)
          print("The file " + filename + " has about " + str(num_words) +
              " words.")

filename = 'alice.txt'
count_words(filename)
word_count.hy
(defn count_words [filename]
    (try
        (with [f_obj (open filename "rb")]
            (setv contents (.read f_obj)))
        (except [FileNotFoundError]
            (setv msg (+ "Sorry,the file " filename " does not exist"))
            (print msg))
        (else
            (setv words (.split contents))
            (setv num_words (len words))
            (print "The file" filename " has about " (str num_words) " words"))))
(setv filename "alice.txt")
(count_words filename)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 205,386评论 6 479
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,939评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,851评论 0 341
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,953评论 1 278
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,971评论 5 369
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,784评论 1 283
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,126评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,765评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,148评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,744评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,858评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,479评论 4 322
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,080评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,053评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,278评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,245评论 2 352
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,590评论 2 343

推荐阅读更多精彩内容