clear the python output stream - python

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

Related

How do I create a card deck that returns an answer?

import random
def shuffled_deck():
basic_deck = list(range(2, 15))
random.shuffle(basic_deck)
return basic_deck
print(shuffled_deck())
def suits():
Suits_Deck = list('Spades','Hearts','Clubs','Diamonds')
random.shuffle(Suits_Deck)
return(Suits_Deck)
e = random.randint(0,3)
f = random.randint(0,3)
a = random.randint(0,11)
b = random.randint(0,11)
c = str(input("What is Player 1's name? "))
d = str(input("What is Player 2's name? "))
print(c+ ' drew card ' + shuffled_deck[a] + 'of'+ suits[e])
print(d+ ' drew card ' + shuffled_deck[b] + 'of'+ suits[f])'''
Okay so basically I need to make a deck of cards. I also have to have the code select a card at random and assign it to a player. For some reason when I try to run the code this error appears.
Traceback (most recent call last):
File "main.py", line 17, in <module>
print(c+ ' drew card ' + shuffled_deck[a] + 'of'+ suits[e])
TypeError: 'function' object is not subscriptable
Instead of shuffled_deck[a] use shuffled_deck()[a] and
Instead of suits[a] use suits()[a]
Both shuffled_deck and suits are functions that return list, so call function then use index to get the element fun()[index]
You need to get the list by calling the shuffled_deck function, then index the returned list, i.e. shuffled_deck()[a] instead of shuffled_deck[a].
The same applies for suits[a] - this should be written as suits()[a] to first call the function.
this is elaboration version from #dspencer and #Praveen answer.
so you want to print like :
player A drew card 5 of Clubs
player B drew card 3 of Spades
If this what you want, you might edit your code.
import random
def shuffled_deck(n):
basic_deck = list(range(2, 15))
random.shuffle(basic_deck)
return basic_deck[n]
def suits(n):
Suits_Deck = ['Spades','Hearts','Clubs','Diamonds']
random.shuffle(Suits_Deck)
return Suits_Deck[n]
e = random.randint(0,3)
a = random.randint(0,11)
#first attempt
print(' drew card ' + str(shuffled_deck(a)) + ' of '+ suits(e))
#second attempt
print(' drew card ' + str(shuffled_deck(a)) + ' of '+ suits(e))
note in the suits() fucntion, directly make a list using '[ ]' Python list
also your shuffled_deck[a], its not a proper way to call a function, use shuffled_deck(a). 'a' from randomint will be the index of basic_deck List.
Hope it help

how do i fix my problem with my tuple in python

i have a problem in python i have been told that is is to do with the tuple in the code the idle gives me this error after login
Traceback (most recent call last):
artist, song = choice.split()
ValueError: need more than 1 value to unpack
this is my full code
import random
import time
x = 0
print("welcome to music game please login below")
AuthUsers = {"drew":"pw","masif":"pw","ishy":"pw"}
#authentication
PWLoop = True
while PWLoop:
userName = input("what is your username?")
#asking for password
password = (input("what is the password?"))
if userName in AuthUsers:
if AuthUsers.get(userName) == password:
print("you are allowed to play")
PWLoop = False
else:
print("invalid password")
else:
print("invalid username")
#GAME
#SETTING SCORE VARIBLE
score = 0
#READING SONGS
read = open("SONGS.txt", "r")
songs = read.readline()
songlist = []
for i in range(len(songs)):
songlist.append(songs[i].strip())
while x == 0:
#RANDOMLY CHOSING A SONG
choice = random.choice(songlist)
artist, song = choice.split()
#SPLITTING INTO FIRST WORDS
songs = song.split()
letters = [word[0] for word in songs]
#LOOp
for x in range(0,2):
print(artist, "".join(letters))
guess= str(input(Fore.RED + "guess the song"))
if guess == song:
if x == 0:
score = score + 2
break
if x == 1:
score = score + 1
break
#printing score
Issue is due to these two lines:
choice = random.choice(songlist)
# choice will be single item from songlist chosen randomly.
artist, song = choice.split() # trying to unpack list of 2 item
# choice.split() -> it will split that item by space
# So choice must be a string with exact one `space`
# i.e every entry in songlist must be string with exact one `space`
As the format of your file https://pastebin.com/DNLSGPzd
And To fix the issue just split by ,
Updated code:
artist, song = choice.split(',')
Change artist, song = choice.split() to:
song, artist = choice.split(',')
this will fix your problem.
according to the data that you given, you should split with ,.\

Python code error in program should calculate the monthly average price for Google and tell us the best and worst six-month period for Google

I need help to figure out how to fix errors in my Python code Assignment.
Basically I need create a program that should calculate the monthly average price for Google and tell us the best and worst six-month period for Google.
The average price is defined as ((v1*c1)+(v2*c2)+(v3*c3)+(v4*c4)...+(vn*cn)) / (v1+v2+v3+v4...+vn) where vi is the volume for day i and ci is the adjusted close price for day i.
For this assignment we'll look at Google from 2004 to 2012. The data-set we'll need is a table in CSV format and can be downloaded from https://www.dropbox.com/s/qr7cu2kui654kgz/googlePrices.csv.
So far I've created the Python code below but it's show some errors message and I couldn't figure out.
Thank you in advance.
Regards,
Roberto Leal
============================================================
Code:
__author__ = 'Roberto'
def get_values():
import operator
data_file = open("googlePrices.csv")
def get_data_list(file_name):
data_list = [] # always start with an open list
for line_str in data_file:
data_list.append(line_str.strip().split(',')) # removes all commas from the csv file
return data_list
def monthlyAverage(list_of_tuples=[]):
averageList = []
currentYear_int = 2012
month_int = 11
sum_float = float()
count = 0
for a_tuple in list_of_tuples:
dateStr = a_tuple[0]
Floatdata = a_tuple[1]
listdate = dateStr.split(',')
Year_int = int(listdate[0])
month_int = int(listdate[1])
date_year_str = "Date: " + str(month_int) + "-" + str(currentYear_int)
if month_int != currentYear_int:
float_average = sum_float / count
list_average = [date_year_str , float_average]
average_tuple = tuple(list_average)
averageList.append(average_tuple)
current_month_int = month_int
sum_float = 0.0
count = 0
sum_float += Floatdata
count += 1
return averageList
def best_6_month(averageList):
averageList.sort()
print("The 6 best months fo google are: ")
print()
print(averageList)
def worst_6_month(averageList):
averageList.reverse()
print("The 6 worst months for google are: ")
print()
print(averageList)
optionStr = ""
if optionStr != "0":
print("------------------------------")
print("\n Google Stock Prices. 2004 - 2012")
print("------------------------------")
print("Please choose an option")
print()
print("1. Calculate Average")
print("2. View best six months")
print("3. View worst six months")
print("0. Exit program")
print()
optionStr = input("Enter you choice now: ")
if (len(optionStr) != 1) or (optionStr not in "0123"):
print("You have entered an invalid number!")
print("Please try again")
elif optionStr == "1":
monthlyAverage()
elif optionStr == "2":
best_6_month()
elif optionStr == "3":
worst_6_month()
elif optionStr == "0":
print("\n Exiting program... Goodbye.")
else:
print("\n Bad option")
===============================================================
Error:
Traceback (most recent call last):
File "C:/Users/Kate/Desktop/College DIT/projecttest1/Project_3.py", line 97, in <module>
best_6_month()
TypeError: best_6_month() missing 1 required positional argument: 'averageList'
Process finished with exit code 1
Traceback (most recent call last):
File "C:/Users/Kate/Desktop/College DIT/projecttest1/Project_3.py", line 94, in <module>
monthlyAverage()
File "C:/Users/Kate/Desktop/College DIT/projecttest1/Project_3.py", line 48, in monthlyAverage
list_average = [date_year_str , float_average]`enter code here`
UnboundLocalError: local variable 'date_year_str' referenced before assignment
Process finished with exit code 1

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)

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.

Categories