在for循环中正确的语法

huangapple go评论79阅读模式
英文:

Proper syntax in a for loop

问题

这段代码给出了以下错误:

 File "C:\XXX\XXX\XXX\XXX.py", line 7
    for temp_o not in Units:
                           ^
SyntaxError: invalid syntax

它说冒号 ":" 是无效语法。如果我删除它,也不起作用。有任何想法吗?

英文:

I'm trying to make a convertor of temperature units, and I ran into a problem trying to make it stupid-proof.

Units = "Celsius", "celsius", "Fahrenheit", "fahrenheit", "Kelvin", "kelvin"
temp_o = input("¿Do you wish to convert Celsius, Fahrenheit, or Kelvin?")
for temp_o not in Units:
    temp_o = input("Insert an accepted unit of measurement")

This section of the code is giving me the following error:

 File "C:\XXX\XXX\XXX\XXX.py", line 7
    for temp_o not in Units:
                           ^
SyntaxError: invalid syntax

It's saying that the ":" is invalid syntax (?). If I remove it, it doesn't work either. Any idea?

答案1

得分: 2

The error with the code is the use of the for loop in this specific situation instead of the while loop. The for loop is used to perform the same action on each element, but you want to check if the value of temp_o is not present in the Units list, and if so, you want to have the user input a valid unit of measurement until they get it right.

Units = ["celsius", "fahrenheit", "kelvin"]
temp_o = input("Do you wish to convert Celsius, Fahrenheit, or Kelvin? --> ").lower()
while temp_o not in Units:
temp_o = input("Insert an accepted unit of measurement: ").lower()

  1. Add parentheses to the Units variable to make it a list.
  2. Instead of writing multiple versions of the same temperature as Celsius or celsius, you can simply change all temperatures to lowercase and use the "lower" method with the temp_o variable.
  3. Replace "for" with "while."

This should make it work.

英文:

The error with the code is the use of the for loop in this specific situation instaed of the while loop. The for loop is used to perform the same action on each element, but you want to check if the value of temp_o is not present in the Units list, and if so, you want to have the user to input a valid unit of measurement, until he got it right.

Units = ["celsius", "fahrenheit", "kelvin"]
temp_o = input("""Do you wish to convert Celsius, Fahrenheit, or Kelvin?
--> """).lower()
while temp_o not in Units:
    temp_o = input("Insert an accepted unit of measurement: ").lower()
  1. Add parentheses to the Units variable to make it a list.
  2. Instead of writing multiple versions of the same temperature as Celsius or celsius, you can simply change all temperatures to lowercase and use the "lower" method with the temp_o variable.
  3. Replace for with while.

This should make it work.

huangapple
  • 本文由 发表于 2023年6月29日 05:14:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76576749.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定