python3.5中的While循环重复请求输入,而不是在字典中给出分配给输入的值

2024-09-28 21:14:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图复制一本Python书籍中的一个示例,该示例演示如何将文本文件转换为字典,并通过输入函数请求翻译。你知道吗

我的问题是,现在这个程序不会给我翻译的一个给定的有效输入是在字典里。但是,如果我使用if True而不是while循环,它就会这样做。我试图重新安排代码,但它仍然会重复要求我输入。你知道吗

以下是导致此问题的代码:

    genetischercode={}

    while True:
      triplet=input("Geben sie ein basentriplet ein: ")

    with open("C:\\Users\\Christian\\Desktop\\Python-Programme\\Genetischer Code.txt","r") as fobj:
      for line in fobj:

      line=line.strip()
      Zuordnung=line.split( )
      genetischercode[Zuordnung[0]]=Zuordnung[1]


    if triplet in genetischercode:
     print("Die korrespondierende Aminosäure ist: ",genetischercode[triplet])
    else:
      print("Bitte geben sie ein gültiges Triplet ein: ")

现在发生的是,程序将重复请求变量triplet的输入,而不是if triplet in genetischer code:else:被触发。你知道吗

我怎样才能解决这个问题?你知道吗


Tags: 代码in程序true示例if字典line
1条回答
网友
1楼 · 发布于 2024-09-28 21:14:28

您必须将if triplet in…和下面的行放入循环体中,方法是将其放置在适当的位置并增加缩进。(请注意,缩进在Python编程中非常重要,因为它是生成循环、if等中使用的代码块的唯一方法。)

genetischercode={}

# we have to generate the dictionary only once
with open("C:\\Users\\Christian\\Desktop\\Python-Programme\\Genetischer Code.txt","r") as fobj:
  for line in fobj:

      line=line.strip()
      Zuordnung=line.split( )
      genetischercode[Zuordnung[0]]=Zuordnung[1]
# now enter infinite loop
while True:
  triplet=input("Geben sie ein basentriplet ein: ")

  # you probably want some way to exit the loop
  if triplet == 'stop':
      break

  if triplet in genetischercode:
      print("Die korrespondierende Aminosäure ist: ",genetischercode[triplet])
  else:
      print("Bitte geben sie ein gültiges Triplet ein: ")

相关问题 更多 >