Python循环不会正确遍历字典

时间:2020-01-22 18:50:56

标签: python python-3.x loops dictionary for-loop

我正在开发我的个人理财计划,我试图让用户能够选择他们想要交易的货币。我正在尝试错误处理,如果他们输入了密钥在字典中不存在,它显示一条消息并关闭程序。但是现在即使我输入了正确的键,它仍然会关闭。

<?php

namespace Tests\Feature;

use App\Http\Middleware\TestMiddleware;
use Exception;
use Illuminate\Database\Events\TransactionBeginning;
use Illuminate\Database\Events\TransactionCommitted;
use Illuminate\Database\Events\TransactionRolledBack;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Event;
use Tests\TestCase;

class ExampleTest extends TestCase
{
    /**
     * @var \App\Http\Middleware\TestMiddleware
     */
    protected $middleware;

    /**
     * @var \Illuminate\Http\Request
     */
    protected $request;

    /**
     * @var \Illuminate\Http\Response
     */
    protected $response;

    public function setUp():void
    {
        parent::setUp();

        Event::fake();

        $this->middleware = new TestMiddleware();

        $this->request = new Request();

        $this->response = new Response();
    }

    public function testTransactionShouldRollback()
    {
        $fake = Event::fake();
        DB::setEventDispatcher($fake);

        // Ignore the exception so the test itself can continue.
        $this->expectException('Exception');

        $this->middleware->handle($this->request, function () {
            throw new Exception('Transaction should fail');
        });

        Event::assertDispatched(TransactionBeginning::class);
        Event::assertDispatched(TransactionRolledBack::class);
        Event::asserNotDispatched(TransactionCommitted::class);
    }

    public function testTransactionShouldBegin()
    {
        $fake = Event::fake();
        DB::setEventDispatcher($fake);

        $this->middleware->handle($this->request, function () {
            return $this->response;
        });

        Event::assertDispatched(TransactionBeginning::class);
        Event::assertNotDispatched(TransactionRolledBack::class);
        Event::assertDispatched(TransactionCommitted::class);
    }
}

,如果我删除了else语句,但是它没有起作用,但是我可以输入任何单词,它不必是键,而是将其分配给变量,甚至不检查它是否作为键存在于字典

4 个答案:

答案 0 :(得分:0)

您不想在检查第一个键后立即退出。一种解决方法可能是

found = False

for key in currencySYM:
    if currencyCheck == key:
        currencyCheck = currencySYM[key]
        found = True

if !found:
    print("Make sure you type the correct three letter symbol.")
    exit()

当然,更好的方法是检查密钥是否在字典中:

if currencyCheck in currencySYM:
    currencyCheck = currencySYM[key]
else:
    print("Make sure you type the correct three letter symbol.")
    exit()

答案 1 :(得分:0)

您正在检查是否已输入字典中的每个键,这是不可能的。您可以通过在break子句的末尾添加if语句来轻松解决此问题:

 if currencyCheck == key:
    currencyCheck = currencySYM[key]
    # found the key, so stop checking
    break

在任何情况下,此代码都不是Python语言,您可以用整个循环替换此代码,如果dict中的键不可用,则将返回None:

currencyCheck = currencySYM.get(key,None)
if not currencyCheck:
    print("Make sure you type the correct three letter symbol.")
    exit()

答案 2 :(得分:0)

如果要检查给定词典中是否存在key,可以执行key in dict

currencyCheck = input("Input the currency you would like to use. Ex: 'USD' or 'EUR'...etc ").upper()
currencySYM = {'USD':'$', 'EUR':'€', 'CAN':'C$','YEN':'¥','GBP':'£'}
if currenyCheck in currencySYM:
    currencyCheck = currencySYM[key]
else:
    exit()

或者您可以使用.get()

currencyCheck = input("Input the currency you would like to use. Ex: 'USD' or 'EUR'...etc ").upper()
currencySYM = {'USD':'$', 'EUR':'€', 'CAN':'C$','YEN':'¥','GBP':'£'}

currencyCheck=currencySYM.get(currencyCheck,exit())

字典 是无序的-因为 字典中的是用键索引的 ,它们不以任何特定顺序保存,与列表不同,在列表中,每个项目都可以通过其在列表中的位置进行定位。

答案 3 :(得分:0)

应该可以:

currencyCheck = input("Input the currency you would like to use. Ex: 'USD' or 'EUR'...etc ").upper()

#currencySYM is a dictionary of currency ticker symbols and currency symbols
currencySYM = {'USD':'$', 'EUR':'€', 'CAN':'C$','YEN':'¥','GBP':'£'}
#the for loop takes the input from Currencycheck and applies the correct symbol to the letters
key_list = currencySYM.keys()
if currencyCheck in key_list:
    currencyCheck = currencySYM[currencyCheck]

elif currencyCheck not in key_list:
    print("Make sure you type the correct three letter symbol.")
    exit()