这是我的代码,但它不适用于python 3.4
print ("Hello")
b = str(input("Where do you go?\n"))
def place(a):
if a == "r" or a > 0:
print("Turned right.")
elif a == "l" or a < 0:
print("Turned left.")
else:
print("Invalid")
a = int(str(input("Where do you go?\n")))
place(a)
place(b)
我想制作&#39; b&#39;成为一个int或一个字符串
答案 0 :(得分:3)
使用try except
块:
b = input("Where do you go?\n")
def place(a):
try:
a = int(a)
# code for a being a number
except ValueError:
# a is a letter
答案 1 :(得分:1)
isdigit()方法将告诉您字符串是否为整数。
a = "1"
if a.isdigit():
a = int(a)
答案 2 :(得分:0)
这不是你想要的吗?
def place(a):
try:
b = int(a)
except ValueError:
b = 0
if (b != 0):
if b > 0:
print("Turned right.")
else:
print("Turned left.")
elif (type(a) is str) and ((a == 'r') | (a == 'l')):
if a == 'r':
print("Turned right.")
else:
print("Turned Left")
else:
print("Invalid")
raise TypeError("Nothing to do")