EDIT: Reminder, before you ask a stupid question on Stackoverflow, be sure to check all braces, semicolons and parentheses!
ORIGINAL POST:
I'm switching from C to python and have a hopefully rather basic question: Why does this return an unexpected EOF while parsing error?
A little background:
This is supposed to check if a credit card number is valid according to Luhn’s algorithm.
number = input("Number: ", end="")
numArray = []
for i in number:
numArray.append(int(i))
firstTime = 0;
secondTime = 0;
cycle2 = 0
for cycle in range(15):
if(cycle % 2 != 0):
firstTime += numArray[cycle]*2
else:
secondTime += numArray[cycle2]
cycle2 += 1
print("{} and {}".format(firstTime, secondTime)
That's because you're missing a trailing ) in the call to print, and the Python interpreter doesn't expect that:
print("{} and {}".format(firstTime, secondTime)
^
Fix it to print("{} and {}".format(firstTime, secondTime))
Related
My code will always take the first input despite the input. I have tried taking guess and making guess into an int but that leads to both if statements to trigger
x = 1
answer = 4
A=0
guess = 0
while A < 10:
for _ in range (5):
x = random.randint(1,5)
print ("Ralph holds up " + str(x) + " fingers what is the answer")
guess=input()
if guess != answer:
print("WRONG PROGRESS RESET")
A=0
answer = x
if guess == answer:
A += 1
print ("correct")
print ("You have " + str(A) + " out of 10 finished")
answer = x
print ("You win congrats")
First off your code never even import random to use randint. But I'll assume you did import it and you just never pasted it in.
input reads your input as a str, but you want it to read as an int. All you really need to do is wrap the input() call in an int invocation. Additionally, input takes an argument, which prompts that argument in the console.
Also #tobias_k has a good point, but instead of elif guess == answer:, just use else:.
I also changed some variable logic, and I changed A to a much more meaningful identifier, as well as fixing formatting, like a = b is more aesthetically pleasing than a=b.
Oh and indentation. Indentation is important, not only for readability, but in Python, it's required. Python is whitespace significant, meaning scope delimiters are whitespace.
import random
finished_count = 0
while finished_count < 10:
for _ in range(5):
answer = random.randint(1, 5)
guess = int(input("Ralph holds up %d finger%s. What is the answer?\n" % (answer, "" if answer == 1 else "s")))
if guess != answer: # incorrect answer
print("WRONG PROGRESS RESET")
finished_count = 0
else: # correct
finished_count += 1
print("Correct. You have %d out of 10 finished" % finished_count)
print("You win, congrats!")
I just used this code up until I got to 10 and it works fine
import time
import random
info = """welcome to contest!..
pls answer question as quick as possible you can
pls enter small letter...\n"""
print(info)
questions = {"2 * 2 ?":"4",
"what is the capital city of turkey?":"ankara",
"what is the king of jungle?":"lion",
"what is the meaning of book in turkish language?":"kitap",
"who is the foundation of turkish government":"atatürk",
"what is the most popular drink in turkey?":"raki",
"pls tell us a hero as comic":"temel"}
correct = 0
wrong = 0
blank = 0
current_time = time.time() #system time
allowed_time = 25 #total time to reply the question
for i in random.sample(list(questions), 5):
question = questions[i]
if time.time() < current_time+allowed_time:
answer = input("1. soru --> {} : ".format(i))
if answer == question:
correct += 1
elif answer == "":
blank += 1
else:
wrong += 1
print()
print("right answer :", correct)
print("wrong answer :", wrong)
print("blank answer :", blank)
Please see my survey code above. It's selecting random 5 question in total time 25 seconds. But, I'd like to make it time option for every single question.
For example, questions must be replied with in ten seconds otherwise change question automatically.
Could you help on how to do that?
here's the steps to proceed(algorithm):
Add a timer to each question.
Run a counter or a timer inside the for loop, then, for every iteration passed, store the time in a variable x, check if x is less than 10.
Check whether it is answered within 10 seconds.
Iterate to the Next question, this i+1.
If NOT, jump to the next question.
The input() function - by its definition - waits for the input infinitely. Probably there is no cross-platform solution for it.
For *nix operating systems you may do this:
Create another thread with the timer which will interrupt the main thread after some time limit.
You may define a function for your input which will do it:
import thread # _thread for Python 3.x
import threading
def timed_input(prompt, timeout=25.):
timer = threading.Timer(timeout, thread.interrupt_main)
answer = ""
try:
timer.start()
answer = input(prompt)
except KeyboardInterrupt:
pass
timer.cancel()
return answer
and then use it instead of the standard input() function in your code (and of course without your original attempts with the time module).
Probably the most simple and the most elegant (from the programmer's point of view) is simply to keep infinitely time for an answer but then reject it if it was answered after the given time limit:
start_time = time.time()
answer = input("1. soru --> {} : ". format(i))
if time.time() - start_time > allowed_time:
# code for rejecting the answer
So instead of your for loop use this (a tested one, and with an improvement):
for j, i in enumerate( random.sample(list(questions), 5) ): # Slight change
question = questions[i]
start_time = time.time()
answer = input("{}. soru --> {} : ". format(j + 1, i)) # Sligth change
if time.time() - start_time > allowed_time:
print(" Time-out: You didn't answer quickly enough.")
answer = ""
if answer == question:
correct += 1
elif answer == "":
blank += 1
else:
wrong += 1
Not that I slightly changed your for statement and the answer = ... for the sake of printing correct ordinal numbers of questions (yours were always 1.)
My Error
Python throws a syntax error pointed at the last "e" of "else:", preceded by an if statement and inside a while loop.
My Objective
Test if certain parameters are true, if true then go to the beginning of the loop and if not true then perform certain statements and increment a value.
My Source Code
from random import randint
def returnDigRoot(num):
digs = []
while len(str(num)) != 1:
num = str(num)
for each in num:
digs.append(each)
num = int(num)
digs = [int(i) for i in digs]
num = sum(digs)
return(num)
def rnum():
return(randint(1,99999))
ran_nums = []
sols = []
it = 1
The problem area is here
while it <= 3:
print("Generating numbers")
current = randint(1,99999)
print("randomly intializing the 'current' int value")
print("testing if the digital root is greater than 6")
if returnDigRoot(current) > 6:
print("going back to start of loop")
continue
print("testing if it isnt")
else:
ran_nums.append(current)
print("append 'current' to ran_nums")
sols.append(returnDigRoot(current))
print("appending its digital root to sols")
it += 1
print("incrementing the iterator variable")
My Research
I looked at many questions on StackOverflow and other sites and could not find a solution to my problem; most problems people had with else statements were related to tabbing errors, preceding errors (which I checked for), no preceding if statement, or multiple else statements.
Thanks in advance for any help.
print("testing if it isnt") needs to be indented. As it stands, your code doesn’t really relate the if with the else because of the indentation. It’s like writing something like this in C:
if(<condition>)
{
<action>
}
prinf(...)
else
{
<action>
}
Just align the print line with the rest of the code under the if statement.
The line:
print("testing if it isnt")
isn't indented correctly. You can't have anything in between an if block and the else block.
Your statement:
print("testing if it isnt")
is indented to the wrong level; that makes the else: that follows an independent statement, which is syntactically wrong. Probably you meant that print statement to follow the else and be indented one level.
This is most likely a indentation/space/tabbing issue since I copy pasted the code and I don't get any errors. Though I am on Python 2.7.10. (Repasting it here to ensure you can copy paste the same and try):
from random import randint
def returnDigRoot(num):
digs = []
while len(str(num)) != 1:
num = str(num)
for each in num:
digs.append(each)
num = int(num)
digs = [int(i) for i in digs]
num = sum(digs)
return(num)
def rnum():
return(randint(1,99999))
ran_nums = []
sols = []
it = 1
while it <= 3:
current = randint(1,99999)
if returnDigRoot(current) > 6:
continue
else: # this is where the error is pointed
ran_nums.append(current)
sols.append(returnDigRoot(current))
it += 1
On an unrelated note, that while loop will take a long time to exit since the exit criteria is very small (two current <=36 only will cause exit).
I have attempted to search for similar problems, but have come up short. I'm attempting to get a while loop to stop upon the input 'done'. No matter what I do or how I format it, it either won't stop the loop, or it prints the value I have assigned to 'done'. If I run it without an assignment it throws a 'NameError: name 'done' is not defined'. If I assign a value to it, it won't end the loop. I am not asking for code optimization or help with anything else, but I would truly appreciate it if someone could explain why this is happening.
Counter1 = 0
Counter2 = 0
Counter3 = 0
Counter4 = 0
n = 0
while True: #Begins a loop that runs until manually ended.
n = input("Enter desired scores, and type done when complete: ")
if n == "done": #Closes the loop if given this input.
break
else:
n = int(n) #changes input to an integer
if n >= 0 and n <= 25: #increments the counters depending on the input
Counter1 = Counter1 + 1
elif n > 25 and n <= 50:
Counter2 = Counter2 + 1
elif n > 50 and n <= 75:
Counter3 = Counter3 + 1
else:
Counter4 = Counter4 + 1
You're using Python 2. input immediately tries to convert your input into a Python type, which is dangerous and causes problems like the one you are experiencing. Use raw_input instead.
In other words, when you type "done", input tries to eval* it, comes up with a non-existent variable named "done", and bails out complaining. If you use raw_input instead, it will give you a string, which you can properly cast into a different type as desired, or as in your case, leave it alone since a string is what you want.
* This is about JavaScript but eval appears in many programming languages.
I've been tasked with making a Quiz app for a school project. It's meant to ask the user how many questions they want, and they then enter all of the Q&A's. Once finished, someone will then take the test.
The problem is, I'm getting an IndexError from the results function. This function is supposed to compare the test answers with the user's answers and print out a score.
def results(testAnswers, userAnswers):
score = 0
for i in range(0, len(answers)):
if testAnswers[i].lower().strip() == userAnswers[i].lower().strip():
score += 1
print("\nResults: You got " + str(score) + " out of " + str(len(answers)) + "!")
Does anyone know how I can fix this problem?
Your problem is here:
while n < times:
if user_answers[n] == answer_list[n]:
score += 1
n += 1
if user_answers[n] != answer_list[n]:
n += 1
Lets say times is 10, and n is 9, it executes, and n+=1 makes it 10. Most likely, you have 10 elements in the array (note 10 is an example), and now user_answers[10 raises an exception, as the valid varles are 0..9
To fix this issue, use elif:
while n < times:
if user_answers[n] == answer_list[n]:
score += 1
n += 1
elif user_answers[n] != answer_list[n]:
n += 1
Alternate approach is to get rid of the else clause altogether,
while n < times:
if user_answers[n] == answer_list[n]:
score += 1
n += 1
Note that there are quite a few places you could optimize the code, but I am just going to leave the answer here, and let you figure other things out yourself.
Perhaps copying your code into this site went wrong, but regardless the code is not correctly formatted here which makes it very difficult to read.
regardless, its clear that you are indexing into a list to a point that doesn't exist. to help track down this error, add this line after you start your while loop:
print 'n %s, times %s, user_answers %s, answer_list %s' % (n, times, user_answers, answer_list)
then run the program and paste the output of the program into your question (but first please correct the indenting)
Due to an unknown reason, the testAnswers and userAnswers weren't in equal length. The lesson here is to always make sure they are the same length.
A simple if-statment can prevent the entire error.
if len(answers) != len(userAnswers):
return