从if语句更改整数值不起作用? (蟒蛇)

时间:2016-09-18 17:56:41

标签: python python-2.7

Python newb here。我正在寻找一个if语句,它根据输入改变一个整数值,然后循环代码。不幸的是,我有两个问题:

  1. 当亮度打印机接受输入后,该值 无论输入(-10,+ 10,设置为0等)
  2. ,打印都是100
  3. 无论用户输入的值是什么,都会打印else语句 匹配if语句。
  4. 我在这里做错了什么?

    # -*- coding: utf-8 -*-
    
    var = 1
    brightness = 100
    
    while var == 1 :  # This constructs an infinite loop
    
      print 'Brightness is ', brightness
    
      test1 = raw_input('up, down, on or off? ')
    
      if test1 == 'up':
         brightness = brightness + 10
         print brightness
      if test1 == 'down':
         brightness = brightness - 10
         print brightness
      if test1 == 'on':
         brightness = 100
         print brightness
      if test1 == 'off':
         brightness = 0
         print brightness
      else:
         print 'Try again'
    
    print "Good bye!"
    

2 个答案:

答案 0 :(得分:1)

var = 1
brightness = 100

while var == 1 :  # This constructs an infinite loop

print 'Brightness is ', brightness

test1 = raw_input('up, down, on or off? ')

if test1 == 'up':
    brightness = brightness + 10
    print brightness
elif test1 == 'down':
    brightness = brightness - 10
    print brightness
elif test1 == 'on':
    brightness = 100
    print brightness
elif test1 == 'off':
    brightness = 0
    print brightness
else:
    print 'Try again'

print "Good bye!"

答案 1 :(得分:0)

Andrew L.和Kalpesh Dusane回答了这个问题,谢谢!!!

我需要交换我的if for elif(否则如果)。

# -*- coding: utf-8 -*-

var = 1
brightness = 100

while var == 1 :  # This constructs an infinite loop

  print 'Brightness is ', brightness

  test1 = raw_input('up, down, on or off? ')

  if test1 == 'up':
     brightness = brightness + 10
     print brightness
  elif test1 == 'down':
     brightness = brightness - 10
     print brightness
  elif test1 == 'on':
     brightness = 100
     print brightness
  elif test1 == 'off':
     brightness = 0
     print brightness
  else:
     print 'Try again'

print "Good bye!"

代码很棒,谢谢!