Syntax error on else in my quiz - syntax

I'm new to a program called Pythonista. I'm doing a quiz and when I try to test it I get a syntax error.
Here is the error:

Your else indentation is not proper at line number 10
your code with proper indentation:
def quiz():
score = 0
begin = raw_input("do you want to start ?")
if begin == "yes":
print "A : 56"
print "B : 48"
print "C : 45"
q1 = raw_input("what is 12*4")
if q1 in ["b","B"]:
print "congrats !! well done!1"
score += 1
else:
print "sorry!! you are wrong try next one !! good luck"
print "A : Another ice age"
print "B : A meteor will hit the earth"
print "C : Aliens will invade earth"
q2 = raw_input("what will happen in 50 years?")
if q2 in ["a","A"]:
print "nice !! keep going!1"
score += 1
else:
print "sorry!! you are wrong try next one !! good luck"
return score
else:
print "ok bye"
return 0
This is just an edit on top of your code. But I won't suggest this approach as you are writing same code for both question again and again.Instead of that I will suggest to use one proper data structure and loop through that then it will be dynamic enough to do more quiz.You can use one array of dictionary like this-
[{"question":"what is 5*4 ?","options":[10,20,30],"answer_index":1},{"question":"what is 10*4 ?","options":[40,50,60,30],"answer_index":0}]

I'm not familiar with Pythonista, but, from a quick search, it uses significant white-space. In which case, your else is indented when it should be at the same level as its corresponding if. There are further errors like this later on.
See here for more details: http://omz-software.com/pythonista/docs/tutorial/controlflow.html

Related

Is there any difference between the terms line of code and statement?

Is there any difference between the terms 'line of code' and 'statement' in programming languages?
Yes, check following:
int a =0;
while(a<100)
{
cout<<
"Is it ok"<<
a <<
"is the current value of 'a'"<<endl;
a++;
}
Above code snippet is having:
Line of code: 9
Simple Statements: 3
Compound Statements: 1
Line of code is basically how many end points you are using. A Statement is the group of code that you produce to create an expected output.
For example in a conditional statement using if else, you can right that in multiple line of core or using only one line via Ternary method.
Sample:
if($var == 0) {
echo "this is zero";
} else {
echo "not a zero";
}
that basically created 5 line of code. In ternary you can go like this
$var == 0 ? echo "this is zero" : echo "not a zero";
As you see the result is the same only it is created in 1 line of code.
Hope this helps you moving forward
Lines of code presumably refers to lines of content in a source file, i.e. the number of lines in a file. On the other hand, a given statement of code can, and often does, exceed a single line. For example, consider the following Java statement from the Javadoc for streams:
int sum = widgets.stream()
.filter(b -> b.getColor() == RED)
.mapToInt(b -> b.getWeight())
.sum();
One statement spans four physical lines in the editor. However, we could inline the whole thing into a single line.

Printing in while loop, clearing previous iteration prints

I have the following code:
print("Hi there!")
def inputyournumber():
while True:
num = input("your number is?:")
if int(num) <100:
break
return
The output is:
Hi there!
your number is?: 101
your number is?: 1002
your number is?: 100
your number is?: 99
i just want the initial prints: and the final output until a correct input is entered:
Hi there!
your number is?: 99
Erasing the initially wrong inputs, but keeping the prints prior the loop. Is it possible? Or do i have to reprint them? My issue in just clearing everything then reprint the prior texts together with the correct input is that it may consume more time for more complex part of the code with similar problem.
Do you mean it only print out the number you entered when the number you enter is 100?
First, the input you get, will be a string, so the comparison won't work.
maybe this is what you wanted?
def printnum():
while True:
print('Hi there!')
num = input("your number is: ")
if num != '100':
continue
break
print(num)
printnum()

Difference between random.randint and random.sample

I have read the documentation for each and find it a bit hard to comprehend the differences here. I wrote this code using random.sample:
import random
print "Welcome to the guessing game."
number_of_guesses = 1
correct_number = random.sample(range(1,101),1)
while number_of_guesses < 999:
user_choice = int(input("Guess a number between 1 and 100: "))
if user_choice == correct_number:
print "You guessed the number in %s tries." % number_of_guesses
elif user_choice < correct_number:
print "Too low, guess again."
number_of_guesses += 1
elif user_choice > correct_number:
print "Too high, guess again."
number_of_guesses += 1
When i run this code and enter a number i get "Too low, guess again." regardless of what number I enter, yet when i use random.randomint it works correctly. Can anyone explain why this happens?
random.sample(range(1,101),1) will return a singleton list containing an integer, whereas random.randint(1,100) will directly return the integer itself. Note that random.randint is an inclusive bound (i.e. it can return either of the endpoints)
You could also use random.choice(range(1, 101)) to get the integer. In any case, I'd assume that randint is the fastest option.

Infinite Loop x Counter Problems

Hello I have three problems with my code:
when I type in "N" for my first question, it goes into an error.
I get in an infinite loop after the "Run again?" input.
my counters do not add up properly so even when I get an answer right or wrong, it doesn't count them.
Please help me.
Below is my code:
#Introduction-ish print statement
print("In this application, we will be playing a coin coss game. For as "\
"many times as you like, we will continue playing the game.")
#def function1():
response=str(input("\nWould you like to run this application? Type 'Y' to run "\
"or 'N' to not run: "))
if response=="N":
print("\nOutcome of Game:")
print("You did not run the application."\
" Nothing happened. You did not play the game.")
#Counters
programCounter=0
hCounter=0
tCounter=0
guessCountR=0
guessCountW=0
#User Input
if response=="Y":
funcGuess=str(input("\nPick one- Type 'H' for Heads or 'T' for Tails: "))
#Coins
import random
#number=random.randint(1,2)
while response !="N" and funcGuess=="H" or funcGuess=="T":
number=random.randint(1,2)
if number==1:
number=="Heads"
hCounter+=1
else:
number=="Tails"
tCounter+=1
if funcGuess==number:
guessCountR+=1
else:
guessCountW+=1
print(number)
response=str(input("Run again?"))
if response=="Y":
funcGuess=str(input("\nPick one- Type 'H' for Heads or 'T' for Tails: "))
if response=="N":
print("\nOutcome of Game:")
print("You guessed ",programCounter, "time(s).")
print("You guessed heads",hCounter, "time(s).")
print("You guessed tails",tCounter, "time(s).")
print("You guessed correctly",guessCountR, "time(s).")
print("You guessed incorrectly",guessCountW, "time(s).")
#Guess Count
guessCount=guessCountR+guessCountW
#paste
#if response =="Y":
#function1()
#else:
#print("\nOutcome of Game:")
#print("You did not run the application."\
#" Nothing happened. You did not play the game.")
I don't mind all the comments. I purposely left them there but if anyone helping finds them useful, please let me know.
Apologies in advanced for the long post.
Problem 1:
On line 34 you're evaluating a variable called funcGuess. It only gets defined on line 26 should you answer 'Y' to the initial question.
Problem 2:
The while loop loops infinitely, because break conditions can never be met. There's no way to assign response the value "N" within the loop. Also, be sure to put both sides of the or evaluation between parentheses in order to evaluate the line correctly
Problem 3:
The correct number and the guess are assigned into variables number and funcGuess, respectively. number is always 1 or 2, and funcGuess is always "H" or "T". Therefore funcGuess == number can never evaluate as True.

array within an array ruby

Input: <ArrayOfSMSIncomingMessage xmlns=\"http://sms2.cdyne.com\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"><SMSIncomingMessage><FromPhoneNumber>19176230250</FromPhoneNumber><IncomingMessageID>cf8ef62d-9169-4908-a527-891fca056475</IncomingMessageID><MatchedMessageID>6838594b-288f-4e9a-863c-3ad9f4d501ca</MatchedMessageID><Message>This is a test</Message><ResponseReceiveDate>2013-04-07T17:19:06.953</ResponseReceiveDate><ToPhoneNumber>13146667368</ToPhoneNumber></SMSIncomingMessage><SMSIncomingMessage><FromPhoneNumber>19176230250</FromPhoneNumber><IncomingMessageID>ebf11b38-c176-439a-a2d0-7a2bb35390df</IncomingMessageID><MatchedMessageID>6838594b-288f-4e9a-863c-3ad9f4d501ca</MatchedMessageID><Message>Does it wotk</Message><ResponseReceiveDate>2013-04-07T17:19:17.303</ResponseReceiveDate><ToPhoneNumber>13146667368</ToPhoneNumber></SMSIncomingMessage></ArrayOfSMSIncomingMessage>
Expected Output: [["191760250", "This is a test", "2013-04-07T17:19:06.953", "13146636 8"],["191760250", "Does it wotk", "2013-04-07T17:19:17.303", "131466368"]]
I am a newbie but i can't solve this problem or find an answer. The objective is to parse a text. The problem is that I put the information into an array b and then I put array b into array c. However, what happens is that c[0] becomes equal to c[1] even thought they should have different information. I don't know how to fix this.
data='"<ArrayOfSMSIncomingMessage xmlns=\"http://sms2.cdyne.com\" xmlns:i=\" <FromPhoneNumber>191760250</FromPhoneNumber>'
data=data+'<Message>This is a test</Message><ResponseReceiveDate>2013-04-07T17:19:06.953</ResponseReceiveDate>'
data=data+'<ToPhoneNumber>13146636 8</ToPhoneNumber></SMSIncomingMessage><SMSIncomingMessage><FromPhoneNumber>191760250'
data=data+'</FromPhoneNumber><Message>Does it wotk</Message><ResponseReceiveDate>2013-04-07T17:19:17.303</ResponseRecei'
data=data+'veDate><ToPhoneNumber>131466368</ToPhoneNumber></SMSIncomingMessage></ArrayOfSMSIncomingMessage>'
a=[['<FromPhoneNumber>','</FromPhoneNumber>'],['<Message>','</Message>'],
['<ResponseReceiveDate>','</ResponseReceiveDate>'],['<ToPhoneNumber>','</ToPhoneNumber>']]
b=[]
c=[]
d=true
ii=-1
while data.index(a[0][0])!=nil do
ii+=1
for i in 0..3
print "\ni is #{i} first term: #{a[i][0]} second term #{a[i][1]}\n"
b[i]= data[data.index(a[i][0])+a[i][0].length..data.index(a[i][1])-1]
print "b[i] is #{b[i]}\n"
end
print "b is #{b}\n"
print "c is #{c}\n"
c.push(b)
print "c is #{c}\n"
d=data.slice!(0,data.index('</SMSIncomingMessage>')+5)
print "d is #{d}\n"
print "data is #{data}\n"
end
I really don't understand what your code is trying to accomplish, but regarding what you say isn't working as you expect, (However, what happens is that c[0] becomes equal to c[1] even thought they should have different information.), the issue is that you are pushing b (which is a reference) onto c, so when you change b, you get the appearance of the contents of c changing.
Change
c.push(b)
to
c.push(b.dup)
if you want what you push onto c to stay the same even after you change b.
You are parsing XML. Don't waste time trying to manipulate strings, because all you'll do is generate fragile code.
Instead, use a real XML parser, which lets you navigate through the structure, and pick what you want.
First, your XML is malformed, but I worked around that by supplying a closing tag, turning it into damaged XML, but not fatally so.
require 'nokogiri'
xml = '<ArrayOfSMSIncomingMessage xmlns="http://sms2.cdyne.com" xmlns:i="">
<SMSIncomingMessage>
<FromPhoneNumber>191760250</FromPhoneNumber>
<Message>This is a test</Message>
<ResponseReceiveDate>2013-04-07T17:19:06.953</ResponseReceiveDate>
<ToPhoneNumber>131466368</ToPhoneNumber>
</SMSIncomingMessage>
<SMSIncomingMessage>
<FromPhoneNumber>191760250</FromPhoneNumber>
<Message>Does it wotk</Message>
<ResponseReceiveDate>2013-04-07T17:19:17.303</ResponseReceiveDate>
<ToPhoneNumber>131466368</ToPhoneNumber>
</SMSIncomingMessage>
</ArrayOfSMSIncomingMessage>'
doc = Nokogiri::XML(xml)
pp doc.search('SMSIncomingMessage').map{ |incoming_msg|
%w[FromPhoneNumber Message ResponseReceiveDate ToPhoneNumber].map{ |n| incoming_msg.at(n).text }
}
Which outputs:
[["191760250", "This is a test", "2013-04-07T17:19:06.953", "131466368"],
["191760250", "Does it wotk", "2013-04-07T17:19:17.303", "131466368"]]

Resources