gpt4 book ai didi

python - Python 如何解释这个条件?

转载 作者:行者123 更新时间:2023-12-01 06:04:35 25 4
gpt4 key购买 nike

我正在解决的问题解释如下:

2.1) Write a program that asks a user to input a color. If the color is black or white, output "The color was black or white". If it starts with a letter that comes after "k" in the alphabet, output "The color starts with a letter that comes after "k" in the alphabet". (Optional: consider both capitalized and non-capitalized words. Note: the order of the alphabet in Unix and Python is: symbols, numbers, upper case letters, lower case letters.)

这是作者的解决方案:

#!/usr/bin/env python
#
# guess a color
#
answer = raw_input ("Please enter a color: ")

if (answer == "black") or (answer == "white"):
print "The color was black or white."
elif answer >= "k":
print "The color starts with a letter that comes after \"k\" in the alphabet."

这是我对问题的回答:

#!usr/bin/env python
#
#This program asks the user to input a color

color = raw_input("Please, enter a color, any color.")

if (color == "black") or (color == "white"):
print "The color was black or white."

elif color[0] != "a" or "b" or "c" or "d" or "e" or "f" or "g" or "h" or "i" or "j" or "k":
print "The color starts with a letter that comes after 'k' in the alphabet."

else:
print "The color was niether black nor white."

我无法理解作者的解决方案是如何工作的,特别是用于识别“颜色是否以字母表中“k”之后的字母开头”。

Python 是如何做到这一点的?

elif answer >= "k":

Python 如何识别第一个字符,例如 color[0] 以及 k 之外的字母范围?

最佳答案

因为一般来说,Python 序列(包括字符串)实现 lexicographical ordering对于他们的元素。因此首先比较元素 0,如果相同则比较元素 1,依此类推。

但请注意,您的解决方案是错误的。它被解析为 (color[0] != "a") 或 "b"或 "c"或 "d"或 "e"或 "f"或 "g"或 "h"或 "i"或“j”或“k”,仅当 color[0] == 'a' 时为 false。您正在寻找的 color[0] 不在 ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i' 中, 'j') (你也不应该排除 'k'),但是使用 >= 只是一个非常非常干净的事情。

关于python - Python 如何解释这个条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8775467/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com