Skip to main content
 首页 » 编程设计

python之简单的原始输入和条件

2025年05月04日10myhome

我创建了简单的代码:

name = raw_input("Hi. What's your name? \nType name: ") 
age = raw_input("How old are you " + name + "? \nType age: ") 
 
if age >= 21 
    print "Margaritas for everyone!!!" 
else: 
    print "NO alcohol for you, young one!!!" 
 
raw_input("\nPress enter to exit.") 

在我到达“if”语句之前,它工作得很好......它告诉我我使用了无效的语法。

我正在尝试学习如何使用 Python,并且已经将代码弄乱了很多,但我无法弄清楚我做错了什么(可能是一些非常基本的东西)。

请您参考如下方法:

应该是这样的:

name = raw_input("Hi. What's your name? \nType name: ") 
age = raw_input("How old are you " + name + "? \nType age: ") 
age = int(age) 
 
if age >= 21: 
    print "Margaritas for everyone!!!" 
else: 
    print "NO alcohol for you, young one!!!" 
 
raw_input("\nPress enter to exit.") 

您漏掉了冒号。此外,您应该将年龄从字符串转换为整数。

希望这对您有所帮助!