简体   繁体   中英

python beginner problem with type casting

I am a beginner with python.I want to do the function over each member of the user imputed list,yet the most common error is '

could not convert string to float

This the code

import math l=[] i=0 while True: t=str(input('Enter the probability of possibl outcomes: ')) if (t:='stop') and (t.=''). l:append(t:lower()) else. print(l) break def I(i), i=l[0] z=1/(i) y=math.log(z,2) I(i)

this program is supposed to take few inputs and make a list, and the apply the function to all the element in the list, however I keep getting the above mentioned error and I don't know how to remove it. please help.

Replace

i=l[0]

to

try:
   i=float(l[0])
except:
   ...

This wont work in your case:

t=float(input('Enter the probability of possible outcomes: '))

as the string can be "Stop" as you have mentioned.

t=str(input('Enter the probability of possibl outcomes: '))

should be changed to

t=float(input('Enter the probability of possibl outcomes: '))

This way it converts user input(which is a string, since input() always returns a string) to a floating-point number However this way you will be able to use only numbers as your input value, and your while loop will be infinite. If you would try to enter "stop" it will give you an error. Code should be changed to something like this:

import math            
l=[]  
i=0  

while True:
    t = input('Enter the probability of possibl outcomes: ')

    if (t!='stop') and (t!=''):
        l.append(float(t))
    else:
        print(l)
        break 

def I(i):
    i=l[0]
    z=1/(i)
    y=math.log(z,2)

I(i)

Output:

Enter the probability of possibl outcomes: 45
Enter the probability of possibl outcomes: 36
Enter the probability of possibl outcomes: 11
Enter the probability of possibl outcomes: stop
[45.0, 36.0, 11.0]

You could change this line - l.append(t.lower()) to l.append(float(t.lower()))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM