Skip to main content
 首页 » 编程设计

python之为什么我们在循环之前将变量 "option"1 的值赋值

2025年05月04日17arxive

我是编程新手,我选择 python 作为我的第一语言,因为它很简单。但是我在这里对这段代码感到困惑:

option = 1  
while option != 0: 
    print "/n/n/n************MENU************" #Make a menu 
    print "1. Add numbers" 
    print "2. Find perimeter and area of a rectangle" 
    print "0. Forget it!" 
    print "*" * 28 
 
    option = input("Please make a selection: ") #Prompt user for a selection       
    if option == 1: #If option is 1, get input and calculate  
        firstnumber = input("Enter 1st number: ") 
        secondnumber = input("Enter 2nd number: ")  
        add = firstnumber + secondnumber 
        print firstnumber, "added to", secondnumber, "equals", add #show results   
 
    elif option == 2: #If option is 2, get input and calculate 
        length = input("Enter length: ") 
        width = input("Enter width: ") 
        perimeter = length * 2 + width * 2 
        area = length * width 
        print "The perimeter of your rectangle is", perimeter #show results        
        print "The area of your rectangle is", area 
 
    else: #if the input is anything else its not valid 
        print "That is not a valid option!" 

好的 好的,我得到了 Option 变量下面的所有内容。我只想知道为什么我们给Option=1赋值,为什么把它加在程序的最前面,它的作用是什么。我们也可以改变它的值(value)。请让我用简单的语言理解它,因为我是编程新手。

请您参考如下方法:

如果您没有在程序开始时创建变量 option,则行

 while option != 0: 

会中断,因为还没有 option 变量存在。

至于如何改变它的值,注意每行都会改变它:

option = input("Please make a selection: ") 

发生 - 将其值重新分配给用户的输入。