Temel python hesaplayıcı

Oct 20 2020

Okulda Python öğrenmeye başlayan ve ona küçük bir görev vermemi isteyen genç bir arkadaşım var. Hiçbir şekilde öğretmen veya Python uzmanı değilim, ama kabul ettim.

İlk başta, işlemin girdisi için biraz ayrıştırarak başlamanın eğlenceli olacağını düşündüm, örneğin:

Enter your operation : 3+3

Ama ona biraz ezici geldi, bu yüzden onu üç kısma ayırmaya karar verdik (birinci sayı, işlenen ve ikinci sayı).

Biraz düzeltme yaptım ama bunu beceriksiz buluyorum ve egzersizin amacı ona bazı iyi uygulamaları göstermektir.

İşte kodum:

calculate = True
while calculate:
    try:
        number1 = float(input("Enter the first number : "))
    except ValueError:
            print("Incorrect value")
            exit()
    symbol = input("Enter the operation symbol (+,-,/,*,%) : ")
    try:
        number2 = float(input("Enter the second number : "))
    except ValueError:
            print("Incorrect value")
            exit()
    operande = ["+", "-", "*", "/", "%"]
    resSentence = "Result of operation \"{} {} {}\" is :".format(number1, symbol, number2)
    if symbol not in operande:
        print("Incorrect symbol")
    elif symbol == "+":
        print(resSentence, number1 + number2)
    elif symbol == "-":
        print(resSentence, number1 - number2)
    elif symbol == "*":
        print(resSentence, number1 * number2)
    elif symbol == "/":
        print(resSentence, number1 / number2)
    elif symbol == "%":
        print(resSentence, number1 % number2)
    restart = input("Do you want to do another calcul (Y/n) ? ")
    while restart.lower() != "y" and restart.lower() != "n":
        print(restart.lower(), restart.lower(), restart.lower()=="n")
        restart = input("Please, enter \"y\" to continue or \"n\" to exit the program : ")
    if restart.lower() == "n":
        calculate = False

Kullanıcı geçerli bir değer girene kadar geçerli olduğunda number1veya number2olmadığında bir döngü yapmak isterdim float, ancak bunu yapmanın temiz bir yolunu bulamadım. Bununla ilgili tavsiyeleri memnuniyetle kabul ederim (bunun bu Yığın Değişimi için bir soru olmadığını bilsem de, bunu yapmanın iyi bir Pythonic yolu harika olurdu :)).

Yanıtlar

9 AryanParekh Oct 21 2020 at 04:59

Daha fazla işlev kullanın

Bir fonksiyonunuz var calculate(), ancak bunun sadece hesaplamaktan çok daha fazlasını yaptığını görürseniz, bu, kodunuzun mantıksız bir şekilde hantal görünmesine neden olur. Ancak çok basit bir çözüm var, daha fazla işlev kullanın. Ya ana döngünüz gibi görünebilseydi

while True:
    number1,number2,operand = take_input()
    result = calculate(number1,number2,operand)
    print(f"Answer : {numebr1} {operand} {number2} = {result}")
    if input("Do you want to play again? (y/n): ").lower() == 'n':
        break 

Bu, programınızın bakımını kolaylaştırır.

continue bir hata olduğunda

try:
    number1 = float(input("Enter the first number : "))
except ValueError:
        print("Incorrect value")
        exit()

Kendinize sorun, kullanıcı geçersiz girdi girerse bir program neden sonlanır? Ona bir şans daha ver xD

Tutarlı girintiyi koruyun

try:
    number2 = float(input("Enter the second number : "))
except ValueError:
            print("Incorrect value")
            exit()

Tutarlı girintiyi korumaya çalışın, çünkü 4daha önce boşluklar kullandığınız için, 8daha sonra kullanmak için iyi bir neden yoktur , sadece kodu daha sonra okuyanların kafasını karıştırabilir.

Kod mantığı 1

Bu örnek girdiyi düşünelim

Enter the first number : 1
Enter the operation symbol (+,-,/,*,%) : I like python
Enter the second number : 2
Incorrect symbol

Açıkçası, symbolyanlış. Neden girerken hata yaptığımı öğrenmek için ikinci numarayı girmek zorunda kaldım symbol? Bana hemen sembolümün yanlış olduğunu söylemeliydi, böylece onu düzeltebilirdim.

if symbol not in operandsİfadeyi girişin hemen yanında olacak şekilde hareket ettirin .

eval

Python'da Değerlendir

Bu, 10-15 satırlık kodu bir kod satırına dönüştürdüğü için programınızdaki en büyük gelişme olacaktır.

eval()Fonksiyon ifadesi hukuki bir Python deyimi ise, bu çalıştırılacaktır, belirtilen ifadeyi değerlendirir.

Kulağa tanıdık geliyor, temelde basit ifadeleri değerlendirmiyor muyuz?

Kullanıldığında eval, hesaplama bölümünüz şöyle görünür

result = eval(f"{number1}{operand}{number2}")

Misal, number1 = 5,number2 = 10, operand = '+'

Temelde olan bu

result = eval("5+10")

Final

İşte iyileştirmelerle birlikte kod

def take_input():
    err_msg = "Invalid input"
    operands = ['+','-','*','/','%']
    try:
        num1 = float(input("Enter number 1: "))
    except Exception:
        print(err_msg)
        return take_input()
    try:
        num2 = float(input("Enter number 2: "))
    except Exception:
        print(err_msg)
        return take_input()

    print("Operands: " + ', '.join(x for x in operands))
    try:
        operand = input("Enter operand: ")
    except Exception:
        print(err_msg)
        return take_input()

    if operand not in operands:
        print(err_msg)
        return take_input()

    return num1,num2,operand

def calculate(num1,num2,operand):
    return eval(f"{num1}{operand}{num2}")


def mainloop():
    while True:
        num1,num2,operand = take_input()
        result = calculate(num1,num2,operand)
        print(f"Answer: {result}")
        if input("Do you want to play again? (y/n): ").lower() == 'n':
            break

mainloop()
5 Deep_Thoughts Oct 20 2020 at 21:54

Bu, kodunuza bir alternatiftir, biraz daha karmaşıktır, ancak aynı zamanda daha okunabilirdir. Döngü olayını yapmayı başardım ama takip etmesi biraz zor. Afedersiniz.

running = True
# Break Things up into functions each function does one single thing

def calculate(inputOne, operand, inputTwo):
    """
    Calculates inputOne operand and inputTwo
    """

    if operand == "+":
        return inputOne + inputTwo
    elif operand == "-":
        return inputOne - inputTwo
    elif operand == "*":
        return inputOne * inputTwo
    elif operand == "/":
        return inputOne / inputTwo
    elif operand == "%":
        return inputOne % inputTwo

def askInput():
    """
    Asks for a number until a number is given checks if each one is valid
    """

    isValid = [False, False, False] # none of the numbers are validated yet
    number1, symbol, number2 = ["", "", ""]
    
    # Here is a good implementation of the loop, it is kind of complex though
    while True:
        try:
            if not isValid[0]: # Asks for number1 if it is not valid
                number1 = int(input("Enter the first number : "))
                isValid[0] = True

            if not isValid[1]: # This is added functionality because there was a loophole in your program
                symbol = input("Enter the operation symbol (+,-,/,*,%) : ") # use tuples whenever possible
                supportedOperands = ("+", "-", "/", "*", "%")

                if symbol not in supportedOperands:
                    raise ValueError

                isValid[1] = True

            if not isValid[2]: # Asks for number2 if it is not valid
                number2 = int(input("Enter the second number : "))
                isValid[2] = True
            break
        
        except ValueError:
            continue # this just restarts the whole thing
    
    return number1, symbol, number2



def continueApp():
    """
    Checks if the input to restart is valid
    """
    restart = input("Do You want to do another calculation (Y/n) ? ").lower()

    while True:
        if restart == "y":
            return True
        elif restart == "n":
            return False
        else:
            restart = input("Please, enter \"y\" to continue or \"n\" to exit the program : ").lower()

while running:

    numberOne, operand, numberTwo = askInput()
    answer = calculate(numberOne, operand, numberTwo)
    resSentence = f"Result of operation {numberOne} {operand} {numberTwo} is : {answer}"
    print(resSentence)

    if continueApp():
        pass
    else:
        running = False
exit()


İpuçları:

  • İşleri işlevlere ayırın:

Fonksiyonlar, fonksiyon çalıştırılabilir kod için sadece kaplardır GEREKİR yapmak ONE sadece ve TEK fonksiyonlar üzerinde bir şey daha burada .

  • Lütfen kodunuz hakkında yorum yapmayı deneyin, okumayı ve düzenlemeyi kolaylaştırır.

Bu işlev

def calc():
    x = 1
    y = 12
    return (((x+y)/x)**y)+(3*x+4*y) # Please don't write like this in any case

bir açıklamayla veya neler olup bittiğiyle çok daha iyi olurdu

def calc():
    """
    Accepts: Nothing
    Does: Adds X and Y, then divides it by X to the power of Y
          then it adds  it to X multiplied by three and 4 multiplied by Y
    Returns: integer (the result of Does) ^^^^^
    """
    x = 1
    y = 12
    return ((x+y)/x**y)+(3*x+4*y) # Again, please don't write code like this
  • F dizelerini kullanın (bu, python 3.6 ve üstünü gerektirir)

f dizeleri böyle kullanılır

value = "12"
print(f"Number {value} is an example of an f string") 

# Versus

print("Number {} is an example of an f string".format(value))
  • Kodunuzda boşluk bırakmayı deneyin

İnanın bana, bu kodunuzun okunmasını ve anlaşılmasını kolaylaştırır.

def calc():
    """
    Accepts: Nothing
    Does: Adds X and Y, then divides it by X to the power of Y
          then it adds  it to X multiplied by three and 4 multiplied by Y
    Returns: integer (the result of Does) ^^^^^
    """
    x = 1
    y = 12
    ans = (x + y) / (x ** y)
    ans += (3 * x) + (4 * y) # just adds ans to the right side of the operator
    return ans