ksksblg

今は英文実践のチラ裏

Making simple calculation program in Python

while True: 
    # -- Get user input and make list --
    data = input("Asset(JPY),Amount of Trade,Loss-cut percentage/Exit(E)>>")
    if data == "E" or data == "e":
        break
    
    list = data.split(",")

    # -- Check validity of the user input --
    if len(list) != 3:
        print("Arguments error. Please check the total number of arguments.")
        continue   
    if all(float(s) for s in list) == False:
        print("Arguments error. Please input only numbers.")
        continue
    
    list = [float(x) for x in list]
    
    # -- Compute a result -- 
    #list[0] is totalAsset
    #list[1] is amount of trading
    #list[2] is loss cut percentage  
    losscut_jpy = list[0]*(list[2]*0.01)
    losscut_pips = float(losscut_jpy / list[1])*100

    print("Loss-cut is {0}pips or less.".format(losscut_pips))

I made very little Python program. This code outputs losscut point from an asset, the amount of trade, a percentage of loss-cut.

I thought three things, that is...

  • How to make a list from a data separated with "," a comma-separated data?
  • How to get length(size) of a list?
  • How to check if all conditions are True?
  • How to convert all item's type of a list?

How to make a list from a comma-separated data

string.split() is used to separate with any character. string.split() returns a list.

How to get length(size) of a list?

You can use len() for getting a length of a list. The format is len(list)

How to check if all conditions are True?

all() returns True if all elements of am iterator is True. In this case,
I use float() as an argument. float() will return if the function fail the process.
So I write

if all(float(s) for s in list) == False:

"all(float(s) for s in list" returns True if all the items of the list is a number.

How to convert all item's type of a list?

"List Comprehensions" can be used for this purpose.

[statement for x in list-object]