Home > Blockchain >  Problem using curly brackets in functions
Problem using curly brackets in functions

Time:10-31

The line answer = int(input("What is {number1} * {number2} ?")) works fine when using without the function, but when I put it in functions, it throws the error Traceback (most recent call last): File "C:\Users\hjg\Downloads\test4.py", line 17, in <module> answer = eval(input("What is", number1, "*", number2, "?")) NameError: name 'number1' is not defined >>>.

import random, math

def quiz(answer):
    number1 = random.randint(0,9)
    number2 = random.randint(0,9)


    if answer == correctanswer:
        return print("Correct")
    else:
       return print("Incorrect.")


answer = int(input("What is {number1} * {number2} ?"))
correctanswer = number1 * number2


quiz(number1, number2)

CodePudding user response:

You got little confused on your code. number1 and number2 should be out of the function and the function need to get only 1 argument. Try this:

      import random

      def quiz(answer: int):
      correctanswer = number1 * number2
      if answer == correctanswer:
        return print("Correct")
      else:
        return print("Incorrect.")

      number1 = random.randint(0,9)
      number2 = random.randint(0,9)
      answer = int(input(f"What is {number1} * {number2} ?"))
      quiz(answer)

CodePudding user response:

try this

import random, math
number1 = random.randint(0,9)
number2 = random.randint(0,9)

def quiz(answer):
    correctanswer = number1 * number2
    if answer == correctanswer:
        return print("Correct")
    else:
       return print("Incorrect.")

answer = int(input(f"What is {number1} * {number2} ?"))
quiz(answer)

is it ok??

CodePudding user response:

If you declare number1 and number2 inside the function, you'll only be able to access them inside the function. You can either modify the quiz function so that you take the input inside it, or you can initialize the variables outside of the function.

Your function also takes only a single argument, but you pass two. You also don't need to import math. Basic arithmetic (add, subtract, multiply, divide, etc.) is built into Python's core, and you only need the math package to do more complex things like trigonometry or messing around with Pi.

For example:

import random

def quiz(question, correctanswer):
    answer = int(input(question))
    if answer == correctanswer:
        return print("Correct")
    else:
       return print("Incorrect.")

number1 = random.randint(0, 9)
number2 = random.randint(0, 9)

quiz(f"What is {number1} * {number2} ?", number1 * number2)

I suggest you read up on scoping.

CodePudding user response:

Its because of your scope. number1 and number2 don't exist where your referencing them.

  • Related