繁体   English   中英

需要帮助打破 while 循环

[英]Need help in breaking out of a while loop

get_valid_user_input() function 独立运行。 但是在 enter_new_trade() function 中调用它时,循环不断重复。 一旦用户进入单笔交易,程序就需要退出循环。

def get_valid_user_input():
    
    valid_input = False
    
    while not valid_input:
        ticker = input("Enter a Ticker")
        if ticker == "":
            print("Ticker cannot be blank")
            
        else:
            b_s = ['b','s']
            buy_sell = input("Buy or Sell").lower()
            while buy_sell not in b_s:
                print("Please enter b or s")
                buy_sell = input("Buy or Sell").lower()
                
            # validating the Quantity of Stock
            valid_integer = False
            while not valid_integer:
                try:
                    stock_qty = int(input("Quantity of Stock "))
                    if stock_qty < 0:
                        print("Please enter a positive whole number")
                    else:
                        valid_integer = True

                except ValueError:
                    print("Please enter a positive whole number")

            # validating the Price of stock
            valid_float = False
            while not valid_float:
                try:
                    floating = float(input("Total Cost (including brokerage):"))
                    if floating < 0:
                        print("Price cannot be negative")
                    else:
                        valid_float = True
                
                except ValueError:
                    print("Enter a valid price")
                    
            valid_date = False
            while not valid_date:
                try:
                    date = datetime.datetime.strptime(input("Date"),"%Y-%m-%d").date()
                    valid_date = True
                except:
                    print("Enter the date format in yyyy-mm-dd")
            
            break
            
            valid_input = True
            
get_valid_user_input()
print("All user inputs validated")

# Manually enter new trade
def enter_new_trade():
    
    trading_data = []
    
    choice = input("Are you looking to buy or sell stocks? (b/s)?").lower()
    while choice:
        if choice == 'b':
            ticker = get_valid_user_input()
            buy_sell = get_valid_user_input()
            stock_qty = get_valid_user_input()
            stock_price = get_valid_user_input()
            Date = get_valid_user_input()
            print(f"{Date} {ticker}   BUY   {stock_qty} for $   {stock_price}") 

            trading_data.append([ticker,buy_sell,stock_qty,stock_price,Date])
            

        elif choice == 's':
            ticker = get_valid_user_input()
            buy_sell = get_valid_user_input()
            stock_qty = get_valid_user_input()
            stock_price = get_valid_user_input()
            Date = get_valid_user_input()
            print(f"{Date} {ticker}   SELL   {stock_qty} for $   {stock_price}")
            trading_data.append([ticker,buy_sell,stock_qty,stock_price,Date])

    #else:
    #    print("Invalid Input")
        choice = input("Are you looking to buy or sell stocks? (b/s)?").lower()

        #break
        return trading_data

enter_new_trade()
print("Trades are added to the system")

使用break keywork 跳出循环并在捕获它们后打印Exception以查看实际的异常是什么。

import sys
import datetime

def get_valid_user_input():


    valid_input = False

    while not valid_input:
        ticker = input("Enter a Ticker")
        if ticker == "":
            print("Ticker cannot be blank")

        else:
            b_s = ['b', 's']
            buy_sell = input("Buy or Sell").lower()
            while buy_sell not in b_s:
                print("Please enter b or s")
                buy_sell = input("Buy or Sell").lower()

            # validating the Quantity of Stock
            valid_integer = False
            while not valid_integer:
                try:
                    stock_qty = int(input("Quantity of Stock "))
                    if stock_qty < 0:
                        print("Please enter a positive whole number")
                    else:
                        valid_integer = True

                except ValueError:
                    print("Please enter a positive whole number")

            # validating the Price of stock
            valid_float = False
            while not valid_float:
                try:
                    floating = float(input("Total Cost (including brokerage):"))
                    if floating < 0:
                        print("Price cannot be negative")
                    else:
                        valid_float = True

                except ValueError:
                    print("Enter a valid price")

            valid_date = False
            while not valid_date:
                try:
                    data = input("Date (yyyy-mm-dd) :").strip()
                    date = datetime.datetime.strptime(data, "%Y-%m-%d").date()
                    valid_date = True
                except Exception as e:
                    print(e)
                    print(f"Enter the date format in yyyy-mm-dd invalid date >>>{data}<<<")

            valid_input = True

    return ticker, buy_sell, stock_qty, floating, date



def enter_new_trade():
    trading_data = []

    choice = False
    while not choice:

        choice = input("Are you looking to buy or sell stocks? (b/s)? ").lower()

        if choice == 'b':
            ticker, buy_sell, stock_qty, stock_price, _date = get_valid_user_input()
            print(f"{_date} {ticker}   BUY   {stock_qty} for $   {stock_price}")
            trading_data.append([ticker, buy_sell, stock_qty, stock_price, _date])
            break
        elif choice == 's':
            ticker, buy_sell, stock_qty, stock_price, _date = get_valid_user_input()
            print(f"{_date} {ticker}   SELL   {stock_qty} for $   {stock_price}")
            trading_data.append([ticker, buy_sell, stock_qty, stock_price, _date])
            break
        else:
            print(f"Invalid input {choice}")
            choice = False

    return trading_data

def main():
    print(enter_new_trade())

if __name__ == "__main__":
    main()

Output:

Are you looking to buy or sell stocks? (b/s)? b
Enter a Ticker33
Buy or Sellb
Quantity of Stock 33
Total Cost (including brokerage):555
Date (yyyy-mm-dd) :2022-10-20
2022-10-20 33   BUY   33 for $   555.0
[['33', 'b', 33, 555.0, datetime.date(2022, 10, 20)]]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM