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.
Related
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)
So I made a program for hangman that accesses an input file but it is having trouble accessing it once I type it in.
This is the function that is calling the file
def getWord(filename):
print("Loading from file...")
inputFile = open(filename, 'r')
wordlist = inputFile.read().splitlines()
print(len(wordlist) + " lines loaded.")
return wordlist
filename = input("What file will the words come from? ")
wordlist = getWord(filename)
theWordLine = random.choice(wordlist)
game(theWordLine)
And this is the file itself
person,Roger
place,Home
phrase,A Piece Of Cake
The error it is giving me is this
File "hangman.py' , line 77, in <module>
wordlist = getWord(filename)
File "hangman.py' , line 10, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Can anyone help me out?
The error states: TypeError: unsupported operand type(s) for +: 'int' and 'str'. That means that you cannot use + with something of type int and something of type str. the len function returns an int. Thus you need to cast it into a str before you being able to concatenate it with another str
It should be print(str(len(wordlist)) + " lines loaded.") instead of print(len(wordlist) + " lines loaded.")
You may also want to use string formatting as a comment mentions. If you are using python 3.6 or higher, you can try f-strings: f'{len(wordlist)} lines loaded}'.
It has nothing to do with reading the file. Read the error: an integer and string cannot be added.
Why are you getting this error? Because len() returns an integer, not a string. You can cast len()'s return to a string, or you can just use an f-string:
f'{len(wordlist)} lines loaded}'
Use print(len(wordlist), " lines loaded.") instead of print(len(wordlist) + " lines loaded.")
print(len(wordlist) + " lines loaded.") is causing your issue as it is trying to apply the + operand to variables of different datatypes.
You could use print("{} lines loaded".format(len(wordlist))) to avoid this.
I am looping through a pandas dataframe and trying to append the result on a conditional statement. However, my code seems to be posing a problem stopping me from append what I want although it prints fine but displays the error in the end. here is my code below:
counta=[]
for line in ipcm_perf['Alarms']:
if '/' in line:
print (line)
the error I get is the following :
2 for line in ipcm_perf['Alarms']:
----> 3 if ('/') in line:
4 print (line)
5
TypeError: argument of type 'float' is not iterable
I really do not know why Python is flagging that line. where's the float? Everything is being printed but with error at the bottom. It is stopping from appending.
your problem is that you are trying to check if there is a string (/) in a floating number (line), and Python does not like that.
That's because when you write "/" in some_string Python iterates through each char of some_string, but he can iterate through a floating number.
you can double check this by simply running:
if '/' in 3.14:
print("something")
output:
TypeError: argument of type 'float' is not iterable
I suppose that you're searching for a / because you've seen that somewhere in the column. If that's the case, it probably is in a string, and if that's the case, a quick&dirty way to clean your data can be:
if type(line) == str:
if "/" in line:
print(line)
else:
print("I am not a string")
and with line = 3.14, it returns:
I am not a string
and with line = "4/2", it returns:
I am a string
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.
I am stuck with these 2 errors in Python 3.3.2:
import os
path="D:\\Data\\MDF Testing\\MDF 4 -Bangalore\\Bangalore Testing"
os.chdir(path)
for file in os.listdir("."):
if file.endswith(".doc"):
print('FileName is ', file)
def testcasenames(file):
nlines = 0
lookup="Test procedures"
procnames=[]
temp=[]
'''Open a doc file and try to get the names of the various test procedures:'''
f = open(file, 'r')
for line in f:
val=int(nlines)+1
if (lookup in line):
val1=int(nlines)
elif(line(int(val))!=" ") and line(int(val1))==lookup):
temp=line.split('.')
procnames.append(temp[1])
else:
continue
return procnames
filename="MDF_Bng_Test.doc"
testcasenames(filename)
Traceback (most recent call last):
File "D:/Data/Python files/MS_Word_Python.py", line 34, in <module>
testcasenames(filename)
File "D:/Data/Python files/MS_Word_Python.py", line 25, in testcasenames
elif(line(val)!=" " and line(val1)==lookup):
TypeError: 'str' object is not callable
The idea is to only get the test procedure names after I get the Section "Test procedures" while looping in the Test document file (MDF_Bng_Test.doc) and after that I copy all the test procedure names (T_Proc_2.1,S_Proc_2.2...)coming under it.
Ex:
1.1.1 Test objectives
1.Obj 1.1
2.Obj 1.2
3.Obj 1.3
4.Obj 1.4
**2.1.1 Test procedures
1.T_Proc_2.1
2.S_Proc_2.2
3.M_Proc_2.3
4.N_Proc_2.4**
3.1.1 Test References
1.Refer_3.1
2.Refer_3.2
3.Refer_3.3
when you use () with line, it thinks that line is a function which actually is not. What you actually need to use is [] notation
line[int(val)]!=" " and line[int(val1)]==lookup
The problem is in this line:
elif(line(int(val))!=" ") and line(int(val1))==lookup):
If you are trying to index the string, Python uses square brackets notation ([]) to accomplish it, it would be like this:
elif(line[int(val)]!=" ") and line[int(val1)]==lookup):
Another suggestion, parenthesis wrapping if..else statements in Python are optional and normally the code looks better without them:
elif line[int(val)]!=" " and line[int(val1)]==lookup:
Hope this helps!