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

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!'

Related

How to print a text with an emoji together using Python in replit.com and I don't know why I am getting this error

This is what I am trying to do
[This is my try on it. I don't know why there is an error. I don't know how to print a text with an emoji.]
(https://i.stack.imgur.com/5Blv4.png)
print("""
R1cHL3
December 30th 2022
I am signing up for Replit's 100 days of Python
challenge!
I will make sure to spend some time every day coding
along, for a minimum of 10 minute a day.
I'll be using Replit, an amazing online IDE so I can do
this from my phone wherever I happen to be. No excuses
for not coding from the middle of a field!
"")
print("I am feeling")
print(u'\U0001f604')
print("You can follow my progress at") --- Line 14
File "main.py", line 15
print("You can follow my progress at")
^
SyntaxError: EOF while scanning triple-quoted string literal
Thank you.
I am trying different ways to expect it to work. Trying and trying until it will hopefully work
print("""
...
...
this from my phone wherever I happen to be. No excuses
for not coding from the middle of a field!
"")
This is the problem. There should be three quotes on that last line, not two.

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!

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.

Reading user input in python 2.4, putting it into a queue

So I'm writing a differential calculator program in python 2.4 (I know it's out of date, it's a school assignment and our sysadmin doesn't believe in updating anything) that accepts a user input in prefix notation (i.e. input = [+ - * x^2 2x 3x^2 x], equivalent to x^2 + 2x - 3x^2 * x) and calculates the differential.
I'm trying to find a way to read the command line user input and put the mathematical operators into a queue, but I can't figure it out! apparently, the X=input() and x=raw_input() commands aren't working, and I can find literally 0 documentation on how to read user input in python 2.4. My question is: How do I read in user input in python 2.4, and how do I put that input into a queue? Here is what I am trying:
1 formula = input("Enter Formula:")
2
3 operatorQueue=[]
4
5 int i = len(formula)
6
7 for x in formula:
8 if formula[x] == '*', '+', '-', '/':
9 operatorQueue.append(formula[x])
0
11 print "operator A:", operatorQueue.pop(0)
12
Which is not working (I keep getting errors like "print: command not found" and "formula:command not found")
Any help would be appreciated
#miku already answered with this being your initial problem, but I thought I would add some more.
The "sh-bang" line is required by command line scripts so that the proper process is used to interpret the language, whether it be bash, perl, python,etc. So in your case you would need: /usr/bin/env python
That being said, once you get it running you are going to hit a few other issues. raw_input should be used instead of input, because it will give you back a raw string. input is going to try and eval your string which will mostly likely give you problems.
You may need to review python syntax a bit more. Assignments in python don't require that you declare the variable type: int a = 1. It is dynamic and the compiler will handle it for you.
Also, you will need to review how to do your if elif else tests to properly handle the cases of your formula. That too wont work doing it all on one line with multiple params.
If you're on a unix-ish platform, put a
#!/usr/bin/env python
on top of your program. The shell does not seem to recognize that you are running a python script.

Python unexpected EOF while parsing

Here's my python code. Could someone show me what's wrong with it.
while 1:
date=input("Example: March 21 | What is the date? ")
if date=="June 21":
sd="23.5° North Latitude"
if date=="March 21" | date=="September 21":
sd="0° Latitude"
if date=="December 21":
sd="23.5° South Latitude"
if sd:
print sd
And Here's what happens:
>>>
Example: March 21 | What is the date?
Traceback (most recent call last):
File "C:\Users\Daniel\Desktop\Solar Declination Calculater.py", line 2, in <module>
date=input("Example: March 21 | What is the date? ")
File "<string>", line 0
^
SyntaxError: unexpected EOF while parsing
>>>
Use raw_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.
Reference
Note: this is only for Python 2. For Python 3, raw_input() has become plain input() and the Python 2 input() has been removed.
Indent it! first. That would take care of your SyntaxError.
Apart from that there are couple of other problems in your program.
Use raw_input when you want accept string as an input. input takes only Python expressions and it does an eval on them.
You are using certain 8bit characters in your script like 0°. You might need to define the encoding at the top of your script using # -*- coding:latin-1 -*- line commonly called as coding-cookie.
Also, while doing str comparison, normalize the strings and compare. (people using lower() it) This helps in giving little flexibility with user input.
I also think that reading Python tutorial might helpful to you. :)
Sample Code
#-*- coding: latin1 -*-
while 1:
date=raw_input("Example: March 21 | What is the date? ")
if date.lower() == "march 21":
....
I had this error, because of a missing closing parenthesis on a line.
I started off having an issue with a line saying:
invalid syntax (<string>, line ...)?
at the end of my script.
I deleted that line, then got the EOF message.
While #simon's answer is most helpful in Python 2, raw_input is not present in Python 3. I'd suggest doing the following to make sure your code works equally well in Python 2 and Python 3:
First, pip install future:
$ pip install future
Second: import input from future.builtins
# my_file.py
from future.builtins import input
str_value = input('Type something in: ')
And for the specific example listed above:
# example.py
from future.builtins import input
my_date = input("Example: March 21 | What is the date? ")
I'm using the follow code to get Python 2 and 3 compatibility
if sys.version_info < (3, 0):
input = raw_input
I'm trying to answer in general, not related to this question, this error generally occurs when you break a syntax in half and forget the other half. Like in my case it was:
try :
....
since python was searching for a
except Exception as e:
....
but it encountered an EOF (End Of File), hence the error. See if you can find any incomplete syntax in your code.
i came across the same thing and i figured out what is the issue. When we use the method input, the response we should type should be in double quotes. Like in your line
date=input("Example: March 21 | What is the date? ")
You should type when prompted on console "12/12/2015" - note the " thing before and after. This way it will take that as a string and process it as expected. I am not sure if this is limitation of this input method - but it works this way.
Hope it helps
After the first if statement instead of typing "if" type "elif" and then it should work.
Ex.
` while 1:
date=input("Example: March 21 | What is the date? ")
if date=="June 21":
sd="23.5° North Latitude
elif date=="March 21" | date=="September 21":
sd="0° Latitude"
elif date=="December 21":
sd="23.5° South Latitude"
elif sd:
print sd `
What you can try is writing your code as normal for python using the normal input command. However the trick is to add at the beginning of you program the command input=raw_input.
Now all you have to do is disable (or enable) depending on if you're running in Python/IDLE or Terminal. You do this by simply adding '#' when needed.
Switched off for use in Python/IDLE
#input=raw_input
And of course switched on for use in terminal.
input=raw_input
I'm not sure if it will always work, but its a possible solution for simple programs or scripts.
Check the version of your Compiler.
if you are dealing with Python2 then use -
n= raw_input("Enter your Input: ")
if you are dealing with python3 use -
n= input("Enter your Input: ")
Check if all the parameters of functions are defined before they are called.
I faced this problem while practicing Kaggle.

Categories