Python 2.7, unexpected EOF while parsing - python-2.7

I am a newbie to Python and I was trying my hand at the following problem: I want to add numbers entered by the user. Here is my program
add = 0
num = input('Enter a number:')
add = add + num
while num != ' ' :
num = input('Next number:')
add = add + num
print add
I want to terminate the program when a blank is entered. So I know the problem is with line 4. What would be the correct syntax?
Thanks in advance for your help

In python 2.7 user input should be processed using raw_input
This is because input is semantically equivalent to:
eval(raw_input(prompt))
which, when given an empty string, will cause the following line of code:
eval('')
will return an EOF error while parsing, since empty is not a valid object to parse.
Since raw_string doesnt parse the string into an int you'll also have to use int() to convert it when you do the addition.
You also need to change to while statement:
add = 0
num = raw_input('Enter a number:')
# you cant do a + here what if the user hits enter right away.
if num:
add = int(num)
while num: # enter will result in a null string not a space
num = raw_input('Next number:')
if num:
add = add + int(num)
print add

Try following and read a bit.
>>> help(input)
>>> help(raw_input)
>>> s=raw_input()
<return right here>
>>> s
''
>>> s=raw_input()
<one space followed by return here>
>>> s
' '
>>>

Related

Text processing to get if else type condition from a string

First of all, I am sorry about the weird question heading. Couldn't express it in one line.
So, the problem statement is,
If I am given the following string --
"('James Gosling'/jamesgosling/james gosling) , ('SUN Microsystem'/sunmicrosystem), keyword"
I have to parse it as
list1 = ["'James Gosling'", 'jamesgosling', 'jame gosling']
list2 = ["'SUN Microsystem'", 'sunmicrosystem']
list3 = [ list1, list2, keyword]
So that, if I enter James Gosling Sun Microsystem keyword it should tell me that what I have entered is 100% correct
And if I enter J Gosling Sun Microsystem keyword it should say i am only 66.66% correct.
This is what I have tried so far.
import re
def main():
print("starting")
sentence = "('James Gosling'/jamesgosling/jame gosling) , ('SUN Microsystem'/sunmicrosystem), keyword"
splited = sentence.split(",")
number_of_primary_keywords = len(splited)
#print(number_of_primary_keywords, "primary keywords length")
number_of_brackets = 0
inside_quotes = ''
inside_quotes_1 = ''
inside_brackets = ''
for n in range(len(splited)):
#print(len(re.findall('\w+', splited[n])), "length of splitted")
inside_brackets = splited[n][splited[n].find("(") + 1: splited[n].find(")")]
synonyms = inside_brackets.split("/")
for x in range(len(synonyms)):
try:
inside_quotes_1 = synonyms[x][synonyms[x].find("\"") + 1: synonyms[n].find("\"")]
print(inside_quotes_1)
except:
pass
try:
inside_quotes = synonyms[x][synonyms[x].find("'") + 1: synonyms[n].find("'")]
print(inside_quotes)
except:
pass
#print(synonyms[x])
number_of_brackets += 1
print(number_of_brackets)
if __name__ == '__main__':
main()
Output is as follows
'James Gosling
jamesgoslin
jame goslin
'SUN Microsystem
SUN Microsystem
sunmicrosyste
sunmicrosyste
3
As you can see, the last letters of some words are missing.
So, if you read this far, I hope you can help me in getting the expected output
Unfortunately, your code has a logic issue that I could not figure it out, however there might be in these lines:
inside_quotes_1 = synonyms[x][synonyms[x].find("\"") + 1: synonyms[n].find("\"")]
inside_quotes = synonyms[x][synonyms[x].find("'") + 1: synonyms[n].find("'")]
which by the way you can simply use:
inside_quotes_1 = synonyms[x][synonyms[x].find("\x22") + 1: synonyms[n].find("\x22")]
inside_quotes = synonyms[x][synonyms[x].find("\x27") + 1: synonyms[n].find("\x27")]
Other than that, you seem to want to extract the words with their indices, which you can extract them using a basic expression:
(\w+)
Then, you might want to find a simple way to locate the indices, where the words are. Then, associate each word to the desired indices.
Example Test
# -*- coding: UTF-8 -*-
import re
string = "('James Gosling'/jamesgosling/james gosling) , ('SUN Microsystem'/sunmicrosystem), keyword"
expression = r'(\w+)'
match = re.search(expression, string)
if match:
print("YAAAY! \"" + match.group(1) + "\" is a match 💚💚💚 ")
else:
print('🙀 Sorry! No matches! Something is not right! Call 911 👮')

Storing incorrect passwords on .txt file - Python 2.7

I am creating a python program which stores it in a list, then records in a text file called wrongpasswords.txt.
The program should ask the user for input by saying 'Please enter your password: '. The correct password will always be 'rusty' but the user can of course enter any String. And also, how do I add to my program that the number of characters the user inputs wrong is also stored for each incorrect password?
Please do mind me as I am a beginner in programming and python.
Please see my code below:
enteredPass = raw_input("Enter your password: ")
incorrectPass= file("wrongpasswords.txt","w")
counter = 0
for i in range(0, counter+1):
if enteredPass != "rusty":
counter = counter +1
incorrectPassO = open("wrongpasswords.txt","w")
incorrectPassO.write("Incorrect password" +str(counter)+": " + enteredPass + "\n")
incorrectPassO.close()
enteredPass = raw_input("Enter your password: ")
else:
incorrectPassO = open("wrongpasswords.txt","w")
incorrectPassO.write("Correct password entered on the " + str(counter)+"th entry")
incorrectPassO.close()
If I understood correctly you're trying to create a simple login program that counts the wrong login attempts? This should work:
counter = 0
correct_answer_entered = False
while not correct_answer_entered:
enteredPass = raw_input("Enter your password: ")
counter = counter + 1
if enteredPass != "rusty":
incorrectPassO = open("wrongpasswords.txt","a")
incorrectPassO.write("Incorrect password" +str(counter)+": " + enteredPass + "\n")
incorrectPassO.close()
else:
incorrectPassO = open("wrongpasswords.txt","a")
incorrectPassO.write("Correct password entered on the " + str(counter)+"th entry")
incorrectPassO.close()
correct_answer_entered = True
The points I fixed in your code that you should notice:
I replaced the "w" with an "a" where you open the file, since "w" makes it write over what's already wroten in the file, while "a" appends after what's there.
I replaced the for loop with a while, what you did was a range from 0 to 1, so the loop would exit after the first round, I added a boolean value (correct_answer_entered), to indicate if the correct password was entered, and keeps going if it wasn't.
I moved the "counter = counter + 1" outside of the if statement, since the number of attempts is not related to wither the password is correct or not, the way you did it if the password was correct at the first attempt it'd say 0th attempt instead of 1th.
overrall your code is pretty nice and it's good to see new people getting into programming ^.^

Getting error "NameError: name 'letter' is not defined"

I'm fairly new to python and don't know much but i tried to make a program that sees how fast it can guess a string in this case a password. I tried to create an individual variable for each letter by making a loop that sets the variable. (I added the print letter1... at the end so i can see if it works).Then when i went to test it i got this error.
letter[x] = password[x - 1:-(len(password)-1)]
NameError: name 'letter' is not defined
print "Password guesser"
password = raw_input('Enter Password (1-30 carechters only): ')
passwordLength= len(password)
for x in range(0,passwordLength):
letter[x] = password[x - 1:-(len(password)-1)]
print letter1
print letter2
print letter3
Since you're assigning letters with dictionary syntax, you may want to declare the letter variable as a dictionary: letter = {}, then output it as a dictionary. This may get you in the direction you want to go:
letter = {}
for x in range(passwordLength):
letter[x] = password[x - 1:-(passwordLength-1)]
print letter[0]
print letter[1]
print letter[2]

How to check if a value entered is an integer or string when using input

I wrote a program where you guess a randomly generated number between 1 and 100:
from random import randint
play='y'
print 'Guess a number between 1 and 100'
while play=='y':
x = randint(1,100)
guess=1000
while guess != x:
guess=input('Guess: ')
if guess < x:
print 'Higher'
if guess > x:
print 'Lower'
print 'You got it! Good Job! The number was ' + str(x)
play=raw_input('Would you like to play again(y/n)?: ')
raw_input("Press <enter> to exit")
when the user enters a guess that is not an integer how do I print That is not a number, then allow them to continue guessing?
Use a while True loop to repeat the question until it breaks. Only way to break the loop is if try does not raise a ValueError. int() raises an error when it gets something like 'hello' or '1.2'.
Also, use raw_input instead of input (note: raw_input assigns a string to guess).
while True:
guess=raw_input('Guess: ')
try:
int(guess)
break
except ValueError:
print '\nNot an int, try again.'
More specifically, insert this after while guess != x: and before if guess < x.

NZEC in python on spoj for AP2

I wrote the following two codes
FCTRL2.py
import sys;
def fact(x):
res = 1
for i in range (1,x+1):
res=res*i
return res;
t = int(raw_input());
for i in range (0,t):
print fact(int(raw_input()));
and
AP2.py
import sys;
t = int(raw_input());
for i in range (0,t):
x,y,z = map(int,sys.stdin.readline().split())
n = (2*z)/(x+y)
d = (y-x)/(n-5)
a = x-(2*d)
print n
for j in range(0,n):
sys.stdout.write(a+j*d)
sys.stdout.write(' ')
print' '
FCTRL2.py is accepted on spoj whereas AP2.py gives NZEC error. Both work fine on my machine and i do not find much difference with regard to returning values from both. Please explain what is the difference in both and how do i avoid NZEC error for AP2.py
There may be extra white spaces in the input. A good problem setter would ensure that the input satisfies the specified format. But since spoj allows almost anyone to add problems, issues like this sometimes arise. One way to mitigate white space issues is to read the input at once, and then tokenize it.
import sys; # Why use ';'? It's so non-pythonic.
inp = sys.stdin.read().split() # Take whitespaces as delimiter
t = int(inp[0])
readAt = 1
for i in range (0,t):
x,y,z = map(int,inp[readAt:readAt+3]) # Read the next three elements
n = (2*z)/(x+y)
d = (y-x)/(n-5)
a = x-(2*d)
print n
#for j in range(0,n):
# sys.stdout.write(a+j*d)
# sys.stdout.write(' ')
#print ' '
print ' '.join([str(a+ti*d) for ti in xrange(n)]) # More compact and faster
readAt += 3 # Increment the index from which to start the next read
The n in line 10 can be a float, the range function expects an integer. Hence the program exits with an exception.
I tested this on Windows with values:
>ap2.py
23
4 7 9
1.6363636363636365
Traceback (most recent call last):
File "C:\martin\ap2.py", line 10, in <module>
for j in range(0,n):
TypeError: 'float' object cannot be interpreted as an integer