Python3 - "ValueError: not enough values to unpack (expected 3, got 1)" - python-3.x

I'm very new to Python and programming overall, so if I seem to struggle to understand you, please bear with me.
I'm reading "Learn Python 3 the Hard Way", and I'm having trouble with exercise 23.
I copied the code to my text editor and ended up with this:
import sys
script, input_encoding, error = sys.argv
def main(language_file, encoding, errors):
line = language_file.readline()
if line:
print_line(line, encoding, errors)
return main(language_file, encoding, errors)
def print_line(line, encoding, errors):
next_lang = line.strip()
raw_bytes = next_lang.encode(encoding, errors=errors)
cooked_string = raw_bytes.decode(encoding, errors=errors)
print(raw_bytes, "<====>", cooked_string)
languages = open("languages.txt", encoding = "utf-8")
main(languages, input_encoding, error)
When I tried to run it I got the following error message:
Traceback (most recent call last):
File "pag78.py", line 3, in <module>
script, input_encoding, error = sys.argv
ValueError: not enough values to unpack (expected 3, got 1)
which I am having difficulties understanding in this context.
I googled the exercise, to compare it something other than the book page and, if I'm not missing something, I copied it correctly. For example, see this code here for the same exercise.
Obviously something is wrong with this code, and I'm not capable to identify what it is.
Any help would be greatly appreciated.

When you run the program, you have to enter your arguments into the command line. So run the program like this:
python ex23.py utf-8 strict
Copy and paste all of that into your terminal to run the code. This exercise uses argv like others do. It says this in the chapter, just a little bit later. I think you jumped the gun on running the code before you got to the explanation.

Let's record this in an answer for sake of posterity. In short, the immediate problem described lies not as much in the script itself, but rather in how it's being called. No positional argument was given, but two were expected to be assigned to input_encoding and error.
This line:
script, input_encoding, error = sys.argv
Takes (list) of arguments passed to the script. (sys.argv) and unpacks it, that is asigns its items' values to the variables on the left. This assumes number of variables to unpack to corresponds to items count in the list on the right.
sys.argv contains name of the script called and additional arguments passed to it one item each.
This construct is actually very simple way to ensure correct number of expected arguments is provided, even though as such the resulting error is perhaps not the most obvious.
Later on, you certainly should check out argparse for handling of passed arguments. It is comfortable and quite powerful.

I started reading LPTHW a couple of weeks ago. I got the same error as 'micaldras'. The error arises because you have probably clicked the file-link and opened an IEExplorer window. From there, (I guess), you have copied the text into a notepad file and saved. it.
I did that as well and got the same errors. I then downloaded the file directly from the indicated link (right click on the file and choose Save Target As). The saves the file literally as Zed intended and the program now runs.

Related

Python 3 Tips to Shorten Code for Assignment and Getting Around TextIO

I've been going through a course and trying to find ways to shorten my code. I had this assignment to open a text file, split it, then add all of the unique values to a list, then finally sort it. I passed the assignment, but I have been trying to shorten it to learn some ways to apply any shortening concepts to future codes. The main issues I keep running into is trying to make the opened file into strings to turn them into lists to append and such without read(). If I don't used read() I get back TextIO errors. I tried looking into it but what I found involved importing os and doing some other funky stuff, which seems like it would take more time.
So if anyone would mind giving me tips to more effectively code this that are beginner friendly I would be appreciative.
romeo = open('romeo').read()
mylist = list()
for line in romeo.split() :
if line not in mylist:
mylist.append(line)
mylist.sort()
print(mylist)
I saw that set() is pretty good for unique values, but then I don't think I can sort it. Then trying flip flop between a list and set would seem wacky. I tried those swanky one line for loop boys, but couldn't get it to work. like for line not in mylist : mylist.append(line) I know that's not how to do it or even close, but I don't know how to convey what I mean.
So to iterate:
1. How to get the same result without read() / getting around textIO
2. How to write this code in a more stream lined way.
I'm new to the site and coding, so hopefully I didn't trigger anyone.

Migrate from Python2 to Python 3.6.2 with TypeError

I want to migrate from python2 to python3.
In code, it opens a file in binary mode like this.
f = open('test', 'rb+')
Because, it needs file seeking like this.
f.seek(-26, 1)
And, the code writes a formatted string to file.
f.writelines("%20s,%04d\n" % (varStr, varInt))
f.writelines('{0:>20s},{1:04d}\n'.format(varStr, varInt))
Upper code is original code and lower code is edited by me.
But, When I run a code, there is an error.
TypeError: a bytes like object is required, not 'int'
Please, help me out from this hell.
There are two mistakes:
You need encode your strings when opening the file in binary mode (to change them in bytes)
writelines must be used with a list instead of a single item (the function has an 's' at the end). In your case, you can use 'write'
Maybe something like this will work:
f.write(("%20s,%04d\n" % (varStr, varInt)).encode())
f.write(('{0:>20s},{1:04d}\n'.format(varStr, varInt)).encode())

Python 3 Code works interactively, but not when I run my code from a .py file

I am new to programming, and new to Python. I am running Python 3 on Windows 10, and I am having a strange problem. I built the following script, and it doesn't work:
def count_item(sequence, item):
return sequence.count(item)
count_item([1,2,1,1], 1)
When I run it, it comes up empty. Not so much as an error, or the "none" that Python likes to give.
However, when I run it from the interactive shell:
>>> item = 1
>>> sequence = [1,2,1,1]
>>> sequence.count(item)
3
I am guessing that this has something to do with how functions work on a deep level in Python, but I am just not sure.
Any help would be appreciated.
The REPL, or interactive shell, is built to be interactive. One way that is manifested is that you don't need to print variables and other objects - you can just type their name, hit Enter, and the relevant info shows up.
However, when actually running a program, you need to explicitly call the print() function in order to make anything show up on the screen. return just returns a value to the calling function or statement. So, for your code, modify the last line to:
print(count_item([1,2,1,1], 1))

Python3.4 Anaconda: Input() Function Broken?

I'm having trouble with the input() function in Python3.4 using the Anaconda integrated editor. If I just type
x = input()
into the editor, it returns a blank line that I can type text into. If I type:
foo
into this line, I would expect 'foo' be stored as a string with variable name x. But, instead I get:
NameError: name 'foo' is not defined
To make the function work as expected, I must instead type in:
'foo'
which is unfortunate because what I really want is just to pause my code and wait for an arbitrary user input, and I read somewhere that "wait = input()" is the most pythonic way to do this. Using that line in my actual script returns an "unexpected EOF" error - I assume as another symptom of the same problem. Can anyone suggest a workaround?
Note: I suspect this is an Anaconda-specific problem, given the following reference:
https://docs.python.org/3.4/library/functions.html#input
Thanks for your time.
Your code is being run by Python 2, not 3. I don't know enough about Anaconda to know if the problem is with their editor, or if you have your path messed up, but the problem is that the wrong version of Python is being used.

Same for loop, giving out two different results using .write()

this is my first time asking a question so let me know if I am doing something wrong (post wise)
I am trying to create a function that writes into a .txt but i seem to get two very different results between calling it from within a module, and writing the same loop in the shell directly. The code is as follows:
def function(para1, para2): #para1 is a string that i am searching for within para2. para2 is a list of strings
with open("str" + para1 +".txt", 'a'. encoding = 'utf-8') as file:
#opens a file with certain naming convention
n = 0
for word in para2:
if word == para1:
file.write(para2[n-1]+'\n')
print(para2[n-1]) #intentionally included as part of debugging
n+=1
function("targetstr". targettext)
#target str is the phrase I am looking for, targettext is the tokenized text I am
#looking through. this is in the form of a list of strings, that is the output of
#another function, and has already been 'declared' as a variable
when I define this function in the shell, I get the correct words appearing. However, when i call this same function through a module(in the shell), nothing appears in the shell, and the text file shows a bunch of numbers (eg: 's93161), and no new lines.
I have even gone to the extent of including a print statement right after declaration of the function in the module, and commented everything but the print statement, and yet nothing appears in the shell when I call it. However, the numbers still appear in the text file.
I am guessing that there is a problem with how I have defined the parameters or how i cam inputting the parameters when I call the function.
As a reference, here is the desired output:
‘She
Ashley
there
Kitty
Coates
‘Let
let
that
PS: Sorry if this is not very clear as I have very limited knowledge on speaking python
I have found the solution to issue. Turns out that I need to close the shell and restart everything before the compiler recognizes the changes made to the function in the module. Thanks to those who took a look at the issue, and those who tried to help.

Resources