2017年5月22日 星期一

Python quick lookup - basic

#operator

# not equal
!=

# shift

<< >>

# xor

^

#modules

random

random.random()

# they are equal
random.randint(1,5)
random.choice( [1,2,3,4,5] )

math

math.ceil()

#loop

# foreach
days = ['Monday', 'Tuesday']
for day in days:

# range from 0 to 9
for i in range(10):

# range with step as 2
for i in range(0, 10, 2):

# foreach in dictionary
menu_prices = { '1': 0.5, '2': 0.3, '3': 0.7 }
for key, value in menu_prices.items():
    print( key, ': $', value )

# while
while <condition not matched>:
while (True):
   if <condition>:
      continue
   if <condition>:
      break

#list

# getting length of list
days = ['Monday', 'Tuesday']
length_of_list_days = len( days )

# removing item from list
days.remove('Monday')
del days[0]

# try getting item from dict, return None if not exist
days.get(key) 

#print 

# automatic separated with space
print( item1, item2 )

# specify separator
print( item1, item2, sep='' )

# print with format
print( format(value, '.2f') )


#string

# reverse a string
'hello world'[::-1] # [begin:end:step]
reversed('hello world')

沒有留言:

張貼留言