Python Forum

Full Version: A problem with defining variables
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm trying to create a function that accepts two numbers and returns the product or the number zero if the result is negative.
I wrote the following code

def mul_2nums():
    x = raw_input('write first number: ')
    y = raw_input('write second number: ')
    return x, y


def multiply():
    x = b
    y = a
    print a * b
    if a * b < 0:
        print 0

multiply(x,y)
And i get - NameError: name 'x' is not defined

What am I doing wrong
?
In mul_2nums you ask the user for 2 numbers and then return the user input - that's good.
The problems:
You need to call this function and assign the 2 values that it will return to two variable names for later use in multiply(). Check the code from your other thread from almost a year ago.
When you define multiply() you need to "tell" python to expect two numbers as arguments.
In order to be able to multiply the two numbers you need to convert the user input (which will be str) to int. The best place to do so is within mul_2nums, i.e. you can keep asking user for input until you get twice valid input that you can convert to int.
Finally - you use python2. You should be using and learning python3. Python2 supports ends at the end of the 2019
Thank's buran

Can you show an example of how the code that convert the user input to int should look?
You can use int() built-in function

x = int(raw_input('write first number: '))
this is basic example. it will raise and exception in case of invalid input
(Jan-30-2019, 12:14 PM)meru120 Wrote: [ -> ]Thank's buran

Can you show an example of how the code that convert the user input to int should
look?

wanna discuss something?
what's your question? why you resurrect this thread?