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

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.

Related

I added an operators to give spaces between the two strings but it still doesn't work

I was trying to make a name input that whenever you type a name it places on the welcome sign of the game. The only problem I am experiencing is that the name I input never has spaces between it, despite that I placed an operator to give it a space
name = input("what is your name:")
print("Welcome to the Casino" + name + "now go play till get broke")
and this is the output result: Welcome to the CasinoMikenow go play till get broke
You could always just add a space after 'Casino' and before 'now'. A better way would be to use an fstring.
For example:
name = input("what is your name: ")
print(f'Welcome to the Casino {name} now go play till get broke')
Output:
what is your name: Jordan
Welcome to the Casino Jordan now go play till get broke
Edit: Here are a few resources on format string literals:
'f-Strings: A New and Improved Way to Format Strings in Python' article on RealPython.com
'Python f-strings: Everything you need to know!'article on DataGy.io
Their are many ways to solve this problem for example:
You can add space after the word "Casino" and before the word "now"
print("Welcome to the Casino" + name + "now go play till get broke")
You can use "," instead of using "+" to separate multiple values in print statement:
print("Welcome to the Casino", name, "now go play till get broke")
"Welcome to the casino " + name + " now go play"
type it like this add a space at the end
Or just
name = input("what is your name: ")
print(f"Welcome to the Casino {name}")

Python printing beginner

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!

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

How do I insert a variable into a raw_input query?

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.

Python for Absolute Beginners: Chapter 2 #Word Problems [duplicate]

This question already has answers here:
input vs. raw_input: Python Interactive Shell Application?
(2 answers)
Closed 6 years ago.
I've started working on the well known Python for Absolute Beginners 3e. I've been copying the code faithfully, but some how keep getting error messages. So, I used the code provided in the help/examples folder but still get the same message:
Traceback (most recent call last):
File "word_problems.py", line 6, in <module>
input("Press the enter key to find out.")
File "<string>", line 0
^
SyntaxError: unexpected EOF while parsing
Can someone give me either a clue, or explain what's not working. I can also post part of the code, the rest is identical (but I guess many people know this book), but with different questions:
print("If a 2000 pound pregnant hippo gives birth to a 100 pound calf,")
print("but then eats 50 pounds of food, how much does she weigh?")
input("Press the enter key to find out.")
print("2000 - 100 + 50 =", 2000 - 100 + 50)
useraw_input instead of input
If you use input, then the data you type is is interpreted as a
Python Expression which means that you end up with gawd knows
what type of object in your target variable, and a heck of a wide
range of exceptions that can be generated. So you should NOT use input
unless you're putting something in for temporary testing, to be used
only by someone who knows a bit about Python expressions.
raw_input always returns a string because, heck, that's what you
always type in ... but then you can easily convert it to the specific
type you want, and catch the specific exceptions that may occur.
Hopefully with that explanation, it's a no-brainer to know which you
should use.
source 1 | source 2
As others have said, it's because input in python 3 behaves like raw_input did in python 2. So one solution would be to use raw_input to get this to work in python 2.
However if you're following this book which seems like it's using python 3 I think you're much better off switching to python 3 now and you shouldn't run into these issues further along in the book.
You are using python2 version
so you raw_input() instead of input()
and your code should be:
print("If a 2000 pound pregnant hippo gives birth to a 100 pound calf,")
print("but then eats 50 pounds of food, how much does she weigh?")
raw_input("Press the enter key to find out.")
print("2000 - 100 + 50 =", 2000 - 100 + 50)
and If you want show output only on blank input or enter,you can put simple validation as:
print("If a 2000 pound pregnant hippo gives birth to a 100 pound calf,")
print("but then eats 50 pounds of food, how much does she weigh?")
ur = raw_input("Press the enter key to find out.")
if ur== '':
print "She weigh ", 2000 - 100 + 50,"pounds"
else:
print 'SOrry!'

Categories