为什么我只能得到索引0的正确回报

时间:2019-06-29 18:14:51

标签: python loops iteration

我正在解决一个问题,该问题需要列出油漆颜色并让用户输入颜色名称。如果它们匹配,则表示在列表中找到了颜色。否则它说找不到。如果用于用户输入,则使用列表中的第一个值,它告诉我已找到它;但是,对于所有其他颜色,它会给出未找到的消息。

我检查了油漆颜色列表和输入变量之间是否存在任何变量差异,更改了变量名称,尝试将输入转换为上下。

paint_colors = ['black', 'blue', 'green', 'white', 'yellow']
color_request = input("Enter color name: ")
for color in paint_colors:
    if color_request.lower() == color:
        print("Color exists in list!")
        break
    else:
        print("Color is not in the list!")
        break

我希望通过在输入框中输入“白色”或“白色”一词,它会告诉我找到了它,但是返回它的唯一方法是用黑色填充。

3 个答案:

答案 0 :(得分:1)

第二个break是多余的,因为当颜色与第一个索引不匹配时,您将过早地退出循环:

paint_colors = ['black', 'blue', 'green', 'white', 'yellow']
color_request = input("Enter color name: ")
for color in paint_colors:
    if color_request.lower() == color:
        print("Color exists in list!")
        break
else:
    print("Color is not in the list!")

答案 1 :(得分:0)

我们可以设置一个标记colour_found来跟踪我们是否在列表中找到了颜色。如果找到颜色,则可以退出循环。

paint_colors = ['black', 'blue', 'green', 'white', 'yellow']
color_request = input("Enter color name: ")
colour_found = False
for color in paint_colors:
    if color_request.lower() == color:
        colour_found = True
        break



if colour_found:
    print("Color exists in list!")
else:
    print("Color is not in the list!")

答案 2 :(得分:0)

您的第二个def objective(params, n_folds=2): """Objective function for Hyperparameter Optimization""" # Keep track of evals global ITERATION ITERATION += 1 clf = KerasClassifier(build_fn=create_model,**params) start = timer() # Perform n_folds cross validation cv_results = cross_val_score(clf, X, y, cv=5, ).mean() run_time = timer() - start # Loss must be minimized loss = -cv_results # Dictionary with information for evaluation return { 'loss': loss, 'params': params, 'iteration': ITERATION, 'train_time': run_time, 'status': STATUS_OK } from hyperopt import fmin, tpe, hp, Trials, STATUS_OK space = {'units1': hp.choice('units1', [12, 64]), 'dropout': hp.choice('dropout1', [0.25, 0.5]), 'batch_size': hp.choice('batch_size', [10, 20]), 'epochs': hp.choice('nb_epochs', [2, 3]), 'activation': 'relu' } 语句引起了问题。您可以尝试以下方法:

global ITERATION
ITERATION = 0

bayes_trials = Trials()

best = fmin(fn = objective, space = space, algo = tpe.suggest, 
            max_evals = 5, trials = bayes_trials, rstate = np.random.RandomState(50))

以其他方式使用另一个变量:

import requests
import pandas as pd
import openpyxl

#reading excel column.
export = pd.read_excel('abc.xlsx')
#creating list from column data
taglist = export.values.T[0].tolist()
#setting url
url = 'https://www.somesite.com/support/article/us/en/'

#reading cell by rows and append the string with variable url
#looping through the elements of list and doing html parsing of the html tag
for i in taglist:
    r = requests.get(url+i)
    r.text[1:500]
    from bs4 import BeautifulSoup
    soup = BeautifulSoup(r.text, 'html.parser')

    #getting Title from html page 
    df = soup.title.text
    frame_data = {df}
    df1 = pd.DataFrame(frame_data)
    df1.to_excel("pandasExcel.xlsx", "sheet2")

使用break运算符:

paint_colors = ['black', 'blue', 'green', 'white', 'yellow']
color_request = input("Enter color name: ")
for color in paint_colors:
    if color_request.lower() == color:
        print("Color exists in list!")
        break
else:
    print("Color is not in the list!")