首页 > 解决方案 > 用 Python 自动化无聊的东西:Hello World Code 1

问题描述

我正在尝试通过这本书“用 Python 自动化无聊的东西”来学习 Python。但是,我坚持第一个代码本身。

我在我的编辑器文件中简单地复制了这段代码:

print('Hello world!')
print('What is your name?') # ask for their name
myName = input() 
print('It is good to meet you, ' + myName)
print('The length of your name is:') 
print(len(myName)) 
print('What is your age?') # ask for their age 
myAge = input()
print('You will be ' + str(int(myAge) + 1) + ' in a year.')

在 Shell 窗口中,我得到了前两行,但是一旦我输入我的名字,它就会给我一个错误。我不知道我做错了什么。

Python 2.7.8 (default, Jun 30 2014, 16:08:48) [MSC v.1500 64 bit
(AMD64)] on win32 Type "copyright", "credits" or "license()" for more
information.
>>> ================================ RESTART ================================
>>>  Hello world! What is your name? Ashima

Traceback (most recent call last):   File "C:\Users\sahnas01\Desktop\PYTHON\hello.py", line 4, in <module>
myName = input()   File "<string>", line 1, in <module> NameError: name 'Ashima' is not defined

标签: python

解决方案


首先,您应该使用 Python 3+,因为不推荐使用 2。然后在您提出问题时查看您的代码标记以正确理解它。此代码应该适用于 Python3。

  1. 打印你好世界!
  2. 问题后在新行上使用用户输入进行变量
  3. 从输入打印文本+变量
  4. 打印文本 + var 的长度(阅读str函数和len函数)
  5. 在包含年龄的新行上输入变量
  6. 打印文本 + 带有年龄的变量 + 文本
print('Hello world!')
myName = input('What is your name?\n')
print('It is good to meet you, ' + myName)
print('The length of your name is:' + str(len(myName)))
myAge = input('What is your  age?\n')
print('You will be ' + str(int(myAge) + 1) + ' in a year.')

推荐阅读