In Learn Python The Hard Way (Exercise 13) the 3rd Study Drill says to "Combine raw_input with argv to make a script that gets more input from a user."
I wrote this script below, intending to have the terminal prompt the user for answers to three questions, then it would print back phrases with those answers integrated into them. However, I get an error about not having enough values to unpack when I try to run it with the following command:
python ex13.py
I understand that I need more variables to unpack in order for the script to work, so when I type this then the script works but never outputs the variables "first", "second" or "third" (which I don't want it to anyway):
python ex13.py first second third
I know how to write a script without importing argument variables, but how else can I interpret the study drill? I know I am not understanding the prompt of the study drill correctly but I'm not sure how to write the script differently or even if I am going in the right direction.
Can anyone offer some tips or advice? You don't have to give me the answer outright (I like figuring things out) but I am at a loss for the moment.
MY SCRIPT:
from sys import argv
script, color, number, shape = argv
color = raw_input("What is your favorite color? ")
number = raw_input("What is your favorite number? ")
shape = raw_input("What is your favorite shape? ")
print """
This program is called %r and it will determine your
favorite color, number and shape.
""" % script
print "Based on your answers, your favorite color is:", color
print "Your favorite number is:", number
print "And your favorite shape is a:", shape
What exactly do you want your code to do? If you want to have
$ python ex13.py
$ What is your favorite color? <yourColor>
..........
$ Your favorite color is <yourColor>
Then you need to get rid of the part where you set all those values from argv. argv is a list of the arguments passed to python when you invoke it in the command line. The fix you have in your comments sets script = ['ex13.py'] instead of 'ex13.py' for precisely this reason, you're setting script to be a list as opposed to a string.
If you want your code to run so that you pass the script arguments when you run it, you could get rid of your sections calling for raw_input (or you could leave them in, but that would overwrite their values from what you passed in the command line) Try running the code you've posted with
$ python ex13.py <yourColor> <yourNumber> <yourShape>
It should work much more closely to what you want.
As you have already solved one problem by removing the variables before the =, now the only problem is you are getting square brackets around ex13.py.
You see you have to add another variable after script before = that is without input() and the problem is solved.
Related
I just started with python. My teacher gave me an assignment and I'm stuck on a project where I have to make the numbers of characters appear when someone enters their name for input command input("what is your name") I don't think I have been taught this and google is giving me a hard time when trying to look for the command. This might be Childs play to most but can anyone throw me a tip/hint?
using print(len(myVariable)) should output the number of characteres that the string has. You should familiarize yourself with python methods.
Here are some resources:
https://docs.python.org/3/library/functions.html
https://www.w3schools.com/python/ref_func_len.asp
Printing the length of a variable is very easy with Python due to the many built-in functions you can perform on strings! In this case, you would use use len(). Read about other helpful string methods in python too in order to get a head start on your class!
inputtedName = input("What is your name? ")
nameLength = len(inputtedName)
print("Your name is " + str(nameLength) + " letters.")
print(f"Your name is {nameLength} letters.")
The first print statement uses something called string concatenation to create a readable sentence using variables. The second uses f strings to make using variables in your strings even easier!
name = input("Hi. What's your name? ")
print("name")
print("Hi,", name)
input("\n\nPress the enter key to exit.")
It says multiple statements found while compiling a single statement
I'm using a book and tried many different things. Also, I'm a noob at this as you can tell. If you have any suggestions that'll be great
Your code is fine, assuming you are using python 3, but you need to type (or paste) each line, one at a time. Based on what you are seeing, I suspect you are putting it all in at once, without a new line after each line.
If you are using python 2, you'll need to use raw_input rather than input, like this:
name = raw_input("Hi. What's your name? ")
print("name")
print("Hi,", name)
input("\n\nPress the enter key to exit.")
So couple of things:
print("name") will not print the name you captured from the last variable but a string that says name
print("Hi,", name) prints ('Hi,', 'Dmitry') which is probably not what you want, instead do this: ', '.join(["Hi", name]) There are probably other Python 3 conventions but I work in Python 2 so I don't know them all off the top of my head.
input("\n\nPress the enter key to exit.") not sure of the purpose of this line. Seems like a stray line from a block of code and it's not being assigned to any variable. Furthermore it throws an error SyntaxError. What book are you using if I may ask?
You can check the Python version in the HELP>about IDLE tab of IDLE editor or Shell - you seem to be using python 2 as others have stated
If you are able to enter and run one line of code at a time, followed by the next line then you are using the Shell, not the IDLE editor
You should be able to paste the code you have in question into IDLE editor and run (F5) - you should be prompted to save before it is run in the Shell.
I am really new on python and try to find a good IDE
My friend suggest me sublime text3.
But when I try to write some code, it come up a question:
I try to write a code that will read the line from user input.
import sys
a = sys.stdin.readline()
print (a)
At beginning I expect some cmd jump out and let me type something to let my program read.
But there's nothing happen....
Can someone tell me that can SublimeText read user input?
or did I do something wrong....
(I find out that there is a post discuss about 'Using sys.stdin.readline() to read multiple lines from cmd in Python'
Using sys.stdin.readline() to read multiple lines from cmd in Python
but I'm not sure if this is the case for sublime.....)
Hi everyone again.
Sorry for the miss leading title and thank you for answering my question again!
DYZ point out the question I would want to ask, and actually I also try package "SublimeREPL". However, it's not working :(( (the figure show it)
I also try my code on terminal and it works...
Can some one tell me where did I did wrong? or maybe I shouldn't do this on Sublime..
thank you guys again and sorry for confusing!
enter image description here
Correct me if I misunderstand what you are trying to do, but to get user input in python theres no need for importing sys, just use raw_input(). For example:
x = raw_input("enter something: ")
print "you entered", x
This program (written in sublime by the way) when run in the command prompt, produced the following output:
python user-input.py
enter something: hello
you entered hello
In this case I entered "hello". If you don't need a prompt, just don't pass any parameter to the raw_input method.
Let me know if this wasn't what you needed or if you need any clarification.
See this question on using stdin: How to finish sys.stdin.readlines() input?
Example below (From the Q):
>>> import sys
>>> message = sys.stdin.readlines()
Hello
World
My
Name
Is
James
Bond
# <ctrl-d> EOF sent
>>> print message
['Hello\n', 'World\n', 'My\n', 'Name\n', 'Is\n', 'James\n', 'Bond\n']
If using Python 2.x it is recommended you use the raw_input() function and the input() function in Python 3.x. Like below
>>> raw_input()
test
'test'
I am a total newbie in programming so I was hoping anyone could help me. I am trying to write program in python that, given an integer n, returns me the corresponding term in the sylvester sequence. My code is the following:
x= input("Enter the dimension: ")
def sylvester_term(n):
""" Returns the maximum number of we will consider in a wps of dimension n
>>> sylvester_term(2)
7
>>> sylvester_term(3)
43
"""
if n == 0:
return 2
return sylvester_term(n-1)*(sylvester_term(n-1)-1)+1
Now, my questions are the following, when trying to run this in GitBash, I am asked to input the n but then the answer is not showing up, do you know what I could do to receive the answer back? I plan to continue the code a bit more, for calculating some other data I need, however, I am not sure if it is possible for me to, after coding a certain piece, to test the code and if so, how could I do it?
You will need to add:
print(sylvester_term((int(x)))
to the end of your program to print the answer.
You will need to cast to int because the Python Input() function stores a string in the variable. So if you input 5 it will return "5"
This does not handle exceptions, e.g if the user inputs a letter, so you should put it in a try and except statement.
Here's an example of how I'd handle it. You can use sys.argv to get the arguments passed via the command line. The first argument is always the path to the python interpreter, so you're interested in the second argument, you can get it like so:
sys.argv[1]
Once that is done, you can simply invoke your function like so
print(sylvester_term(int(sys.argv[1]))
I'm stuck at this point. here is the code:
from sys import argv
script, first, second, third = argv
print "The script is called:", script
print "The first variable is:", first
print "The second variable is:", second
print "The third variable is:", third
my problem is this, when I run it I get:
value error need more than one value to unpack
as far as I can see I have three values and the code is good, could someone explain where I am going wrong please.
So, in chat #Ricky troubleshooted his way to successfully determining that argv was splitting on whitespace and not , comma. Changing his command line params from
$python myprog.py one,two,three
to
$python myprog.py one two three
made everything fine.
For those who wish to learn the mysteries of the argparse.