2013-03-07 140 views
0
print("this program will calculate the area") 

input("[Press any key to start]") 

width = int(input("enter width")) 
if width < 0: 
    print ("please chose a number between 0-1000") 
    width = int(input("enter width")) 

if width > 1000000: 
    print ("please chose a number between 0-1000") 
    width = int(input("enter width")) 

height = int(input("Enter Height")) 

area = width*height 

print("The area is:",area) 

有没有一种方法可以压缩下面的代码,例如将它们放在一起,这样我就不必编写除了less then和greater then语句两次以外的同一行代码。Python if语句

width = int(input("enter width")) 
if width < 0: 
    print ("please chose a number between 0-1000") 
    width = int(input("enter width")) 

if width > 1000000: 
    print ("please chose a number between 0-1000") 
    width = int(input("enter width")) 

我已经试过

width = int(input("enter width")) 
if width < 0 and > 10000: 
    print ("please chose a number between 0-1000") 
    width = int(input("enter width")) 

但我得到没有爱。

我也不想键入

width = int(input("enter width")) 

声明两次,如果它能够得到帮助。

感谢 本

+0

不错的工作家伙,Ty为您的时间。 – BenniMcBeno 2013-03-08 00:10:28

回答

7

有几种方法可以做到这一点。最明显的是:

if width < 0 or width > 10000: 

,但我最喜欢的是这样的:

if not 0 <= width <= 10000: 
+0

真的你在哪里所有的礼拜这么谢谢,但这一个最适合我:) – BenniMcBeno 2013-03-07 11:09:44

0

你想说

if width < 0 or width > 10000: 
    print ("please chose a number between 0-1000") 
    width = int(input("enter width")) 
+1

没有人想说'宽度< 0 or > 10000'。 – eumiro 2013-03-07 09:51:34

+0

当然。更正:) – Himanshu 2013-03-08 10:05:12

0

if width < 0 and > 10000: 

应该读

if width < 0 or width > 10000: 

或者:

if not 0 <= width <= 10000: 
0

你错过可变宽度

if width < 0 or width> 10000: 
3

你需要一个循环。否则,如果用户持久存在,用户仍然可以输入无效值。 while语句将循环与条件组合在一起 - 它保持循环,直到条件被破坏。

width = -1 
while width < 0 or width > 10000: 
    width = int(input("enter width as a positive integer < 10000")) 

您使用的,如果在原来的问题语句语法不正确:

if width < 0 and > 10000: 

你想:

if not (0 < width < 1000): 
    ask_for_new_input() 

,或者更明确的方式:

if width < 0 or width > 1000: 
    ask_for_new_input() 
0

如果:

print("this program will calculate the area") 

res = raw_input("[Press any key to start]") 

def get_value(name): 
    msg = "enter {0}".format(name) 
    pMsg = "please choose a number between 0-1000" 
    val = int(input(msg)) 
    while val not in xrange(1, 1001): 
     print pMsg 
     val = int(input(msg)) 
    return val 


print("The area is: {0}".format(get_value('width') * get_value('height')))