-4

The validation doesnt work. im not sure why, is there a way to validate a string. The questions asked are endless i need 10 questions to be asked

import random

name=(input("Please enter your name"))
print("welcome",name,"the arithmetic is about to start")

question=0


while question<10:
    number=random.randint(1,10)
    numbers=random.randint(1,10)
    arith=random.choice("+" "-" "/")

if arith=="+":
    print(number,arith,numbers)
    answer=number+numbers





if arith=="-":
    print(number,arith,numbers)
    answer=number-numbers



if arith=="/":
    print(number,arith,numbers)
    answer=number/numbers



while True:
        try:     
            usersanswer= int(input())
        except ValueError:
            print ("That is not a valid answer")
            continue
        if usersanswer==answer:
            print("correct")
            break
    else:
        print("incorrct")

The validation doesnt work. im not sure why, is there a way to validate a string

Brad Larson
  • 170,088
  • 45
  • 397
  • 571
python
  • 7
  • 6
  • 1
    You should explain *does not work* . – Anand S Kumar Aug 26 '15 at 13:28
  • after `try`, you have `int(input())`. `input()` is always an integer--you need `raw_input()` to take a string. In other words, `useranswer` is an integer without having to use the `int()` function. Try doing `int(raw_input)` or just plain `input()` – Joseph Farah Aug 26 '15 at 13:42
  • There is no need for all the line breaks in Python. They make your code much more difficult to read. – kylieCatt Aug 26 '15 at 14:22
  • which version of python are you using? – NightShadeQueen Aug 26 '15 at 15:21
  • 1
    Please read the wikis for the tags you are using. You may think your quiz is "slick", but "slickquiz" is for a library in another language that you are not even using here. – Two-Bit Alchemist Aug 26 '15 at 15:38
  • What does it mean to you to "validate a string"? That's an extremely vague question as is - it could mean "check that a string is actually a string", or "the string is not empty", or "the string has a specific structure or content", or .... – twalberg Aug 26 '15 at 17:11
  • how to check if string is string – python Aug 27 '15 at 13:22

3 Answers3

2

I've taking silentphoenix's answer and made it somewhat more pythonic and six'ed.

You should almost never use python2's input, because on top of being massive security hole, it sometimes does things that can be...rather unexpected.

import random
import operator # contains the python operators as functions
try:
    input = raw_input # rebind raw_input to input, if it exists
                      # so I can just use input :P
except NameError:
    pass
name = input("Hi, what is your name?\n")
print("Hi {} let's get started! Question 1".format(name))
#Get out of the habit of using string concatenation and use string 
#formatting whenever possible. Strings are *immutable*;
#concatenation has to produce a lot temporary strings and is *slow*
#str.join and str.format are almost always better ideas.

#Python does not have a switch-case, so emulating one with a dictionary
operator_mapping = {'+': operator.add,
                    '-': operator.sub,
                    '*': operator.mul,
                   #'/': operator.truediv, #hey, division exists.
                   #But if you want division to actually work, you'll
                   #have to introduce a fudge factor :P
                    }
for i in range(10): # If you're just going for 10 iterations, it should be a for loop
    # Brevity :P This is a list comprehension
    first_number, second_number = [random.randint(1,10) for _ in range(2)]
    oper = random.choice(list(operator_mapping))
    answer = operator_mapping[oper](first_number, second_number)
    while int(input("{} {} {} = ".format(first_number, oper, second_number))) != answer:
   #while abs(float(input("{} {} {} = ".format(first_number, oper, second_number)))-answer) < 0.001: if you want truediv.
        print('Wrong answer! try again!')
    #If I've left the loop, user has given correct (enough) answer
    if i <9: # all but last
        print('Well done! Now onto question number {0}'.format(i+2))
print('Well done! You are done!')
Community
  • 1
  • 1
NightShadeQueen
  • 3,284
  • 3
  • 24
  • 37
  • This is hilarious. I was working on a very similar thing and came out with almost the same program. (Not really, but used a lot of similar ideas -- Python 2/3 compatibility, the dict mapping operators to strings, leaving out division because of the inherent inconsistency in how computers and humans do it.) – Two-Bit Alchemist Aug 26 '15 at 16:03
1

In the third line, you ask for input. But a name is a string, so you need raw_input. raw_input takes strings, input only takes numerical values. Python 2.7 getting user input and manipulating as string without quotations

Nowhere in your code do you update the variable questions, which I am guessing is a counter. You have to update that whenever a question is asked, using question += 1.

Finally, your code at the end does not really make sense. Based off the code, it checks for whether or not it is a string, but then compares it to the answer regardless. The if statement needs to be within the try.

The else statement does not match any outer indentation.

Finally, because of the while True: your code will never exit the loop unless the answer is wrong. At the point the entire program terminates. I see what kind of program you are trying to write, but the parameters for random number generation have to be within some kind of a while question <= 10 loop. As of now, only two lines in the program are being affected by that first while loop.

EDIT: I am working on a good example code. Hopefully this answer will help until I can finish it. EDIT: Here is code that shows how it works within a while loop.

import random
from random import randint

name = raw_input("Hi, what is your name?\n") # Asks for name
print "Hi " +name+ " let's get started!"

score_count = 0
question_count = 0 # creates counter
while question_count <= 10: # Everything MUST BE WITHIN THIS LOOP
    # makes numbers and operator
    first_number = randint(1,10)
    second_number = randint(1,10)
    oper = random.choice("+""-""*")
    # determines the problem
    if oper == "+":
        answer = first_number + second_number
        print first_number,second_number,oper
    elif oper == "-":
        answer = first_number - second_number
        print first_number,second_number,oper
    elif oper == "*":
        answer = first_number*second_number
        print first_number, second_number, oper
    user_answer = int(raw_input("Your answer: "))
    if user_answer != answer: 
        print 'Wrong answer! try again!'
        user_answer = int(raw_input('Your answer: '))
    if user_answer == answer: # exits the while loop when the correct answer is given
        if question_count < 10:
            print 'Well done! Now onto question number {0}'.format(question_count+1)
            score_count += 1
        elif question_count == 10:
            print 'Well done! You are done!'
            score_count += 1
    else:
        print 'Something is wrong.'
    question_count += 1 # updates the variable
    # GOES BACK TO THE BEGINNING UNTIL question_count IS GREATER THAN OR EQUAL TO 10
print "Your score was: {}".format(score_count)

Happy coding! and best of luck!

Community
  • 1
  • 1
Joseph Farah
  • 2,463
  • 2
  • 25
  • 36
0

hi im Nathan and I saw this post I am 5 years to late but I figured if someone on here is knew to python I have a much easier (in my opinion) way to do this in python 3, the code is below:

import random #random module automatically downloaded when you install python

name = input("Please enter your name ")
print("welcome",name,"the arithmetic is about to start")

question=0
while question<10:
    number=random.randint(1,10) #creating a random number
    numbers=random.randint(1,10) #creating a random number
    list = ["+","-","/"] #creating a list (or sometimes called array)
    arith=random.choice(list) #getting random operators from list (+,-,/)
    question += 1 #basically means add one to question variable each time in loop
    if arith=="+":
        print(number,arith,numbers)
        answer=number+numbers
        
        
    elif arith=="-":
        print(number,arith,numbers)
        answer=number-numbers
        
        
    elif arith=="/":
        print(number,arith,numbers)
        answer=number/numbers
        answer = int(answer)
        
    #from HERE
    useranswer = "initialising this variable"
    while useranswer == "initialising this variable":
        try:
            usersanswer= int(input())
            if usersanswer==answer:
                print("correct")
                break
            else:
                print("incorrect")
        except ValueError:
            print ("That is not a valid answer")
    #to HERE it is input validation this takes a while to explain in just commenting
    #but if you dont know what this is then copy this link https://youtu.be/EG69-5U2AfU
    #and paste into google for a detailed video !!!!!!

I hope this helps and is a more simplified commented bit of code to help you on your journey to code in python

N G
  • 23
  • 4