Python Forum
A problem with defining variables
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
A problem with defining variables
#1
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
?
Reply
#2
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
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
Thank's buran

Can you show an example of how the code that convert the user input to int should look?
Reply
#4
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
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
(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?
Reply
#6
what's your question? why you resurrect this thread?
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#7
why the forum is looks like closed? no one posting there
Reply
#8
One problem is you don't use the values returned by mul_2nums(). The values returned by mul_2nums() are also the wrong type for multiplication.

You could do this.
def mul_2nums():
    x = input('write first number: ')
    y = input('write second number: ')
    return x, y
 
 
def multiply(x, y):
    result = x * y
    if result < 0:
        print(0)
    else:
        print(result)
x, y = mul_2nums()
multiply(x,y)
There's likely to be some confusion caused by programming using Python2 instead of Python3. In Python2, input() evaluates the entered string and returns the result. To get the string entred by the user you would use raw_input(). In python3, input() does what raw_input() did in python2, and nothing does what input() used to do in python2. Everyone decided automatically evaluating input strings was a really bad idea.

Another problem is that you never return the result of the multiplication. Printing is not returning. When a function returns a value, the value can be used to perform additional calculations. When a function prints a value instead of returning, the result is lost. Not only that, a function that prints is not easily reused. I might want to format my output differently than the way it is done in the function.

This is how I might write your code, using python3.
def input_int(prompt="Enter an integer: "):
    while True:
        try:
            text = input(prompt)
            return int(text)
        except ValueError:
            print(f"{text} is not an integer.")


def multiply(x, y):
    return max(0, x * y)


x = input_int()
y = input_int()
result = multiply(x, y)
print(f"{x} * {y} = {result}")
I would write a special function for getting the integer input. Entering integers is error prone. Care must be taken that the user provides an invalid input that crashes the program. In input_int() I use try/except to catch invalid input and ask the user to try again.

returning 0 for negative results in multiply() can be done with an if statment, but it can also be done using max(*args). Max returns the maximum value *args. max(0, result) returns result or 0, whichever is greater.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Problem defining a variable rix 6 4,343 Dec-17-2019, 11:34 AM
Last Post: rix
  problem using exec to save local variables dkarl 0 2,484 Dec-01-2019, 08:52 AM
Last Post: dkarl
  Problem with variables JCB 3 3,143 Nov-13-2019, 07:20 PM
Last Post: the_ophidian_order
  Problem with defining a function snow_y 4 4,248 Nov-26-2018, 02:13 AM
Last Post: snippsat
  Problem with variables Steffenwolt 4 4,319 Jul-14-2018, 07:27 PM
Last Post: Steffenwolt
  Defining Variables in outside modules Barnettch3 4 4,660 Dec-12-2017, 10:19 PM
Last Post: Larz60+
  [split] Problem using global variables RedSkeleton007 1 3,246 Nov-10-2017, 09:13 PM
Last Post: sparkz_alot
  Vending Machine Program: Problem with variables icabero0225 2 9,312 Jun-08-2017, 11:04 AM
Last Post: buran
  MySQLdb, problem with query with user-defined variables buran 6 7,829 Feb-03-2017, 06:16 PM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020