python - 跳过 Elif 条件
问题描述
在代码执行期间,程序会跳过所有 ELIF 条件,直接进入 ELSE,即使 ELIF 条件为 TRUE
a = 0
b = 0
c = 0
r = 0
soma = 1
sub = 2
div = 3
mult = 4
print('enter the number corresponding to the operation you want to do:\n')
print('Sum [1]')
print('Subtraction[2]')
print('Divisao [3]')
print('Multiplication [4]')
r = int(1)
while (r == 1):
operacao = 0
operacao = input('\n>')
if operacao == soma:
a = int(input('Enter the value of a:'))
b = int(input('Enter the value of b:'))
c = a + b
print ('\n A Soma de {} mais {} equivale a: {}'.format(a,b,c))
elif operacao == sub:
a = int(input('Enter the value of a:'))
b = int(input('Enter the value of b:'))
c = a - b
print ('\n A subtracao de {} menos {} equivale a: {}'.format(a,b,c))
elif operacao == div:
a = int(input('Enter the value of a:'))
b = int(input('Enter the value of b:'))
c = a / b
print ('\n A divisao de {} de {} equivale a: {}'.format(a,b,c))
elif operacao == mult:
a = int(input('Enter the value of a:'))
b = int(input('Enter the value of b:'))
c = a * b
print ('\n The multiplication of {} by {} is equivalent to: {}'.format(a,b,c))
else: #going direct to here...
print('\n Unrecognized operation')
预计 ELIF 条件在 true 时会起作用,但不起作用。
解决方案
input
返回 a string
,因此您需要这样做operacao = int(input('\n>'))
,否则str == int
将始终是False
:
x = input("\n>") # I've input 5
x
# '5'
# returns False because x is a string
x == 5
# False
# converts x to int, so returns True
int(x) == 5
# True
# returns True because we are comparing to a string
x == '5'
# True
所以对于你的代码:
# convert the return of input to int for comparing against other ints
operacao = int(input('\n>')) # I'll put 3
if operacao == 1:
print('got one')
elif operacao == 3:
print('got three')
# got three
推荐阅读
- android - 未知属性 layout_width
- jquery - @Html.RenderPartial 与 jQuery.load()
- angular - 角度为 7 的 Ng-fullcalendar
- javascript - 反应路由器,路由器不工作
- python - OpenStack sdk won't use keystone v3?
- vb.net - 从 DataGridView 和 Access 数据库中删除错误
- kotlin - get array from inside many objects in kotlin
- excel - Excel sort with formula in cell
- python - my tkinter doesnt show up anything i have coded
- javascript - Merging objects with multiple properties in JS