我试图得到一个准确的年龄,但这不起作用,它给了我错误,有时还会重复。我已经试着让它工作几个小时了。但我想问题出在finally上。我尝试了except,但它只给我错误。我该怎么解决它呢?
end04 = False
while not end04:
Age = input("Age: ")
try:
int(Age)
end04 = True
finally:
if Age[-1:] == 'w':
Age.replace('w','')
int(Age)
Age /= 52
end04 = True
elif Age[-1:] == 'm':
Age.replace('m', '')
int(Age)
Age /= 12
end04 = True
else:
end04 = False
print("Only enter m or w after number or just number")如果我放在最后,它只是重复说“只在数字后面输入m或w,或者只输入数字”。
如果我put except,它会给出一个错误(当我输入3M时)
int(Age) ValueError:基数为10的int()的文本无效:'3m‘
发布于 2021-02-14 14:20:52
end04 = False
while not end04:
Age = input("Age: ")
try:
int(Age)
end04 = True
except ValueError: # Here your are trying to catch the Exception (when m/w in input), so you need to use except with the Exception you want to catch
if Age[-1:] == 'w':
Age = Age.replace('w','') # string.replace function return's the replaced string therefore need to assign it back to Age Variable.
Age = int(Age) # similarly int() also returns the type casted value.
Age /= 52
end04 = True
elif Age[-1:] == 'm':
Age = Age.replace('m', '')
Age = int(Age)
Age /= 12
end04 = True
else:
end04 = False
print("Only enter m or w after number or just number")我已经修复了你的代码。
也要调查一下,
如果所有字符都是数字(0-9),则
发布于 2021-02-14 14:43:42
这就是你的最终程序的样子,以更简单的方式处理所有类型的输入。
import re
end04 = False
divider = 1
while not end04:
Age = input("Age: ")
try:
age = re.findall(r'\d+\w', Age)
if len(age) > 0:
letter = age[0][-1]
if letter.isnumeric() or (letter in ['w', 'm']):
if letter in ['w', 'm']:
age = int(age[0][:-1])
divider = 12
if letter == 'w':
divider = 52
else:
age = int(age[0])
print('age', age)
age /= divider
print('output', age)
end04 = True
finally:
if not end04:
print("Only enter m or w after number or just number")输出:
Age: 32
age 32
output 32.0
Age: 32w
age 32
output 0.6153846153846154
Age: 32m
age 32
output 2.6666666666666665https://stackoverflow.com/questions/66192769
复制相似问题