如果语句在我的程序中不起作用
If statement is not working in my program
import time
name=input("Enter your name:")
currentTime = int(time.strftime('%H'))
if currentTime < 12 :
print('Good morning,'+name)
elif currentTime > 12 :
print('Good afternoon,'+name)
else :
print('Good evening,'+name)
def main():
import random
guess: int = input('Enter a number the between 1 and 2 :')
if guess <= "2":
num: int = random.randint(1, 2)
print("the number is ", num)
if num == guess: #### this if statement is not working
print('you won'
'your promote to level 2')
else:
print("You lost", ",Lets try again")
repeat = input('Do you want to try again:')
if repeat == "yes":
main()
else:
print("Good bye")
exit()
else:
print("the number you entered is grater than 5,Please enter a number between 1 and 2")
main()
main()
此代码中的 if 语句不起作用(我在代码中突出显示了 if 语句)但是 else 语句对这两种情况都有效。
在你的代码中 guess
是类型 str
,请阅读 input 的文档:
The function then reads a line from input, converts it to a string
(stripping a trailing newline), and returns that
当您执行 guess: int
时,您使用的是 type hint。文档说:
The Python runtime does not enforce function and variable type
annotations. They can be used by third party tools such as type
checkers, IDEs, linters, etc.
在您的 if
中,您试图将 int
与 str
进行比较。 运行这个在Python控制台可以看到:
print(1 == '1') # --> False
print(1 == 1) # --> True
所以你需要做的就是将它显式转换为 int
:
guess = int(input('Enter a number the between 1 and 2 :'))
并将第一个if
改为:
if guess <= 2:
...
(删除 "2"
中的引号)。
通过这些更改,您的 if 语句将起作用。
import time
name=input("Enter your name:")
currentTime = int(time.strftime('%H'))
if currentTime < 12 :
print('Good morning,'+name)
elif currentTime > 12 :
print('Good afternoon,'+name)
else :
print('Good evening,'+name)
def main():
import random
guess: int = input('Enter a number the between 1 and 2 :')
if guess <= "2":
num: int = random.randint(1, 2)
print("the number is ", num)
if num == guess: #### this if statement is not working
print('you won'
'your promote to level 2')
else:
print("You lost", ",Lets try again")
repeat = input('Do you want to try again:')
if repeat == "yes":
main()
else:
print("Good bye")
exit()
else:
print("the number you entered is grater than 5,Please enter a number between 1 and 2")
main()
main()
此代码中的 if 语句不起作用(我在代码中突出显示了 if 语句)但是 else 语句对这两种情况都有效。
在你的代码中 guess
是类型 str
,请阅读 input 的文档:
The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that
当您执行 guess: int
时,您使用的是 type hint。文档说:
The Python runtime does not enforce function and variable type annotations. They can be used by third party tools such as type checkers, IDEs, linters, etc.
在您的 if
中,您试图将 int
与 str
进行比较。 运行这个在Python控制台可以看到:
print(1 == '1') # --> False
print(1 == 1) # --> True
所以你需要做的就是将它显式转换为 int
:
guess = int(input('Enter a number the between 1 and 2 :'))
并将第一个if
改为:
if guess <= 2:
...
(删除 "2"
中的引号)。
通过这些更改,您的 if 语句将起作用。