Python3 newb ie требуется совет - PullRequest
0 голосов
/ 30 мая 2020

Привет всем, я новичок в программировании и серверных вычислениях в целом. Я занимался этим около 3 недель и думал, что попробую написать свое первое приложение. Большая часть моего приложения работает нормально, но я не могу понять, как заставить систему принять новый ввод и применить его к моим функциям после запуска l oop (). помогите пожалуйста!

from os import sys

def say_bye():
    print("GoodBye!")
    sys.exit()

def loop():
    print()
    print("Would you like to enter another value?")
    choice2 = input('y/n: ')
    if choice2 == 'y':
        print()
        amount = float(input("enter another price: "))
        rate = float(input("tax rate: "))
        print()
        return in_page(), tot_with_tax_exit(), print(tot_with_tax()), loop()
    else:
        return say_bye()

def tot_with_tax():
    tax = (amount * rate)
    total = ("Your total after tax is", tax + amount)
    return total

def tot_with_tax_exit():
    if amount == int(0):
        print('would you like to exit')
        choice = input('y/n?: ')
        if choice == 'y':
            print()
            return say_bye()
        else:
            return tot_with_tax()

def in_page():
    print()
    print("Welcome to the tax tool!")
    print()
    print("Please enter your total price, and tax rate.")

in_page()
amount = float(input("enter price: "))
tot_with_tax_exit()
rate = float(input("tax rate: "))
print(tot_with_tax())
loop()

Ответы [ 5 ]

0 голосов
/ 30 мая 2020

Я предполагаю, что вы хотите указать количество и ставку количества в своей функции tot_with_tax (). В этом случае вы можете передать аргументы в функцию.

Таким образом, дескриптор функции будет:

def tot_with_tax(amount, rate):

И вы должны вызвать его, сказав:

return in_page(), tot_with_tax_exit(amount, rate), print(tot_with_tax(amount, rate)), loop()

При вызове tot_with_tax () вам не нужно указывать количество аргументов и скорость, если вы не хотите, например, если у вас есть два состояния, то есть CA и FL, вы можете передать:

return tot_with_tax(amount_CA, rate_CA)

or

return tot_with_tax(amount_FL, rate_FL)

И любой из них будет переведен в сумму и скорость внутри функции.

Также один небольшой совет, вы не хотите помещать в произвольные скобки в python, поскольку это означает тип переменной, называемый кортежем.

Итак, вместо этого:

tax = (amount * rate)

Сделайте следующее:

tax = amount * rate
0 голосов
/ 30 мая 2020

как насчет упрощения вашего l oop? у вас много всего непонятного

in_page()
while(True): ## while the user continues to enter 'y'
    ## ask for input
    amount = float(input("enter price: "))
    tot_with_tax_exit()
    rate = float(input("tax rate: "))
    print(tot_with_tax()) # output

    ## ask the user if they want to enter again
    print()
    print("Would you like to enter another value?")
    choice2 = input('y/n: ')
    if choice2 != 'y': ## if the user does not enter 'y'
        break # break out of the loop
0 голосов
/ 30 мая 2020

Я предполагаю, что ваша проблема заключалась в том, что после вычисления начального tot_with_tax() оно продолжало бы возвращать то же значение независимо от новых входных данных. По крайней мере, это то, что я заметил, когда запустил ваш код. Посмотрите, где я прокомментировал "ЗДЕСЬ". Я только что изменил tot_with_tax(), чтобы взять две переменные tot_with_tax(amount, rate). Теперь вы передаете новую сумму и ставку в функцию каждый раз, когда вам нужно новое вычисление.

from os import sys

def say_bye():
    print("GoodBye!")
    sys.exit()

def loop():
    print()
    print("Would you like to enter another value?")
    choice2 = input('y/n: ')
    if choice2 == 'y':
        print()
        amount = float(input("enter another price: "))
        rate = float(input("tax rate: "))
        print()
        return in_page(), tot_with_tax_exit(), print(tot_with_tax(amount, rate)), loop() # <--- HERE
    else:
        return say_bye()

def tot_with_tax(amount, rate): # <---- HERE
    tax = (amount * rate)
    total = ("Your total after tax is", tax + amount)
    return total

def tot_with_tax_exit():
    if amount == int(0):
        print('would you like to exit')
        choice = input('y/n?: ')
        if choice == 'y':
            print()
            return say_bye()
        else:
            return tot_with_tax()

def in_page():
    print()
    print("Welcome to the tax tool!")
    print()
    print("Please enter your total price, and tax rate.")

in_page()
amount = float(input("enter price: "))
tot_with_tax_exit()
rate = float(input("tax rate: "))
print(tot_with_tax(amount, rate)) # <--- HERE
loop()

Надеюсь, это поможет.

0 голосов
/ 30 мая 2020

Чтобы проверить вводимые пользователем данные, используйте while True l oop.

while True:
    name = input("What's your name?: ")
    if name != "": # If the user entered a name
        break # Exit the loop
    # Else the program will keep asking
    # Until the user enters name.

Вот упрощенная версия вашего кода с реализованной:

from os import sys


print("Welcome to the tax tool!")
print()
print("Please enter your total price, and tax rate.")

def taxed(amount, rate):
    tax = amount * rate
    total = "Your total after tax is $" + str(tax + amount)
    return total

while True:
    amount = float(input("Enter price: "))
    rate = float(input("Tax Rate: "))

    if amount >= 0 and rate >= 0:
        print (taxed(amount, rate))

        while True:
            again = input("Would you like to enter another value? (y/n): ")
            if again == "n":
                print("GoodBye!")
                sys.exit()
            if again == "y":
                break
0 голосов
/ 30 мая 2020

Вы должны передать значения в функцию to_with_tax (), вот код с изменениями, которые заставляют его работать.

from os import sys

def say_bye():
    print("GoodBye!")
    sys.exit()

def loop():
    print()
    print("Would you like to enter another value?")
    choice2 = input('y/n: ')
    if choice2 == 'y':
        print()
        amount = float(input("enter another price: "))
        rate = float(input("tax rate: "))
        print()
        return in_page(), tot_with_tax_exit(), print(tot_with_tax(amount, rate)), loop()
    else:
        return say_bye()

def tot_with_tax(amount, rate):
    tax = (amount * rate)
    total = ("Your total after tax is", tax + amount)
    return total

def tot_with_tax_exit():
    if amount == int(0):
        print('would you like to exit')
        choice = input('y/n?: ')
        if choice == 'y':
            print()
            return say_bye()
        else:
            return tot_with_tax()

def in_page():
    print()
    print("Welcome to the tax tool!")
    print()
    print("Please enter your total price, and tax rate.")

in_page()
amount = float(input("enter price: "))
tot_with_tax_exit()
rate = float(input("tax rate: "))
print(tot_with_tax(amount, rate))
loop()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...