Making something compatible with python 3 and 2 - python

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.

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)

Related

clear the python output stream

So I'm trying to code an assassin game generator but to do so, after it shows the player who their target is, it needs to clear the output stream.
I figured out that you have to manually clear it in Pycharm, so I decided to use the os.system("cls") method and open the python terminal:
import random
import sys
import time
import os
#Creating the players
np = input("How many players do you want to set? ")
np = int(np)
players = []
enemies = []
for player in range(1, np+1):
player = str(player)
x = (input("Player #" + player + ": "))
x = str(x)
x = x.title()
players.append(x)
enemies.append(x)
random.shuffle(players)
enemies = players.copy()
enemies.insert(0, enemies.pop(-1))
picked = []
def clear():
os.system("cls")
print("Loading players and targets:")
time.sleep(2)
print("\n")
for p in range(np):
r = random.randrange(np)
while players[r] in picked:
r = random.randrange(np)
input("\033[1m" + players[r] + ", your target is: ")
input("\033[31;1;4m" + enemies[r] + "\033[0m (Press Enter to continue)")
picked.append(players[r])
clear()
print("\n")
I input the number of players, but when I input the first name, it gives me the following error:
How many players do you want to set? 5
Player #1: Bob
Traceback (most recent call last):
File "C:\Users\Bob\PycharmProjects\test\assassins.py", line 15, in <module>
x = (input("Player #" + player + ": "))
File "<string>", line 1, in <module>
NameError: name 'Bob' is not defined
I've tried to change a lot of different things but none work.
Version: Python 3.4

Custom python function is not running

names=["aaa","bbb","ccc","ddd","eee"]
itMarks=[90,98,87,98,78]
def printMainMenu():
print(" Main Menu")
print(" =========")
print(" (1)Add Student")
print(" (2)Search Student")
print(" (3)Delete Student")
print(" (4)List Student")
print(" (5)Exit")
choice = int(input("Enter Your choice[1-5]:"))
return choice
def searchStudent(names,itMarks):
name = input("Enter Name")
i = names.index(names)
print("Index is" + i)
def deleteStudent(student,itMarks):
name = input("Enter Name to remove")
student.remove(names)
print("Successfully Deleted" + names)
def removeStudent(names):
name = input("Enter name to remove")
name.remove(name)
print("Successfully deleted" + names)
def addStudent(names, itMarkas):
name = input("Enter Name")
names.append(names)
itMarks = input("Enter IT Marks")
itMarks.append(itMarks)
def listStudent(names, itMarks):
for i in range(0, len(names)):
print(names[1], "", itMarks[i])
names = []
itMarks = []
choice = 1
while choice >= 1 and choice <= 4:
choice = printMainMenu()
if choice == 1:
addStudent(names, itMarks)
elif choice == 2:
searchStudent(names, itMarks)
elif choice == 3:
deleteStudent(names, itMarks)
elif choice == 4:
listStudent(names, itMarks)
elif choice == 5:
print("Exit from the program")
else:
print("invalid choice!")
choice = 1
I am new to the programming in Python. The following Python code is written to do some tasks with the array. There are two array named names and itMarks. And there are some functions :
addStudent() - To add students to the array
searchStudent() - To search a student with in the list.
deleteStudent() - To delete the given student from the list.
listStudent() - To list out the all the names of the students in the list.
When the program runs, it asks to select a choice. Then it do the task according to their choice. But when I run this coding it shows the errors.
Please help me. Thanks in advance.
ERROR :
When I select the choice 1 (Add student) and input name after the error is yield.
Traceback (most recent call last):
File "C:\Users\BAALANPC\Desktop\new 3.py", line 59, in <module>
addStudent(names, itMarks)
File "C:\Users\BAALANPC\Desktop\new 3.py", line 42, in addStudent
name = input("Enter Name")
File "<string>", line 1, in <module>
NameError: name 'rtrt' is not defined
Their so many mistakes in naming
In addStudent
def addStudent(names, itMarkas):
name = input("Enter Name")
names.append(name) # names cant appent it should be name
itMark = input("Enter IT Marks") # here itmark not itMarks
itMarks.append(itMark)
In searchStudent
def searchStudent(names,itMarks):
name = input("Enter Name")
i = names.index(name) # try to find index of name not names
print("Index is" + i)
In deleteStudent
def deleteStudent(student,itMarks):
name = input("Enter Name to remove")
student.remove(name) # try to remove name not names
print("Successfully Deleted" + name)
after change above I run its running you have to also change the naming of the variable for all methods
Output
Main Menu
=========
(1)Add Student
(2)Search Student
(3)Delete Student
(4)List Student
(5)Exit
Enter Your choice[1-5]:1
add student
Enter Name"aaa"
Enter IT Marks111
Main Menu
=========
(1)Add Student
(2)Search Student
(3)Delete Student
(4)List Student
(5)Exit
Enter Your choice[1-5]:
I'm assuming this is the correct form:
def searchStudent(names,itMarks):
name = input("Enter Name")
i = names.index(name)
print("Index is" + i)
note that I changed names to name.
also the same mistake again
def deleteStudent(student,itMarks):
name = input("Enter Name to remove")
student.remove(name)
print("Successfully Deleted" + names)
tl;dr revise your code
searchStudent(): You shouldn't need the itMarks argument if you're not using it inside your function at all. names refers to the list of names, but you are really trying to search name. i is an integer that is attempting to be concatenated with a string. Not allowed. It should be str(i).
deleteStudent(): Better to keep your arguments consistent and use names rather than student. Again, same problem as above, should be .remove(name) and you shouldn't need the itMarks argument. print statement should refer to name not names.
removeStudent(): This is the same code as deleteStudent(), but not used, so not sure why it's there.
addStudent(): Typo in the argument, .append(name). You have a global variable and a local variable named the same thing, which are conflicting to the program. Change the input set to itMark and .append(itMark).
listStudent(): print statement has a typo, 1 should be i. Not sure why the empty string is included as well.
Underneath your function def's, you restate your variables as empty lists. This can lead to ValueErrors from a lot of your functions as you're trying to look something up or modify something in an empty list. Simply delete this code.
Additionally, any error will break your while loop. I suggest adding more booleans or using a try except clause to catch these errors.
Good luck!

Get variable name from input string without using an elif statement for all possibilities

I'm new to programming in Python 3.4.3 but I've started my first project that will help me as a chemist. I've created a series of code that asks the user to input the name of a chemical (e.g. water or ethanol) and then returns a list of chemical properties of the chemical. My code is below. I left out the chemical data I hard coded to make it easier to read hopefully.
print ("Welcome to [program name]! Copyright (C) 2015 [name omitted] All Rights Reserved.")
print ("----" * 4)
class Chemical():
def __init__(self, data):
self.data = data
def getData(self):
return self.data
chemical1 = Chemical("Data\nData\nData\n")
chemicalName = input("Choose a chemical: ")
if chemicalName == "chemical1":
print (chemical1.getData())
elif chemicalName == "Other chemical name":
# I now have a lot of elif statements, to account for all possible chemicals
print (other_chemical.getData())
else:
print ("\nThe chemical you chose hasn't been added yet\n")
When executed, if the input is chemical1 what will be produced is:
data
data
data
Basically, I have a huge list of chemicals with their data hard coded into the script and a large number of elif statements to account for each chemical (there are now 26 chemicals). The whole thing works perfectly but I would like to reduce the number of elif statements in order to reduce the number of lines of code. Perhaps by writing a for loop or some other expression as suggested by a friend of mine who has some experience with Python. I'm still a beginner so I'm not sure of all the different methods.
I tried this:
chemicalName = input("Choose a chemical: ")
print (chemicalName.getData())
but when I ran the script I got an error that said:
Traceback (most recent call last):
File "C:\Users\john\Desktop\test.py", line 42, in <module>
print (chemicalName.getData())
AttributeError: 'str' object has no attribute 'getData'
The idea is that when I input a chemical e.g. chemical2, I want chemicalName put straight into print (chemicalName.getData()) with the value of chemical2 which then prints the data I inputted for chemical2 = Chemical("Data\nData\nData")
I'm not sure what I can do at this point. To give you all an idea, I have around 150 lines of code with all the elif statements so any ideas or feedback is very welcome.
You can use a dictionary and work like this
class Chemical():
def __init__(self, name, blah1, blah2):
self.blah1 = blah1
self.blah2 = blah2
chemicals = {}
chemical1 = Chemical("chemical1", "Data", "Data")
chemicals[chemical1.name] = chemical1
chemicalName = input("Choose a chemical: ")
if chemicalName in chemicals:
print (chemical1.name + chemical1 + blah1 + chemical1.blah2)
else:
print ("\nThe chemical you chose hasn't been added yet\n")

Calling other scripts and using variables (Python)

i'm not sure how to go about this...
I want to use import to go to another script (Once it's called, the original script has finished) but I need the second script to print a variable from the original.
So, I can import the second script and use the prints fine, however if I try and import the original script so I can access the variable..
But if I do that, it just gives me an error:
Traceback (most recent call last):
File "C:\Users\luke\Desktop\k\startGame.py", line 2, in <module>
import Storyline
File "C:\Users\luke\Desktop\k\Storyline.py", line 1, in <module>
import startGame
File "C:\Users\luke\Desktop\k\startGame.py", line 56, in <module>
Storyline.startGame1()
AttributeError: 'module' object has no attribute 'startGame1'
I am trying to print this:
print ("I see you have picked " + startGame.currentPokemon)
and I am calling it like this:
Storyline.startGame1()
and the currentPokemon is
currentPokemon = inputKK
(InputKK is an input of the starter pokemon)
Is there any way to do this? And yes, i'm making a pokemon game in Python, but it's a version that isn't using real pokemon names..
Storyline script:
import startGame
def startGame1():
print ("Welcome to the H.Q of I.O.D")
print ("I am Professor Steel.")
print ("I see you have picked " + startGame.currentPokemon)
startGame script:
import Storyline
inputKK = input("Choose from, 'Craigby', 'Robinby' or 'KKby' ")
if(inputKK == "Craigby"):
print("Craigby is a electric type.")
print("Craigby: Attack = 7, Defence = 3, Health = 6, Speed = 12")
if(inputKK == "Robinby"):
print("Robinby is a fire type.")
print("Robinby: Attack = 6, Defence = 5, Health = 7, Speed = 7")
if(inputKK == "KKby"):
print("KKby is a water type.")
print("KKby: Attack = 5, Defence = 8, Health = 11, Speed = 5")
print("")
os.system('cls')
currentPokemon = inputKK
counter = 0;
while(counter < 1):
print("Welcome to pokeby.")
print("Type S for [STORYLINE]")
print("Type R for pokemon in the field [CURRENT IS GRASS] ")
print("Type Q for [QUIT]")
inputMainMenu = input("S/R/Q ...")
if(inputMainMenu == "S"):
os.system('cls')
counter = counter + 2
Storyline.startGame1()
if(inputMainMenu == "R"):
os.system('cls')
counter = counter + 2
if(inputMainMenu == "Q"):
os.system('cls')
inputExit = input("Are you sure you want to quit? Y/N ")
if(inputExit == "Y" or inputExit == "y"):
print("K")
else:
counter = counter + 1
Don't import StartGame in your Storyline script. Instead, just pass the desired value to your StartGame1 function.
# Storyline.py
def startGame1(currentPokemon):
print ("Welcome to the H.Q of I.O.D")
print ("I am Professor Steel.")
print ("I see you have picked ", currentPokemon)
Then in startGame you call Storyline.startGame1(inputKK) passing the name of the Pokemon.
BTW, it's a little confusing that your startGame1 function isn't in the module startGame...
You are trying to import Storyline into startGame, and also trying to import startGame into Storyline. You just can't do this kind of recursive import. While importing startGame, Storyline is coming across your Storyline.startGame1() call before startGame1() has been defined, so you get the no attribute error.
You should restructure your files so that this becomes unnecessary.
[edit: don't listen to me; it was late and I didn't think hard enough about what I was saying.]
You can't reference attributes or methods in a module like that. What you need is to put your methods in a class. Alternatively, I think you could do from Storyline import startGame1(). But really, use classes [if you want to]; [i think] they are good. Python docs on classes here.

Python custom modules - error with example code

I am reading the book "Python Programming for the Absolute Beginner (3rd edition)". I am in the chapter introducing custom modules and I believe this may be an error in the coding in the book, because I have checked it 5 or 6 times and matched it exactly.
First we have a custom module games.py
class Player(object):
""" A player for a game. """
def __init__(self, name, score = 0):
self.name = name
self.score = score
def __str__(self):
rep = self.name + ":\t" + str(self.score)
return rep
def ask_yes_no(question):
""" Ask a yes or no question. """
response = None
while response not in ("y", "n"):
response = input(question).lower()
return response
def ask_number(question, low, high):
""" Ask for a number within a range """
response = None
while response not in range (low, high):
response = int(input(question))
return response
if __name__ == "__main__":
print("You ran this module directly (and did not 'import' it).")
input("\n\nPress the enter key to exit.")
And now the SimpleGame.py
import games, random
print("Welcome to the world's simplest game!\n")
again = None
while again != "n":
players = []
num = games.ask_number(question = "How many players? (2 - 5): ", low = 2, high = 5)
for i in range(num):
name = input("Player name: ")
score = random.randrange(100) + 1
player = games.Player(name, score)
players.append(player)
print("\nHere are the game results:")
for player in players:
print(player)
again = games.ask_yes_no("\nDo you want to play again? (y/n): ")
input("\n\nPress the enter key to exit.")
So this is exactly how the code appears in the book. When I run the program I get the error IndentationError at for i in range(num):. I expected this would happen so I changed it and removed 1 tab or 4 spaces in front of each line from for i in range(num) to again = games.ask_yes_no("\nDo you want to play again? (y/n): ").
After this the output is "Welcome to the world's simplest game!" and that's it.
I was wondering if someone could let me know why this is happening?
Also, the import games module, is recognized in Eclipse after I added the path to PYTHONPATH.
I actually have this book myself. And yes, it is a typo. Here is how to fix it:
# SimpleGame.py
import games, random
print("Welcome to the world's simplest game!\n")
again = None
while again != "n":
players = []
num = games.ask_number(question = "How many players? (2 - 5): ", low = 2, high = 5)
for i in range(num):
name = input("Player name: ")
score = random.randrange(100) + 1
player = games.Player(name, score)
players.append(player)
print("\nHere are the game results:")
for player in players:
print(player)
again = games.ask_yes_no("\nDo you want to play again? (y/n): ")
input("\n\nPress the enter key to exit.")
All I did was indent num 4 spaces and lined it up with the first for-loop.
You have an infinite loop here:
again = None
while again != "n":
players = []
If this is exactly the way it's printed in the book, the book does have an error.
You've got these two lines:
num = games.ask_number(question = "How many players? (2 - 5): ", low = 2, high = 5)
for i in range(num):
The second one is more indented than the first. That's only legal if the first one is a block-introducer like a for or while or if. Since it's not, this is an IndentationError. And that's exactly what Python is telling you.
(It's possible that you've copied things wrong. It's also possible that you're mixing tabs and spaces, so it actually looks right in your editor, but it looks wrong to Python. But if neither of those is true, the book is wrong.)
So, you attempted to fix it by dedenting everything from that for loop on.
But when you do that, only one line is still left under the while loop:
while again != "n":
players = []
There's nothing that can possibly change again to "n", so this will just spin forever, doing nothing, and not moving on to the rest of the program.
So, what you probably want to do is to indent the num = … line to the same level as the for i… line, so both of them (and all the stuff after) ends up inside the while loop.

Categories