How do I insert a variable into a raw_input query? - python

I have started learning Python 2.7.x with the "Learn Python the Hard Way" book. I am currently learning about the raw_input function and I'm experimenting with different ways to use it. I wrote the following code:
name = raw_input("What is your name? ")
print "Hi %s," % name,
home = raw_input("where do you live? ")
print "I hear that %s is a great place to raise a family, %s." % (home, name)
age = raw_input("How old are you, %s? ") % name
I receive this error with the last line:
TypeError: not all arguments converted during string formatting
How can I use the raw_input function in a similar way and insert a variable so customize the question embedded in the raw_input query (apologies if I am making a mess of the terminology)?
Ideally, I'd like to output a question along these lines:
How old are you, Bob?

try:
age = raw_input("How old are you, %s? " % name)
Explanation:
raw_input([prompt])
If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.
So, when you do
age = raw_input("How old are you, %s? ") % name
let's say you entered Paul
so the above statement becomes,
age = "Paul" % name
and since string "Paul" is not a placeholder it throws the corresponding error.

Related

How to write a string without quotes to a file with MRJob? [duplicate]

I'm new to programming and I stumbled across something unsightly that I would like to remove. Here's my code:
def test1():
print "What is your name, traveler?"
name = raw_input()
print "Hi %r!" % (name)
Here's the output:
What is your name traveler?
Hi 'Karatepig'!
Is there any way to get rid of those single quotes around my name?
You want to use %s there, not %r.
print "Hi %s!" % (name)
I'd add details, but I think others have already written better explanations here and here.
Most saliently:
The difference between %s and %r is that %s uses the str function and
%r uses the repr function. You can read about the differences between
str and repr in this answer, but for built-in types, the biggest
difference in practice is that repr for strings includes quotes and
all special characters are escaped.
Or use the "new" string formatting method:
def test1():
print "What is your name, traveler?"
name = raw_input()
print "Hi {0}!".format(name)

Im getting a "EOL while scanning string literal" while doing beginners coding, idk what else to do

i'm a beginner at coding and I've spent hours trying to fix this, I don't know what else to do
this is the code
import time
Sid = input("yes hi my name bub, what ur name?")
if (Sid != "bob MC cool pants"):
print ("i don't care...)
time.sleep(2)
print ("so how are the kids???")
it highlights the empty space after the ("I don't care..."), I dont know why it didn't do this in any of the other tests I'm testing please help
Credit to #Aran-Fey
import time
Sid = input("yes hi my name bub, what ur name?")
if (Sid != "bob MC cool pants"):
print ("i don't care...")
time.sleep(2)
print ("so how are the kids???")
You forgot to close off the string - which is a variable type that is designed to store characters. In Python, when writing the value of a string, you put " " marks around it, telling the python interpreter that what you have typed is in fact a string.
Since you forgot to add an ending " the python interpreter thought that the closing parenthesis ) was actually part of the string. The error is basically python saying "Hey, there's an open parenthesis, but where is the closing one?"

Invalid Syntax with name input

I'm new to programming and Python. I am attempting to write my first program, however I keep getting an "Invalid Syntax" error for these few lines of code. This is all I am trying to get down pat. When I written this, it was in IDLE for Python 3.6.1
name = raw_input ("Please tell me your name: ")
print ("Hello "+ name)
print "Your name is:" + str(len(name)) "letters long"
Can you guys please give me a hand for this? Also I like more information around Syntax errors because I heard they happen often. What are they?
I think you lost a plus in your code,
name = raw_input ("Please tell me your name: ")
print ("Hello "+ name)
print "Your name is:" + str(len(name)) "letters long"
# ^ There should be a "+" ?
The right code should be:
name = raw_input ("Please tell me your name: ")
print ("Hello "+ name)
print "Your name is:" + str(len(name)) + "letters long"
There are a few things wrong with it from the beginning, I'd recommend you check out A Byte of Python as it gives a solid understanding of Python and caters it to newbies.
As for your actual issue print is no longer a keyword in Python 3 and requires the use of parenthesis print("thing") as opposed to print "thing"
A second issue I spotted is that raw_input is now input in Python 3 so that also needs to be changed.
To avoid the final issue which seems to be the lack of a + when you concatenate the string, use the str.format() method or perhaps Python 3.6's f strings.
I had something similar happen, when I added a script to a /bin directory.
my issue was that at the start I had:
#!/usr/bin/env python
that called python2
when I needed:
#!/usr/bin/env python3
that actually calls a python3 environment

Why do I get a "name error: name "..." is not defined " when I run this code and enter information?

When I run this simple script and enter information an error appears which says: Name error: name'...' is not defined.
Name = str(input("Enter the name of your friend: "))
Age = int(input("Enter age of that friend: "))
print("The name of your friend is {} and their age is {}".format(Name, Age))
To expand on Tarun Guptas answer, the convention in python is that function names always start with lowercase letters. Uppercase first letters are reserved for classes. All the inbuilt functionality of python sticks to these conventions. The same is true for variable names, never start them with uppercase letters.
If you find yourself hunting a lot after syntax errors, get yourself an editor with a good python linter, that is, inbuilt functionality that checks the code on the fly. This will help you make quick progress in avoiding the most common mistakes.
As you advance in python, you should really check out the python style guide. Most of the conventions in python are not strictly mandated by the language, however if you ever plan to interact with other programmers, they will hate you with a passion you if you don't stick to pep8.
I have modified your code to the correct state:
name = str(input("Enter the name of your friend"))
age = int(input("Enter age of that friend"))
print("The name of your friend is {} and their age is {}".format(name, age))
There were three errors:
p of print needs to be lowercase and
a closing parenthesis was missing
f of format also needs to be in lowercase.

Error in my code that I cannot find, beginner program [duplicate]

This question already has answers here:
Error - input expected at most 1 argument, got 3
(2 answers)
Closed 6 years ago.
I am trying to learn python and I am following video instruction on verson 3 and using the latest Pycharm IDE.
My screen looks like the instructor's screen, but I could have tunnel vision from staring at it too long. His code executes perfectly while mine crashes. What am I missing?
Error message:
line 6, in <module>
balance = float(input("OK, ", name, ". Please enter the cost of the ", item, ": "))
TypeError: input expected at most 1 arguments, got 5
First part of the program up to line 6:
# Get information from user
print("I'll help you determine how long you will need to save.")
name = input("What is your name? ")
item = input("What is it that you are saving up for? ")
balance = float(input("OK, ", name, ". Please enter the cost of the ", item, ": "))
The pycharm version is:
PyCharm Community Edition 2016.1.4 Build #PC-145.1504, built on May
25, 2016 JRE: 1.8.0_77-b03 x86 JVM: Java HotSpot(TM) Server VM by
Oracle Corporation
Now, am I just blind or is there a possible ide issue that could have happened in a minor update between my version and the instructor's version, he is teaching python 3.
Many thanks in advance for any help that anyone can throw out.
In Python, the input operator takes a single input (the string that you would like to display). Also in Python, string concatenation is done with the + operator. In your current operation, you are passing 5 separate strings rather than the 1 that you want to use. Change that line of code to:
balance = float(input("OK, "+ name +". Please enter the cost of the" + item + ": "))
print ("I'll help you determine how long you will need to save.")
name = raw_input("What is your name? ")
item = raw_input("What is it that you are saving up for? ")
balance = float(raw_input("OK, "+ name +". Please enter the cost of the "+ item +": "))
print name
print item
print balance
A little rewrite may clarify
input_message = "OK, {name}. Please enter the cost of the {item}: ".format(name=name, item=item)
balance = float(input(input_message))
The argument to input should be just a string, which I build using format https://docs.python.org/2/library/string.html#format-examples
You are passing 5 objects, say:
"OK, "
name
". "Please enter the cost of the "
item
": "
therefore the the TypeError
Take into account that you should validate the actual input to be converted into a float, if I type "foobar" as input, the above line will give a ValueError as you can check by yourself.
Try using a string format operator %s. % is a reserved character that you can drop right into the input string. The s that follows the % formats the variable, if possible, into a string. If you need an integer just use %d. Then list the variables in order of appearance in the string preceded by the %
balance = float(input("OK %s. Please enter the cost of the %s: " %(name,item)))
You just have to be careful not to change integers or floats into strings unless you want that to happen which I don't recommend doing in an input statement.

Categories