Basically I have a variable equal to a number and want to find the number in the position represented by the variable. This is what I
numbertocheck =1
loopcriteria = 1
while loopcriteria == 1:
if numbertocheck in ticketnumber:
entryhour.append[numbertocheck] = currenttime.hour
entryminute.append[numbertocheck] = currenttime.minute
print("Thank you. Your ticket number is", numbertocheck)
print("There are now", available_spaces, "spaces available.")
loopcriteria = 2
I get this error (in pyCharm):
Traceback (most recent call last): File
"/Users/user1/Library/Preferences/PyCharmCE2017.3/scratches/scratch_2.py",
line 32, in entryhour.append[numbertocheck] =
currenttime.hour TypeError: 'builtin_function_or_method' object does
not support item assignment
How do I do what I'm trying to do?
Though you haven't provided the complete code, I think you only have problem with using append. You cannot use [] just after an append. To insert into a particular position, you need insert
Putting the relevant lines you need to replace below...
entryhour.insert(numbertocheck,currenttime.hour)
entryminute.insert(numbertocheck,currenttime.minute)
# available_spaces-=1 # guessing you need this too here?
P.S. your loop doesn't seem to make sense, I hope you debug it yourself if it doesn't work the way you want.
Related
I'm trying to open a txt file and get all the words in it, assign it to a list, and filter the list of duplicates. The code in the snippet is what I thought would work, but I'm getting a traceback error and it says list index is out of range. How can I modify my code to avoid that error?
Any help is appreciated.
fname = input("Enter file name: ")
fh = open("romeo.txt")
lst = list()
for line in fh:
nlst = (line.rstrip()).split()
lst = lst + nlst
for i in [*range(len(lst))]:
if lst.count(lst[i]) > 1:
while lst.count(lst[i]) > 1:
print(lst[i])
lst.remove(lst[i])
else:
continue
print(lst)
edit 1:
Okay so I thought the cause of the problem was lst.count(lst[i]) having a value of one or more and the inequality is (>1) so it's saying that it's out of range, but I tried 0 instead of 1, and it still gave me the same error.
vsc snippet
but i'm getting a traceback error and it says list index is out of range
First, whenever you're asking about a traceback, include the actual error message in your question. In this case, that looks like:
Traceback (most recent call last):
File ".../countwords.py", line 9, in <module>
if lst.count(lst[i]) > 1:
~~~^^^
IndexError: list index out of range
There are several issues that get us into this situation. Broadly, you're iterating over the number of words in the document. For each word, you're using lst.count to find occurrences of the word in lst...and then removing duplicates. Whenever you find a duplicate, lst gets shorter, but your outer loop doesn't know this. Eventually, you ask for lst[i] when i is larger than the length of the list and your code explodes.
We can fix this while preserving your current logic by making a couple of changes.
First, let's fix that outer loop; you've written for i in [*range(len(lst)], but that's operationally equivalent to for i in range(lst), which is simpler to read.
Instead of trying to update lst, let's populate a new variable lst_no_dupes; this avoids issues with modifying lst while at the same time trying to iterate over it:
Instead of using lst.count, we can use the in operator to check for the presence of a word in a list.
Those changes get us:
lst_no_dupes = []
for i in range(len(lst)):
if lst[i] not in lst_no_dupes:
lst_no_dupes.append(lst[i])
print(lst_no_dupes)
This works, but it's inefficient, because checking to see if a word is contained in the list is an O(n) operation. As the number of words grows larger, it will take longer and longer to look up items in the list.
There's a much simpler way to produce a list of unique items from a list as long as you don't care about their order: just turn them into a set:
fh = open("romeo.txt")
lst = list()
for line in fh:
nlst = (line.rstrip()).split()
lst = lst + nlst
lst = set(lst)
print(lst)
A set is "an unordered collection of distinct objects"; lookups in a set are O(1) so the time required to check for a duplicate is independent of the number of words.
Ultimately, you could simplify everything down to this:
with open('romeo.txt') as fh:
lst = set(word for line in fh for word in line.split())
print(lst)
Here, we're iterating over lines in the file (for line in fd) and then words in each line (for word in line.split()). This is an example of a generator expression (which is like a list comprehension).
I am analysing an episode of Brooklyn 99 specifically trying to find the line number in a text file where Gina says Scully looks 'like an eggplant' but my code isn't working, any help would be appreciated, I am using jupyter and not getting an error message when running my code.
f = open(r'C:\Users\bubba\Downloads\B99_episode_.txt', 'r')
print(f)
# Choosing TERRY
# Initialising the value of count as -1 because it appears in the cast list
count = -1
terry_in_f = f.readlines()
for line in terry_in_f:
if 'TERRY' in line:
count = count + 1
print(count)
# Finding the line number in which Gina states 'like an eggplant'
for index, line in enumerate(f):
if line.lower() == "like an eggplant":
print(index)
break
if "like an eggplant" will always enter the block because "like an eggplant" isn't falsey. You need to check the actual line from the file is equal to the string you're looking for. So it should be if line == "like an eggplant".
Also, you want to print the line number. You can use enumerate() to give you the index of the line you're on instead of just printing the actual line itself.
for index, line in enumerate(f):
if line.lower() == "like an eggplant":
print(index)
break
Lastly, instead of doing a hard comparison of if line == "like an eggplant":, it may be better to do if "like an eggplant" in line:. This will return true if the string "like an eggplant" is in the script line, even if there is some surrounding noise. For example, if the script says "Gina: like an eggplant", having a direct comparison would return false. Checking if the string is inside the line would return True. It gives you more flexibility.
I'm new at Python and trying some exercises I found on-line. The one I'm busy with requires an text input first, folowed by an ineteger input.
I get stuck on the integer input which raises an error.
I've started by modifying the code slightly to test myself when I first got the error.
Eventually changed it backed to be exactly like the example/exercise had it, but both resulted in the same error, on the same line.
The error raised was:
Traceback (most recent call last):
File ************************ line 7, in <module>
numOfGuests = int(input())
ValueError: invalid literal for int() with base 10: ''
I've checked around a bit and found it get's triggered when the input is empty, but according to what I've read the the rest of the code should handle that.
numOfGuests = int(input())
if numOfGuests:
I expected the code to ask for the input again if nothing was entered, but get the error instead.
Much appreciated.
Update:
I've managed to figure out a work-around, and even though it isn't a answer to my question, I'll take it.
For anyone that's interested, here's what I did:
I changed:
numOfGuests=int(input())
to:
numOfGuests=input()
Only once something was entered did I convert it:
numOfGuests=int(numOfGuests)
so the final block is:
numOfGuests=''
while not numOfGuests:
print('How many guests will you have?')
numOfGuests = input()
numOfGuests=int(numOfGuests)
Any ideas to improve it, or some insight, would be appreciated.
I know this question is 10 months old but I just want to share the reason why you are having an error ValueError.
Traceback (most recent call last):
File ************************ line 7, in <module>
numOfGuests = int(input())
ValueError: invalid literal for int() with base 10: ''
Is because the input() function reads any value and convert it into a string type. Even if you try to input empty or blank.
Sample code:
any_input = input("Input something: ")
print(f"Your input is: [{any_input}]")
Ouput:
Input something:
Your input is: []
Then the blank or empty string will be passed inside the int() function. The int() function will try convert string into an integer with a base of 10. As we all know, there is no blank or empty numbers. That is why it is giving you a ValueError.
To avoid this, we need to use try-except/EAFP in your code:
try:
# Try to convert input to integer
numOfGuests = int(input("How many guests will you have? "))
except:
# Handle Value Error
And put inside a While-loop to repeat until input is valid.
Sample code:
while True:
try:
# Try to convert input to integer
numOfGuests = int(input("How many guests will you have? "))
# If input is valid go to next line
break # End loop
except:
# Handle Value Error
print("Invalid input!")
print(f"The number of guest/s is: {numOfGuests}")
Ouput:
How many guest will you have? 3
The number of guest/s is: 3
So I have written this code:
title, name = input("Please provide your title and name: ").split()
if I were to input say, mr fabulous, then mr and fabulous would be assigned to title and name accordingly, however, what if I were to just write fabulous and want it to be assigned to name instead of title?
Am i tackling this in the wrong way? Is there another way to do this with just one input() command? thanks in advance!
I believe this will throw an exception. I Also think you also want raw_input in stead of input, as the latter will try to process your input as a python command, and the former will process it as a string.
>>>title, name = raw_input("Please provide your title and name: ").split()
Please provide your title and name: fabulous
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: need more than 1 value to unpack
Python's sytax to assign multiple variables simultaneously works when the number of variables matches the number of values in the given utterable.
As you can see the best way to get to the bottom of this is usually to just go for it and see what happens!
Now as for a suggestion for how to handle your input maybe something like this:
user_input = raw_input("Please provide your title and name: ").split()
if len(user_input) > 1: # at least two entries provided
title = user_input[0] # the first is the title
name = user_input[1] # the second is the name
elif len(user_input) > 0: # one input provided
title = "" # Or another default
name = user_input[0] # assign to name
print title,name
Sample output:
Please provide your title and name: mr fabulous
mr fabulous
Please provide your title and name: fabulous
fabulous
I am trying to iterate through a string and write characters to a list (with a 'for' loop). If I create the empty list before the for loop, python thinks its a string when I get to myList.append(stuff) It works if I create the empty list in the loop, but the obviously it gets erased at each iteration. I've tried to play with global stuff but I'm not getting anywhere. *This is supposed to be a very simply cipher, a warm-up to a bigger project but this is holding me up.
alphabet = 'abcdefghijklmnopqrstuvwxyz'
while True:
code = []
index = int(input("Code Index:"))
message = input("Message: ")
for i in message:
if i in alphabet:
value = alphabet.find(i)
value += index
new_letter = alphabet[value]
print('new letter: ' + new_letter)
code.append(new_letter)
print('code: ' + str(code))
else:
code.append(i)
code = ''.join(code)
input("EXPORT CODE: ")
print(code)
But when this runs I get:
<i>Traceback (most recent call last):
File "C:/Users/Max Hayes/Desktop/PyCrypt/test.py", line 15, in <module>
code.append(new_letter)
AttributeError: 'str' object has no attribute 'append'</i>
code = ''.join(code) you rebind code to a str class, that's why you have the problem. Probably you can change it to code_str = ''.join(code) . In addition, this statement need to be put outside of the for loop.