首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用python进行编程?(if-else,while,continue)

如何使用python进行编程?(if-else,while,continue)
EN

Stack Overflow用户
提问于 2021-04-04 00:43:15
回答 1查看 49关注 0票数 0

我正在学习用Python编程,但我现在解决不了这个问题。

在第11行和第13行,如果取款被拒绝,我想让它重复第10行input("Enter amount of withdrawal")...but使用continue to to selection=input("Make a selection from the option menu:")。我该怎么办?

代码语言:javascript
复制
balance=1000
print("Options:\n1. Make a Deposit\n 2. Make a Withdrawal\n3. Obtain Balance\n4. Quit")
while True:
selection=input("Make a selection from the option menu:")
if selection=='1':
    deposit=float(input("Enter amount of deposit:"))
    balance+=deposit
    print("Deposit Processed.")
if selection=='2':
    withdrawal=float(input("Enter amount of withdrawal:"))
    if withdrawal>balance:
        print("Denied. Maximum withdrawal is $","{0:,.2f}".format(balance))
        continue                  # ***In this process, if withdrawal is denied, I wanna the 10th row..but using continue goes to selection=input("Make a selection from the option menu:") . What should I do?***
    if withdrawal<=balance:
        balance-=withdrawal
        print("Withdrawal Processed.")
if  selection=='3':
    print('$','{0:,.2f}'.format(balance))
if selection=='4':
    break
EN

回答 1

Stack Overflow用户

发布于 2021-04-04 00:57:43

假设从第4行开始的所有内容都在while循环中,您唯一需要添加的就是if selection=='2'块中的另一个for循环:

代码语言:javascript
复制
if selection == '2':
    while True:
        withdrawal = float(input("Enter amount of withdrawal:"))

        if withdrawal > balance:
            print("Denied. Maximum withdrawal is $", "{0:,.2f}".format(balance))
        else:
            balance -= withdrawal
            print("Withdrawal Processed.")
            break

旁注:您可以考虑使用elifelse语句来提高代码的可读性,而不是使用连续的if语句:

代码语言:javascript
复制
balance = 1000
print("Options:\n1. Make a Deposit\n2. Make a Withdrawal\n3. Obtain Balance\n4. Quit")
while True:
    selection = input("Make a selection from the option menu:")
    if selection == '1':
        deposit = float(input("Enter amount of deposit:"))
        balance += deposit
        print("Deposit Processed.")
    elif selection == '2':
        while True:
            withdrawal = float(input("Enter amount of withdrawal:"))

            if withdrawal > balance:
                print("Denied. Maximum withdrawal is $", "{0:,.2f}".format(balance))
            else:
                balance -= withdrawal
                print("Withdrawal Processed.")
                break
    elif selection == '3':
        print('$', '{0:,.2f}'.format(balance))
    elif selection == '4':
        break
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66933594

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档