Calling other scripts and using variables (Python) - 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.

Related

unresolved NameError while writing Blackjack gameflow

I am currently writing a game of Blackjack using python 2.7. as part of the app's gameflow I have defined a new function called player_turn(), in which I required a user input that would result in different scenarios depending on the input ("hit" would give the player another card, and "hold" would end the player's turn and pass it on to the dealer. otherwise would result in a customized error)
def player_turn():
if sum(player_card_numbers) < 21:
user_decision = input('would you like to hit or hold?')
if user_decision == 'hit':
player_cards.append(deck.draw())
print player_cards, dealer_cards
player_turn()
elif user_decision == 'hold':
print "Dealer's turn!"
dealer_turn()
else:
print "player must choose 'hit' or 'hold'"
player_turn()
elif sum(player_card_numbers) == 21:
print "Blackjack!"
dealer_turn()
else:
print "Player Burnt! \nDealer's turn!"
dealer_turn()
It is worth mentioning that the code was originally written in python 3.7, and was changed later on. the code worked perfectly with 3.7.
Now I get this error:
NameError: name 'hit' is not defined
I would love some advice on how to solve this issue, as well as an explanation on why this would happen. :)
The problem is this line:
user_decision = input('would you like to hit or hold?')
In Python2, input() has an eval() nature to it, so it's evaling your answer: hit
>>> user_decision = input('would you like to hit or hold?')
would you like to hit or hold?hit
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'hit' is not defined
>>>
The coding standard for Python 2 is to not use input() but rather use raw_input() instead:
>>> user_decision = raw_input('would you like to hit or hold?')
would you like to hit or hold?hit
>>> user_decision
'hit'
>>>
In Python 3, the input() function is equivalent to raw_input() in Python 2.

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

Making something compatible with python 3 and 2

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)

Python: Returning a list doesn't work

I am trying to make a program that can add/delete/show students in a class, and the 5 classes are 5 lists in a list.
Help is greatly appreciated.
When I run this code:
global classes
def intro():
print("Welcome to Powerschool v2.0!")
print("Actions:")
print("1. Add Student")
print("2. Delete Student")
print("3. Show Students in a Class")
print("4. Show All Students")
x = int(input())
while x<1 or x>4:
print ("Please choose an action, 1-4.")
x = int(input())
if x == 1:
action1()
elif x == 2:
action2()
elif x == 3:
action3()
elif x == 4:
action4()
classes = [[],[],[],[],[]]
return classes
def action1():
print("Which Class? 1-5")
a = int(input())
print("Please enter the student's name.")
z = input()
classes[a-1].append(z)
again()
def action2():
print ("Which Class? 1-5")
print ("Which student?")
again()
def action3():
print ("Which Class? 1-5")
y = int(input())
if y == 1:
print (classes[0])
elif y == 2:
print (classes[1])
elif y == 3:
print (classes[2])
elif y == 4:
print (classes[3])
elif y == 5:
print (classes[4])
again()
def action4():
print (classes)
again()
def again():
print("Would you like to do something else? y/n")
h = input()
if h == "y":
intro()
else:
quit
def main():
intro()
main()
My error is:
Traceback (most recent call last):
File "C:\Documents and Settings\user1\My Documents\Downloads\az_studenttracker.py", line 67, in <module>
main()
File "C:\Documents and Settings\user1\My Documents\Downloads\az_studenttracker.py", line 65, in main
intro()
File "C:\Documents and Settings\user1\My Documents\Downloads\az_studenttracker.py", line 19, in intro
action1()
File "C:\Documents and Settings\user1\My Documents\Downloads\az_studenttracker.py", line 33, in action1
classes[a-1].append(z)
NameError: name 'classes' is not defined
I did return classes at the end of intro() but I see that doesn't work.
I followed some suggestions, and nothing really happened :/
You're defining classes in your intro method, and, even though it's returning it, your action1 method doesn't see any variable named classes anywhere.
Relevant answer on Python scope and relevant documentation.
return doesn't do what you think it does. return statements are a way of passing execution control back up a context (For example, from intro() to main()), with the ability to send back some information for the higher context to use. Although you're passing classes back to main(), you never do anything with it at that context so it goes away.
One way to solve the problem would be to declare classes as a global variable. This is the easiest thing to do, but isn't generally good design. You could do this either by using the global keyword before declaring the local variable classes in intro() (See this question for guidance on global), or by declaring classes outside any of your functions.
Another solution would be to pass classes as a parameter to your action functions.
In either case, you would need to declare classes before any calls to your action functions.
This is because classes is out of scope for the second two methods. Therefore, you have two options:
Option 1
Pass classes to the methods action1(), action2(), etc like so:
def action1(classes)
...and the when you call it:
action1(classes) //with the classes var you just made
Option 2 (recommended)
Simply put the classes var outside your methods or declare it global like so:
global classes = [[],[],[],[],[]]
...right before:
def intro()
In general, you should read up on how return works; it is not necessary in the code you wrote
classes only exists in intro():, you would have to declare it as a global variable to access it in other functions or declare it outside the function.
classes = [[],[],[],[],[]] # can be accessed by action3() ,action4()
def intro():

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