【问题标题】:Making something compatible with python 3 and 2制作与 python 3 和 2 兼容的东西
【发布时间】:2015-06-27 15:59:50
【问题描述】:

我正在尝试构建一个抽奖系统,允许您选择参与者,然后将其打印到屏幕上。我想让它与python3和python2交叉兼容。我的输入有问题。它要求您输入参与者姓名的输入一直给我一个错误:

Traceback (most recent call last): File "employee-raffle.py", line 20, in <module> participant_list.append(input("Enter person " + str(len(participant_list) + 1) + ": ")) File "<string>", line 1, in <module> NameError: name 'test' is not defined

来自代码:

# Import modules
import time
import random

print("Welcome to the raffle ")
participants = 0

# Checks how many people are participating in the raffle
while True:
    try:
        participants = int(input("\nHow many people are there in the raffle? \n"))
        break
    except:
        print("Invalid option")
        continue

# Creates a list and asks user to input the names of everyone
participant_list = []
while participants > len(participant_list):
    participant_list.append(input("Enter person " + str(len(participant_list) + 1) + ": "))

# Chooses a random person
random_participant = participant_list[random.randint(0,len(participant_list ) - 1)]

# Prints the person to the screen
print("AND THE WINNER IS:")
print("3")
time.sleep(1)
print("2")
time.sleep(1)
print("1")
time.sleep(1)
print(random_participant)

它似乎在 python 3 中运行良好。我真的希望它能够与两者一起使用,因为我正在尝试学习如何使事物交叉兼容,因为在我看来这是一个重要的编程实践。

【问题讨论】:

  • 输入在 Python 2 和 3 中不是同一个函数。
  • 解释here

标签: python backwards-compatibility


【解决方案1】:

This blog 提供了一些使 python 文件同时兼容 python 3 和 2 的示例。

他提到的接受输入的一个具体例子是:

def printme(s):
    sys.stdout.write(str(s))

def get_input(prompt):
    if sys.hexversion > 0x03000000:
        return input(prompt)
    else:
        return raw_input(prompt)

【讨论】:

  • 谢谢,博客帮我找到了很多有用的东西。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-31
  • 1970-01-01
  • 1970-01-01
  • 2018-02-02
相关资源
最近更新 更多