Python Forum

Full Version: Fixing the code
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi everybody, I'm a new beginner and I just starting to learn to code. I have a question about the code that I coded, when I put the operation in and I put two number in, it does not show the result statement but instead it keep doing the while loop, so can you you guys give me any advice?
''' This program is used for calulating numbers as a simple calculator
Created by Khanh Cao
05/02/2020'''
print('This program behaves as a simple calculator. It accpepts 2 numbers and one charater. The character indicates which operation is to be performed')
flag='true'
while True:
    operation=input('Enter one of + - * / % to idicate which operation to perform, or enter q or Q to quit: ')
    if operation =='Q' or operation=='q':
        
        print('Quitting')
        continue
    num1=float(input('Enter the first number: '))
    num2=float(input('Enter the second number: '))
    if operation=='+':
        k=num1+num2
    elif operation=='-':
        k=num1-num2
    elif operation=='*':
        k=num1*num2
    elif operation=='/':
        if num2== 0:
            print ('You can not divide a number by zero')
        else:
            k=num1/num2
    elif operation == '%':
        k=num1%num2
    else:
        flag='false'
        print('Unexpected Operation')
if flag =='true':
    print('The result of', num1, operation,num2,'is: ',k)
While True:
Doesn't have any way to be set False and terminate the loop.

If flag is what you what to use try:
flag = True
While flag:


While you can us "true" and "false", True and False and there for this purpose.
using while True: is perfectly alright and better than using a flag. you just need to use break, not continue to break out of the loop.
print('This program behaves as a simple calculator. It accpepts 2 numbers and one charater. The character indicates which operation is to be performed')
 
while True:
    operation=input('Enter one of + - * / % to idicate which operation to perform, or enter q or Q to quit: ')
    if operation == 'Q' or operation == 'q':
        print('Quitting')
        break
    num1 = float(input('Enter the first number: '))
    num2 = float(input('Enter the second number: '))
    if operation == '+':
        k = num1+num2
    elif operation == '-':
        k = num1-num2
    elif operation == '*':
        k = num1*num2
    elif operation == '/':
        if num2 == 0:
            print ('You can not divide a number by zero')
        else:
            k = num1/num2
    elif operation == '%':
        k = num1%num2
    else:
        print('Unexpected Operation')
        continue # this will skip printing the result
    print('The result of', num1, operation, num2,'is: ', k)
It can be refactored to be more pythonic or logic to be better (e.g. - you don't need to ask for numbers if operation is unexpected, move that part forward)