Ограничение функции time.sleep () одним циклом в python - PullRequest
0 голосов
/ 03 марта 2019

Я создавал банковский интерфейс и хотел, чтобы ежегодные проценты применялись каждые 10 секунд (как часть измененной шкалы времени).

import time

customers = 100
savings = []
fixdeposit = []

ask_user_type = """
What is your user type?
(type 1 if you're an employee)
(type 2 if you're a customer)
"""

employee_function_options = """
What function would you like to carry out?
(type 1 for total savings value)
(type 2 for a specific savings value)
(type 3 for total fixed deposit value)
(type 4 for a specific fd's value)
(type 5 to add a customer)
(type 6 to remove a customer)
(type 7 to end program)
"""

customer_function_options = """
What function would you like to carry out?
(type 1 for withdrawal)
(type 2 for deposit)
(type 3 for savings account balance)
(type 4 to create fixed deposit)
(type 5 to end fixed deposit)
(type 6 for fixed deposit value)
(type 7 to end program)
"""

for i in range (100):
    savings.append(1000)
    fixdeposit.append(0)

while 1 == 1:
    time.sleep(10)
    savings = [i * 1.04 for i in savings]
    fixdeposit = [i * 1.07 for i in fixdeposit]

user = int(input(ask_user_type))

while 1==1:
    if user == 1:
        function = int(input(employee_function_options))
        if function == 1:
            print (sum(savings))
            function = int(input(employee_function_options))

        elif function == 2:
            saving_account = int(input("What is the chosen account's number?"))
            print (savings[saving_account])
            function = int(input(employee_function_options))

        elif function == 3:
            print (sum(fixdeposit))
            function = int(input(employee_function_options))

        elif function == 4:
            fd_no = int(input("What is the chosen fd's number?"))
            print(fixdeposit[fd_no])
            function = int(input(employee_function_options))

        elif function == 5:
            no_new_customers = int(input("How many new customers do you want to add?"))
            for i in range(no_new_customers):
                savings.append(1000)
                fixdeposit.append(0)
            print ("Task Completed")
            function = int(input(employee_function_options))

        elif function == 6:
            account_deleted = int(input("What is the number of the account to be deleted?"))
            savings[account_deleted] = 0
            fixdeposit[account_deleted] = 0
            print ("Task Completed")
            function = int(input(employee_function_options))

        elif function == 7:
            print ("program ended")
            user = int(input(ask_user_type))

        else:
            print("Error")
            function = int(input(employee_function_options))


    elif user == 2:
        function = int(input(customer_function_options))
        if function == 1:
            account_no = int(input("What is your account number?"))
            withdrawal_amount = float(input("How much money do you want to withdraw?"))
            savings[account_no] = savings[account_no] - withdrawal_amount
            withdrawal_amount = 0
            function = int(input(customer_function_options))

        elif function == 2:
            account_no = int(input("What is your account number?"))
            deposit_amount = float(input("How much money do you want to deposit?"))
            savings[account_no] = savings[account_no] + deposit_amount
            deposit_amount = 0
            function = int(input(customer_function_options))

        elif function == 3:
            account_no = int(input("What is your account number?"))
            print(savings[account_no])
            function = int(input(customer_function_options))

        elif function == 4:
            account_no = int(input("What is your account number?"))
            fd_amount = float(input("How much money do you want in your fd?"))
            fixdeposit[account_no] = fd_amount
            fd_amount = 0
            function = int(input(customer_function_options))

        elif function == 5:
            account_no = int(input("What is your account number?"))
            savings[account_no] = savings[account_no] + fixdeposit[account_no]
            fixdeposit[account_no] = 0
            function = int(input(customer_function_options))

        elif function == 6:
            account_no = int(input("What is your account number?"))
            print(fixdeposit[account_no])
            function = int(input(customer_function_options))

        elif function == 7:
            user = int(input(ask_user_type))

        else:
            print("Error")
            function = int(input(customer_function_options))


    else:
        print("Error")
        user = int(input(ask_user_type))

Я использовал time.sleep(), но мне кажется, чтоон также препятствует работе пользовательского интерфейса.

Кто-нибудь знает какие-либо обходные пути или способы ограничить функцию time.sleep() циклом для интереса?

Ответы [ 3 ]

0 голосов
/ 03 марта 2019

Попробуйте использовать threading, переместите деталь, которая обновляет savings и fixdeposit, в другой поток.Это рабочий пример, я только обрезал некоторые части вашего кода, которые не изменились, вы увидите updating, напечатанные каждые 10 секунд:

import threading
import time

customers = 100
savings = []
fixdeposit = []

ask_user_type = ...

employee_function_options = ...

customer_function_options = ...

for i in range (100):
    savings.append(1000)
    fixdeposit.append(0)


def regular_update():
    global savings, fixdeposit
    while True:
        time.sleep(10)
        print('updating')
        savings = [i * 1.04 for i in savings]
        fixdeposit = [i * 1.07 for i in fixdeposit]


my_thread = threading.Thread(target=regular_update, args=())
my_thread.start()

user = int(input(ask_user_type))
... everything here as in your code
0 голосов
/ 03 марта 2019
while 1 == 1:
    time.sleep(10)
    savings = [i * 1.04 for i in savings]
    fixdeposit = [i * 1.07 for i in fixdeposit]

Из-за условия 1 == 1 в вашем цикле while он выполняется вечно, потому что у программы нет возможности выйти из цикла изнутри.Это означает, что ваш time.sleep(10) работает бесконечно.


Обновление: Предполагается, что вы хотите допустимый ввод от пользователя (в зависимости от того, что вы определяете как действительный), вы можете выполнить одно из следующих действий:

number = (int)(input("Enter a number: "))

# 3 is just chosen here as a representative value
# The loop will run until 3 is received as input
while number != 3: 
  number = (int)(input("Enter a number: "))

print("Exited loop")

Или использовать оператор break для выхода из цикла при выполнении условия:

# 3 is just chosen here as a representative value
# The loop will run indefinitely, but if 3 is received as input, it will break the loop (force it to exit)
while 1 == 1:
  number = (int)(input("Enter a number: "))
  if number == 3:
    break

print("Exited loop")
0 голосов
/ 03 марта 2019

Ваш цикл while никогда не прерывается, чтобы позволить другим частям вашей программы работать.

...