Python unexpected EOF while parsing : syntax error - python

I am trying to do a simple toto history with a dictionary and function however I have this funny syntax error that keeps appearing that states "unexpected EOF while parsing" on the python shell when I try to runs it. I re-looked over and over however I cannot find the error. I used input for input of integers therefore I do not think that the problem might lie with the input or raw_input. Please help me ! Below are my codes and the error on the python shell.
options()
choice = input ("Enter your choice: ")
print
while choice != -1:
if choice == 1:
print("Choice 1")
for key in toto_book:
print key + "\t" + "Day: " + toto_book[key][0] + '\t' + 'Winning Numbers: ' + str(toto_book[key][1] + 'Additional Number: ' + toto_book[key][2]
elif choice == 2:
print("Choice 2")
draw = raw_input("Enter draw date(dd/mm/yy): ")
if draw in toto_book:
print (draw + "\t" + "Day: " + toto_book[draw][0] + "\t" + "Winning Numbers: " + str(toto_book[draw][1]) + 'Additional Number: ' + toto_book[draw][2])
else:
print draw + ' cannot be found.'
There is a syntax error at the elif choice == 2: line.

Updated
As pointed out by #cricket_007, this answer is based on the false assumption that Python 3 is being used. Actually, Python 2 is being used and the only serious problem is that the call to str is missing a closing parenthesis.
You are using Python 3 in which print is a function, not a statement (as it is in Python 2).
This is the line causing the problem:
print key + "\t" + "Day: " + toto_book[key][0] + '\t' + 'Winning Numbers: ' + str(toto_book[key][1] + 'Additional Number: ' + toto_book[key][2]
Add parentheses to make print a function call, i.e. print(...):
print(key + "\t" + "Day: " + toto_book[key][0] + '\t' + 'Winning Numbers: ' + str(toto_book[key][1]) + 'Additional Number: ' + toto_book[key][2])
Also, the call to str() was missing the closing parenthesis.
There is a similar problem on line 15.
Other problems:
input() returns a string, not an integer so your if choice ==
statements will never be true. Either convert choice to an integer
with choice = int(choice) after the input(), or use a string in
the if statements, e.g. if choice == '1'.
The while loop is infinte, and unnecessary for the code shown (perhaps it is a work in progress?).

Related

String handling in Python

I am trying to write a short python function to break a long one_line string into a multi_line string by inserting \n. the code works fine when i simply insert \n into the string but i get an index out of range error when i insert a conditional check to add hyphenation as well. Here is the code that i have written.
Sentence = "Python string comparison is performed using the characters in both strings. The characters in both strings are compared one by one. When different characters are found then their Unicode value is compared. The character with lower Unicode value is considered to be smaller."
for i in range(1, int(len(Sentence)/40)+1):
x = i*40
Sentence = Sentence[:x] + "\n" if Sentence[x] == " " else "-\n" + Sentence[x:]
print(Sentence)
Here is the error message i get.
Traceback (most recent call last):
File "/media/u1/data/prop.py", line 4, in <module>
Sentence = Sentence[:x] + "\n" if Sentence[x] == " " else "-\n" + Sentence[x:]
IndexError: string index out of range
The conditional expression is greedy, parsed as if you had written
Sentence = Sentence[:x] + \
("\n" if Sentence[x] == " " else "-\n" + Sentence[x:])
As a result, you are doing one of two operations:
Sentence[:x] + '\n' if you find a space
Sentence[:x] + "-\n" + Sentence[x:] if you find a different character.
Note that case 1 shortens your sentence incorrectly, but your range object is based on the original correct list.
The solution is to use parentheses to define the conditional expression correctly:
for i in range(1, int(len(Sentence)/40)+1):
x = i*40
c = Sentence[x]
Sentence = Sentence[:x] + (f"\n" if c == " " else f"{c}-\n") + Sentence[x+1:]
# ^ ^
Well the issue might not be obvious in the start but when you start looking at the if statement in the middle of string concatenation, you will understand. For a minute just focus on the following line:
Sentence = Sentence[:x] + "\n" if Sentence[x] == " " else "-\n" + Sentence[x:]
Python would parse this statement like so:
Sentence = (Sentence[:x] + "\n") if Sentence[x] == " " else ("-\n" + Sentence[x:])
Notice the brackets carefully. This is exactly the reason why the length of the string held by the variable Sentence is decreasing after each iteration which triggers the IndexError exception. Hence, in order to address this issue, we will have to explicitly tell Python what we are expecting. So, it could be written as such:
Sentence = Sentence[:x] + ("\n" if Sentence[x] == " " else "-\n") + Sentence[x:]
string = "Python string comparison is performed using the characters in both strings. The characters in both strings are compared one by one. When different characters are found then their Unicode value is compared. The character with lower Unicode value is considered to be smaller."
stc = ""
for j in range(1 + len(string) // 40):
stc += string[j * 40:40 * (j + 1)] + "\n"
print(stc)

How to make last element of list finish with a dot and the others with a comma?

I made this list with a for loop that points errors when yoy choose a name. I'd like to know how can I make it so that the last line finishes with '.' and the others finish with ';'.
while True:
if len(errors_list) != 0:
print("Your name has thesse errors::")
for i in errors_list:
print(" " + str(errors_list.index(i) + 1) + "- " + i + ".")
print("Try again.")
errors_list.clear()
name = input("My name is ").title()
choose_name(name)
else:
print("Nice to meet you, " + fname + " " + sname + ".")
break
Result when I type a name like '--- ':
Your name has these errors:
1- It has no letters.
2- It has symbols.
3- The last letter is a space.
Try again.
My name is
I'd like to make it so that 1 and 2 finish with ';' and 3 with '.'. Thanks!
All the existing solutions so far seem pretty poor, this is as print is expensive to call.
errors_list.index(i) runs in O(n) time making your solution run in O(n^2) time. You can improve this, to O(n) time, by using enumerate.
You can also think of what you're doing simply as concatenating values of a list and adding a period.
I would use:
errors = [f' {i}- {error}' for i, error in enumerate(errors_list, 1)]
print(';\n'.join(errors) + '.')
Extending Roman Perekhrest's answer, enumerate has an optional parameter start:
errors_list = ['It has no letters', 'It has symbols', 'The last letter is a space']
for i, err in enumerate(errors_list, start=1):
print("\t{}- {}{}".format(i, err, ';' if i < len(errors_list) else '.'))
additionaly with Python 3.6+ you can use f-strings instead of format:
errors_list = ['It has no letters', 'It has symbols', 'The last letter is a space']
for i, err in enumerate(errors_list, start=1):
print(f"\t{i}- {err}{';' if i < len(errors_list) else '.'}")
Instead of:
for i in errors_list:
print(" " + str(errors_list.index(i) + 1) + "- " + i + ".")
do
s = len(errors_list)
for e, i in enumerate(errors_list):
ending = ";" if e + 1 < s else "."
print(" " + str(errors_list.index(i) + 1) + "- " + i + ending)
EDIT:
to those jumping to the gun - OP did write in a title comma, but he used semicolon (;) twice (!) in a question itself.
Simply with enumerate function:
errors_list = ['It has no letters', 'It has symbols', 'The last letter is a space']
...
for i, err in enumerate(errors_list):
print(" {}- {}{}".format(i+1, err, ';' if i+1 != len(errors_list) else '.'))
The crucial loop will output:
1- It has no letters;
2- It has symbols;
3- The last letter is a space.

How do I get parentheses around my variable? [duplicate]

This question already has answers here:
Print Combining Strings and Numbers
(6 answers)
Closed 4 years ago.
I'm doing one of my first assignments and I can't find out how to put parentheses around a variable when I go to print it.
I've tried
(xs)
{xs}
[xs}
But none get parentheses around it
(print)("Hello user! Welcome to the program!")
name = input("What is your name?")
(print)("Hello", name)
x = input("What is your favorite number?")
y = int(x) // 2
xs = str(x)
ys = str(y)
z = ("Did you know that half of your favorite number" + ' ' + xs + ' ' + 'is' + ' ' + ys + '?')
print(z)
For the 2nd to last line of code I want it to say Did you know that half of your number (5) is 2?
5 is just an example number but I want it in parentheses!
Do it like so:
z = ("Did you know that half of your favorite number" + ' (' + xs + ') ' + 'is' + ' ' + ys + '?')
you just need to add the pharentesis in the right place, something like this:
z = ("Did you know that half of your favorite number" + ' (' + xs + ') ' + 'is' + ' ' + ys + '?')
I am not exactly sure if that is what you need but you just have to concat "(" and ")" around your variable.
>>> y = "number"
>>> print ( "(" + y + ")" )
(number)

How to style long lines in python using Google python style and pylint?

I am trying to clean up my code for an assignment by running pylint over it with the google python style rc file. I just want to confirm that this is the correct style for the the first print line, as it look pretty weird, but the google style rcfile is showing that it is the correct style. I know that the length of each line mustn't exceed 80 characters
for position, length in STEPS:
guess = prompt_guess(position, length)
score = compute_score(guess, position, word)
total = + total + score
print("Your guess and score were: " + ('_' * position + str(guess) +
('_' * (len(word) - length -
position))) + " : " +
str(score))
print("")
I would've formatted it like this:
for position, length in STEPS:
guess = prompt_guess(position, length)
score = compute_score(guess, position, word)
total = + total + score
print("Your guess and score were: " + ('_' * position + str(guess) +
('_' * (len(word) - length -position))) + " : " + str(score))
print("")
Any clarification would be appreciated, thanks
You shouldn't build your string inside print.
When it comes to a very long message, take several steps to build it.
s = "Your guess and score were: "
s += '_' * position
s += str(guess)
s += '_' * (len(word) - length - position)
s += " : "
s += str(score))
You can make it a bit cleaner by using the str.format method.
The parameters will replace the curly braces, according to the names given:
pad1 = '_' * position
pad2 = '_' * (len(word) - length - position)
s = "Your guess and score were: {pad1}{guess}{pad2} : {score}"
s = s.format(pad1=pad1, pad2=pad2, guess=guess, score=score)
This allows you to indent the parameters as a listing, in case their names are long:
s = s.format(pad1=pad1,
pad2=pad2,
guess=guess,
score=score)
If the definition of each parameter is short enough, you can send it to the format method:
s = "Your guess and score were: {pad1}{guess}{pad2} : {score}"
s = s.format(pad1='_' * position,
pad2='_' * (len(word) - length - position),
guess=guess,
score=score)
If your string has a lot of values to be interpolated, you can get rid of the variable names, but then, the curly braces will be replaced by the parameters in the same order:
s = "Your guess and score were: {}{}{} : {}"
s = s.format(pad1, guess, pad2, score)
See PEP-8 on indentation:
# YES: Aligned with opening delimiter.
foo = long_function_name(var_one, var_two,
var_three, var_four)
# NO: Arguments on first line forbidden when not using vertical alignment.
foo = long_function_name(var_one, var_two,
var_three, var_four)
(Consistent with Google Python Style Guide on indentation.)
Also, should a line break before or after a binary operator?:
# NO: operators sit far away from their operands
income = (gross_wages +
taxable_interest +
(dividends - qualified_dividends) -
ira_deduction -
student_loan_interest)
# YES: easy to match operators with operands
income = (gross_wages
+ taxable_interest
+ (dividends - qualified_dividends)
- ira_deduction
- student_loan_interest)
Correct, indentation depends on previous line's parentheses. But readability is more than just passing pylint, consider:
print("Your guess and score were: {PAD1}{GUESS}{PAD2} : {SCORE}"
"".format(PAD1='_' * position,
GUESS=guess,
PAD2='_' * (len(word) - length - position),
SCORE=score))
(Use of string concatenation makes for easier formatting of longer strings.)

Annoying spaces that won't disappear. What should I do?

I am currently making a game with Python.
I want the code to read:
[00:00:00] Name|Hello!
Here is my code:
print(Fore.YELLOW + Style.BRIGHT + '['),
print strftime("%H:%M:%S"),
print ']',
print(Style.BRIGHT + Fore.RED + ' Name'),
print(Fore.BLACK + '|'),
print(Fore.WHITE + Style.DIM + 'Hello!')
time.sleep(5)
Instead - for some reason - it becomes like this:
[ 00:00:00 ] Name | Hello!
I have no idea what's wrong with this code, or how to fix it.
I would really appreciate all the help I can get! Thank you.
Printing with a single print statement and a comma always prints a trailing space.
Either use one print statement with everything concatenated, or use sys.stdout.write() to write to the terminal directly without the extra spaces:
print Fore.YELLOW + Style.BRIGHT + '[' + strftime("%H:%M:%S") + ']',
or
sys.stdout.write(Fore.YELLOW + Style.BRIGHT + '[')
sys.stdout.write(strftime("%H:%M:%S"))
sys.stdout.write(']')
or use string formatting:
print '{Fore.YELLOW}{Style.BRIGHT}[{time}] {Style.BRIGHT}{Fore.RED} Name {Fore.BLACK}| {Fore.WHITE}{Style.DIM}Hello!'.format(
Style=Style, Fore=Fore, time=strftime("%H:%M:%S"))
Another option is to use the end="" option to print(). This prints no linefeed and also does not add the extra space at the end.
print(Style.BRIGHT + Fore.RED + ' Name', end="")
print(Fore.BLACK + '|', end="")
print(Fore.WHITE + Style.DIM + 'Hello!')
The caveat being that the end option is only available with Python 3. It's also available in Python 2.6-ish if you from __future__ import print_function

Categories