For loop error on a very simple program [Python] - python

Whenever I try to run the follwing code:
message = raw_input("Write a word: ")
for i in range (message(len)):
print i
I get this error:
Traceback (most recent call last):
File "C:\Python27\testing.py", line 3, in <module>
for i in range (message(len)):
TypeError: 'str' object is not callable
I have no idea why this is happening.

You need to apply len to the string, not the other way round.
This will work:
for i in range (len(message)):
print i
Note that this will print integers. You might actually want to do print message[i] to print each character in the string?

You're looking for range(len(message)), not range(message(len)). Your program will then print 0, 1, 2, etc. for each character in the string.

Related

How to convert str to a float?

I imported a list full of floats as strings, and i tried to convert them to floats, but this error kept popping up
Traceback (most recent call last):
File "c:\Users\peter\Documents\coding\projects\LineFitting.py", line 12, in <module>
StockPriceFile = float(value.strip(''))
ValueError: could not convert string to float:
this is what i did to try and convert the list:
#1
for value in range(0, len(StockPriceFile)):
StockPriceFile[value] = float(StockPriceFile[value])
#2
for value in StockPriceFile:
value = float(value)
#3
StockPriceFile[0] = StockPriceFile[0].strip('[]')
for value in StockPriceFile:
StockPriceFile = float(value.strip(''))
(Sample Of Data)
['[36800.]', '36816.666666666664', '36816.666666666664', '36833.333333333336', '36866.666666666664']
where its being written:
Data_AvgFile.write(str(Average) + ',')
What does this mean? and how can i fix it? it works fine when i do it one by one.
(also tell me if you need more data, i dont know if this is sufficient)
for value in StockPriceFile:
stock_price = float(value.strip('[]'))
print(stock_price)
strip() will remove the [] characters around the value.
DEMO
As long you have the brackets "[ ]" in you'r string you cant convert it to a a number as that would make it invalid so do letters and most symbols the dot (.) is an exception for float.
>>> print(float('[36800.]'))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: '[36800.]'
>>> print(float('36800.'))
36800.0
l = ['[36800.]', '36816.666666666664', '36816.666666666664', '36833.333333333336', '36866.666666666664']
[float(f.strip('[]')) for f in l]
Output:
[36800.0,
36816.666666666664,
36816.666666666664,
36833.333333333336,
36866.666666666664]

How can len() function count the number of letters in a word entered by the user?

As the user inputs a different word the length of words will change so I am trying to store the .len() answer in a variable which is not working.
This is what I tried:
letter=input("TYPE A WORD--> ")
letter.upper()
NO=letter.len()
print (NO)
Though there is an error message saying:
Traceback (most recent call last):
File "main.py", line 3, in \<module\>
NO=letter.len()
AttributeError: 'str' object has no attribute 'len'
There is no string.len() function in python.
If you want to find the length of a string, you should use len(string) function.
For example
NO = len(letter)
give letter as argument to len()
NO = len(letter)
Updated code for you
letter=input("TYPE A WORD--> ")
letter=letter.upper()
NO=len(letter)
print (NO)

Tuple index out of range error with .format(list)

I have a strange problem I don't get. I have a format string with a lot of fields. I want to supply the content for the fields using a list. The following simple demo below shows the issue:
>>> formatstr = "Hello {}, you are my {} fried since {}"
>>> list = ["John", "best", 2020]
>>> print formatstr.format(list)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: tuple index out of range
>>>
The format string has 3 fields and the list has also 3 elements.
So I don't understand the error message.
Even when I try to address the indexes within the format string:
>>>
>>> formatstr = "Hello {0:}, you are my {1:} fried since {2:}"
>>>
>>> print formatstr.format(list)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: tuple index out of range
>>>
Can you please help me? I think I blocked somewhere in my thinking.
Thanks.

Placing variable in single quotes

I am receiving an integer error when reading from my CSV sheet. Its giving me problems reading the last column. I know theres characters in the last column but how do I define digit as a character. The API function psspy.two_winding_chg_4 requires an input using single quotes ' ' as shown below in that function(3rd element of the array)
Traceback (most recent call last):
File "C:\Users\RoszkowskiM\Desktop\win4.py", line 133, in <module>
psspy.two_winding_chng_4(from_,to,'%s'%digit,[_i,_i,_i,_i,_i,_i,_i,_i,_i,_i,_i,_i,_i,_i,_i],[_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f, max_value, min_value,_f,_f,_f],[])
File ".\psspy.py", line 25578, in two_winding_chng_4
TypeError: an integer is required
ValueError: invalid literal for int() with base 10: 'T1'
The code:
for row in data:
data_location, year_link, from_, to, min_value,max_value,name2,tla_2,digit = row[5:14]
output = 'From Bus #: {}\tTo Bus #: {}\tVMAX: {} pu\tVMIN: {} pu\t'
if year_link == year and data_location == location and tla_2==location:
from_=int(from_)
to=int(to)
min_value=float(min_value)
max_value=float(max_value)
digit=int(digit)
print(output.format(from_, to, max_value, min_value))
_i=psspy.getdefaultint()
_f=psspy.getdefaultreal()
psspy.two_winding_chng_4(from_,to,'%s'%digit,[_i,_i,_i,_i,_i,_i,_i,_i,_i,_i,_i,_i,_i,_i,_i],[_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f, max_value, min_value,_f,_f,_f],[])
The easiest and probable most usable option would be to used your own function to filter on only digits. Example:
def return_digits(string):
return int(''.join([x for x in string if x.isdigit()]))

Splitted input printing in Python [Python 3.4]

I am making a simple command line app, where one of the commands print the text you input after the word 'print'. The commands work fine and I'm using raw input. The commands, however, use a splitted input and extracting text from it is like using a table (string[num]). However, when execute the code, I get an error saying:
>>>
:: print hello world
Traceback (most recent call last):
File "C:/Python34/Commands.py", line 10, in <module>
for i in range(1, len(splitcmd-1)):
TypeError: unsupported operand type(s) for -: 'list' and 'int'
>>>
The code I used is:
cmdlst = ['open', 'print', 'calculate']
files = ['Hello World', 'Hello Jeremy', 'Hello Dog']
while True:
cmd = input(':: ')
splitcmd = cmd.split()
if splitcmd[0] == 'open':
print(files[int(splitcmd[1])])
if splitcmd[0] == 'print':
for i in range(1, len(splitcmd-1)):
print(splitcmd[i], end = '')
print('', end='\n')
I'm aiming to avoid using quotation marks in the command (''/""). Thanks for your help!
Change
for i in range(1, len(splitcmd-1)): to
for i in range(1, len(splitcmd)-1):
Improper parenthesis.
You have the following error
for i in range(1, len(splitcmd-1)):
You should decrease 1 from the length not from the string:
for i in range(1, len(splitcmd)-1):
I have to say that you codes aren't pythonic and when you use
:: open some_string_name
that will cause another problem.......if your some_string_name isn't a number. int() will take string-ed number, but not string.

Categories

Resources