英文:
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()
- Add parentheses to the Units variable to make it a list.
- 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.
- 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()
- Add parentheses to the Units variable to make it a list.
- 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.
- Replace for with while.
This should make it work.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论