0

I'm learning python for 2 weeks. So my question is let's say I created a calculator. How can I add number as much as user likes?

os.system("del *.pyc")    

print "Hello %s!" % ad
print "---------------------------------------"
print "                 *Add"
print "                 *x Add (Dunno english)"
print "                 *Multiply"
print "                  *x Multiply (Look up)"
print "                 *Multiply by itself"
print "                 *math.sqrt"
print "---------------------------------------"

print "What u want? :)"
choice = raw_input("Secimim= ")

print "So you choose %s :)" % choice
print ""
print "redirecting..."
time.sleep(3)
os.system("cls")
if secim.lower()=="add":
    first=input("First number= ")
    second=input("Second= ")
    print "Result= " + str(add(first,second))
    os.system("pause")

Rest of them is same Let's make this part english

print "Let's have your choice :)"
secim = raw_input("Secimim= ")
adsiz = (ad,secim)
print "So you selected this :)" % adsiz
print ""
print "Redirecting..."
time.sleep(3)
os.system("cls")
if secim.lower()=="add":
    ilksayi=input("IFirst= ")
    ikincisayi=input("Second= ")
    print "Result= " + str(toplama(ilksayi,ikincisayi))
    os.system("pause")
def toplama(x,y):
    return x+y

This part

if secim.lower()=="add":
        firstnumber=input("IFirst= ")
        secondnumber=input("Second= ")
        print "Result= " + str(add(ilksayi,ikincisayi))
        os.system("pause")

I want to make it like a loop that it says:

Number=10
Number = 26
Number = 62
...

And when you type

Number= (Blank)

It print the result. Just like the phone's calculators. I tried making it with loop that breaks when user types quit. But I can't declare that much variable. How to make auto making variables?

Dr. UK
  • 73
  • 1
  • 2
  • 7
  • Use a list. Related reading: [How do I do variable variables in Python?](http://stackoverflow.com/q/1373164/953482) – Kevin Jun 23 '16 at 16:56
  • put you input to list – galaxyan Jun 23 '16 at 16:57
  • You might be interested in using a [list](https://docs.python.org/2/tutorial/datastructures.html). Not sure what you mean by "auto making variables". Frankly, it's really quite difficult to understand without the variable names being English. – Alyssa Haroldsen Jun 23 '16 at 16:57
  • Ok I will translate it to english now. – Dr. UK Jun 23 '16 at 16:58
  • Also, auto making variable is something like "How many numbers will you type=6" var1 var2 var3 var4 var5 var6 – Dr. UK Jun 23 '16 at 17:06
  • You don't have to 'auto make' variables in python. You can use `list.append()` method to add as many values as you'd like. – Ishaan Jun 23 '16 at 17:14
  • Possible duplicate of [python restart the program after running a method](http://stackoverflow.com/questions/4413798/python-restart-the-program-after-running-a-method) – TessellatingHeckler Jun 23 '16 at 17:33

3 Answers3

0

I think you are looking for something like this.

Python 2

num = '0'
total = 0
while True: #run loop until user enters something that is not a number
    if not num.isdigit():
        break #at this point break out of the loop
    total += int(num) #else add the number to the total (could be / * - +)
    num = raw_input('Number:\t')
print total #finally print the total

Or you could use an approach with Lists

nums = []
while True:
    num = raw_input('Number: ')
    if num.isdigit(): nums.append(int(num))
    else: break;
print sum(nums)
Ishaan
  • 707
  • 1
  • 7
  • 16
  • @Dr.UK if this answered your question please don't forget to accept it as an answer. Cheers – Ishaan Jun 23 '16 at 17:22
0

Do you mean something like...

def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        return False

number = 0
input = raw_input('Number: ')
while input != None and input != "":
    if not is_number(input):
        print "NaN"
        continue
    number += float(input)
    input = raw_input('Number: ')
print "Number = %s" % (number, )

I typed it blind so there might be errors in the code but you get the drift hopefully

Ivonet
  • 2,492
  • 2
  • 15
  • 28
  • 1
    Typed it blindly, you say? ;) http://stackoverflow.com/questions/354038/how-do-i-check-if-a-string-is-a-number-float-in-python – Ishaan Jun 23 '16 at 17:12
  • I actually truly didn't know. I've written a lot in python and have an extensive code base to cut and pate from. But I see your point about the is_number method :-) – Ivonet Jun 23 '16 at 19:53
0

Try this:

#! python3
# coding=utf-8
"""Add a lot of numbers."""

def add_everything():
    """ """
    numbers = []
    while True:
        print("Sum:", sum(numbers) )
        s = input("Enter number(s) or just hit Return to quit:")
        if not s:
            break
        for n in s.split():
            try:
                number = float(n)
            except ValueError:
                print("That wasn't a number. Try again!")
            else:
                numbers.append( number )
                print("added {} to {}".format( number, sum(numbers[:-1]) ) )
            finally:
                pass

    print("That was fun!")
    print("I remembered all your {} numbers:".format(len(numbers)) )
    for n in numbers:
        print(" {:4.2f}".format(n) )
    print("--------")
    print(" {:4.2f}".format( sum(numbers) ) )


if __name__ == '__main__':
    add_everything()

Example:

Sum: 0
Enter number(s) or just hit Return to quit:123 45.6
added 123.0 to 0
added 45.6 to 123.0
Sum: 168.6
Enter number(s) or just hit Return to quit:hello
That wasn't a number. Try again!
Sum: 168.6
Enter number(s) or just hit Return to quit:-0.99
added -0.99 to 168.6
Sum: 167.60999999999999
Enter number(s) or just hit Return to quit:
That was fun!
I remembered all your 3 numbers:
 123.00
 45.60
 -0.99
--------
 167.61
handle
  • 5,859
  • 3
  • 54
  • 82