Python 2.7: Syntax Error. Newlines characters within string literals - python

I am working on a project using Python 2.7 and I am attempting to output a few string literals with objects. Ideally, each string literal should jump to the next line after each \n newline character.
I am still learning and am a novice programmer, so if I need to include more information please let me know and I will edit the question.
Here is what I am working on:
output = (
f"\nFinancial Analysis\n"
f"----------------------------\n"
f"Total Months: {total_months}\n"
f"Total Revenue: ${total_revenue}\n"
f"Average Revenue Change: ${revenue_avg}\n"
f"Greatest Increase in Revenue: {greatest_increase[0]}(${greatest_increase[1]})\n"
f"Greatest Decrease in Revenue: {greatest_decrease[0]} (${greatest_decrease[1]})\n")
Each time I run my script in the terminal, I receive the following error message:
SyntaxError: invalid syntax
(base) Grants-MacBook-Pro-2:PyBank grant$ python PyBank.py
File "PyBank.py", line 45
f"\nFinancial Analysis\n"
Can anyone offer a suggestion as to how I can tweak my code and correct the syntax? Thanks!

Python 2.7 doesn't have f-strings. Switch to 3.6+ or use .format() instead
For example you need to replace
f"Total Months: {total_months}\n"
with
"Total Months: {}\n".format(total_months)

Related

Python 3.6 - How Do I Format Variables and Literals In A .Write Statement?

... (Be advised the actual values in the data below are not static nor that important, but are only an example.)
Specifically, I am needing assistance on understanding what I did wrong with the format and syntax and what is the proper way. Anyway, here goes.
I need the following Python 3.6 code...
stella = open(stellocation + "\\scripts\\sh4.ssc",'w')
stella.write("core.setDate(\""+date+"T"+time+":00", "UTC""); ")\n)
stella.write("core.setObserverLocation("+longitude +", "+latitude+", 6, 0, "SH4 Navigation Point, ""+ ocean +", "earth")");
stella.close()
...to produce this text...
core.setDate("1943-01-01T10:01:00","UTC");
core.setObserverLocation(-161.605158333, 19.2008553333, 6, 0, "USS Perch (Pacific Ocean)", "Earth");
...I keep getting this error...
File "C:\DAATAPOND\Python Scripts\SH4toStellarium.py", line 54
stella.write("core.setDate(\""+date+"T"+time+":00"") ")\n)
^
SyntaxError: unexpected character after line continuation character
I have been researching and experimenting for three days without success. I have read and attempted to digest a number of websites on the ".write" function statement. They tended to be arcane and left me somewhat confused. I decided it was time to seek help. :)
Please let me know if I can be of any assistance.
Take care,
Calvin
PS - This is my first question on StackOverflow. Please let me know if anything should be different.
Use an f-string to make variable substitution easier. And if you want to put literal double-quotes in the string, wrap it in single quotes so you don't need to escape them.
The syntax error is because you put \n outside the string and added an extra ).
stella.write(f'core.setDate("{date}T{time}:00","UTC");\n')
stella.write(f'core.setObserverLocation({longitude}, {latitude}, 6, 0, "SH4 Navigation Point, ({ocean})", "Earth");')
It should be something like this:
stella.write("core.setDate(\""+date+"T"+time+":00"") \n")
Where you went wrong: You were using an extra bracket at the end of the above line and \n was outside the quoted string.

Python dictionary SyntaxError

I'm moving to Python from PHP and I seem to be stuck in my first hour of learning Python.
This seems to be such a basic question that I'm having trouble finding an answer - so please forgive me.
When I try to create a dictionary I enter:
numbers = ('Bob':'322', 'Mary':'110', 'Joe':'839')
I get the error:
File "<stdin>", line 1
numbers = ('Bob':'322', 'Mary':'110', 'Joe':'839')
^
SyntaxError: invalid syntax
I've tried this in both the command line and in IDLE and the same error appears. What am I doing wrong? I really can't see it. Again sorry for low level of this question.
Dictionaries use curly braces {}, not parentheses ()
numbers = {'Bob':'322', 'Mary':'110', 'Joe':'839'}

invalid syntax when trying to set number of decimals

I am using Python 3.3.2 and I am trying to set the number of decimals after an arithmetic operation but it keeps throwing me SyntaxError: invalid syntax. I can't seem to figure out where I am going wrong. Thanks!
exampleInt = 123.456789
print({:.2f}.format(exampleInt)
I keep getting the error at the colon from the Python shell.
:.2f is not a valid literal. You want a format string, and string literals need quotes:
In [1]: exampleInt = 123.456789
In [2]: print('{:.2f}'.format(exampleInt))
123.46
Also, Delgan is right and a closing parenthesis is missing in your example, but the Python shell will just continue the line in this case, rather than raise a SyntaxError.
You forgot to close the print parenthesis, right?

Format string confusing

Hi im new to Python and Ive been trying to get format print to work but, and this may be me being new, but it seems to be very badly implemented.Any examples for 2.7.6 dont work for the new version and their aren't any real examples I could find on the internet for 3.3. As such I would like to ask for a good example of how format string works. For instance ive been trying to get this to work from my homework.
day,date,year,hour,and minutes must be separate variables.
using one formatted print statement,print the following:
Date:5/31/2013
Time: 3:45 pm
I can get it to work with this code:
def date():
Month=5
Day=31
Year=2013
Hours=3
Minutes=45
Scale='pm'
a="Date: %i/%i/%i\nTime: %i:%i %s" %(Month,Day,Year,Hours,Minutes,Scale)
print(a)
It works but its not one line as asked for. Please help format is so confusing.
The \n in your format string is inserting the new line character. Remove the \n, and you will not have the newline any longer.
Characters preceded by a backslash are known as escape characters. They can be used to insert special formatting into strings. For example:
\n is the newline character,
\t is the tab character
Remove \n because that is used to create a line break.

Repeated errors while working with Portable Python [duplicate]

This question already has answers here:
Syntax error on print with Python 3 [duplicate]
(3 answers)
Closed 9 years ago.
Note: This was not answered by the question that was marked as the original. This is more than just a Python v2 vs v3 problem, which I explain in the comments below.
Original post:
I am trying to learn Python at work, so I am currently using Portable Python 3.2.1.1 (which will henceforth be referred to as PP). (I mention this because this problem doesn't happen at home when I use my Mac and regular Python.)
I am working through exercise 16 of Learning Python the Hard Way (http://learnpythonthehardway.org/book/ex16.html). I've heard this isn't the best learning tool, but I am a complete programming n00b and I'm a hands-on learner. If you have any better suggestions, I'm open!
The first few lines of the exercise read:
from sys import argv
script, filename = argv
print "We're going to erase %r." % filename
print "If you don't want that, hit CTRL-C (^C)."
My script is titled Ex16.py and the file I am using is Python.txt, and both of these are in the same folder as the PP .exes. I don't think that's necessary, but hoped maybe it would fix the problem... negative. When I press "Run" in PP, it doesn't work because argv requires you provide an argument when you start the script: python Ex16.py Python.txt
When I launch Python.exe (which, in PP is Portable-Python.exe), I get the standard Python prompt, >>>, but whatever I enter I get the same error message:
File "<stdin>", line 1
with whatever I've just tried repeated back to me with the marker to
indicate where the problem is. (has not been helpful so far)
SyntaxError: invalid syntax
I have tried typing the following at the >>> prompt:
python Ex16.py Python.txt,,
Ex16.py Python.txt,,
"%PATH&\Ex16.py" "%PATH%\Python.txt" (with the actual filepaths),,
print 'hello world'
I just keep getting the same invalid syntax error over and over. Even a basic print command returned an invalid syntax error. The only one that triggered a different error was the one where I tried whole filepaths. That one returned:
File "<stdin>", line 1
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in
position 2-3: truncated \UXXXXXXXX escape
Yes, I have Googled the crap outta both errors. I read that sometimes the problem is not doubling the backspaces, so I tried that, too, putting two \ where just one had been before in both filepaths. I even tried putting — # -*- coding: utf-8 -*- at the beginning of the script thinking maybe there was some unicode error. That, with the full filepaths, resulted in the same unicode error mentioned earlier.
Yes, I have checked that my code is matching that in the exercise.
Yes, this works at home on non-PP.
All this leads me to believe that the problem is probably in the way I'm trying to run the scripts in PP (but why won't print work?), but I haven't a clue what I'm doing wrong.
Thanks!
print is a function in Python 3:
print('my string with content and the like')
It is no longer supported as being a 'statement'. You might want to check out a list of things that changed from python2.x to python3.x (there's a number of incompatibilities). Also, you might be better off finding a tutorial using Python3.
You have to type:
Portable-Python.exe Ex16.py Python.txt
at your command prompt. To get a command prompt, press WindowsKey-R, then type "cmd" and press enter. You should now be looking at something like c:\>. Navigate to your portable python installation by using the cd command.

Categories

Resources