Making something compatible with python 3 and 2

天大地大妈咪最大 提交于 2019-12-13 01:09:25

问题


I am trying to build a raffle system that allows you to choose participants and then print them to the screen. I want to make it cross compatible with python3 and python2. I am having problems with the inputs. The inputs down where it ask you to enter the participant names keep giving me an error:

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

From code:

# 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)

It seems to work fine in python 3. I really want it to work with both because I am trying to learn how to make things cross compatible as it is an important programming practice in my opinion.


回答1:


This blog has some examples of making a python file compatible with both python 3 and 2.

A particular example for taking input that he mentions is :

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

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


来源:https://stackoverflow.com/questions/31090659/making-something-compatible-with-python-3-and-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!