Comparing file lines to strings in python, and inconsistencies - python-3.x

Important things this code is supposed to in order of execution:
1.Open and read the file "Goods"
2.Assign a random line from file "Goods" to the dictionary "goods"
3.Go through an if block that will assign a random value to the dictionary "cost" if goods[x] equals the string it's being compared to.
4.Print "goods", and "cost"
5.Repeat steps 2-4, 2 more times.
from random import randint
print("You search for things to buy in the market, and find:")
f = open('Goods', 'r') #Opens file "Goods"
lines = f.readlines() #Loads all lines from "Goods"
goods = {1:"", 2:"", 3:""}
cost = {1:"", 2:"", 3:""}
x = 0
while x < 3:
x += 1
goods[x] = lines[randint(0, 41)].strip()
#Checks to see if goods[x] is equal to the string on the right, if it is, it assigns cost[x] to a random integer
if goods[x] == "Lumber":
cost[x] = randint(2, 3)
elif goods[x] == "Rum":
cost[x] == randint(3, 4)
elif goods[x] == "Spices":
cost[x] = randint(4, 5)
elif goods[x] == "Fruit":
cost[x] == randint(2, 4)
elif goods[x] == "Opium":
cost[x] == randint(1, 5)
findings = '%s for %s gold.' %(goods[x], cost[x])
print(findings)
The problem with this code is that the dictionary:"cost" does not get a value assigned from the if block when goods[x] equals: Rum, Fruit, or Opium.
Could someone please tell me what's going on here?
The file "Goods"

Your problem is that you are using two equal signs. cost[x] == randint(3, 4) you need to use just one. Hope this helps!

Related

Problem with my small dictionary quiz. can someone explain this error please

d = {'Red': 1, 'Green': 2, 'Blue': 3}
for color_key, value in d.items():
userinput == (input(color_key))
if userinput == (d[color_key]):
print("correct")
else:
print("wrong")
Hi everyone, i am trying to simulate a quiz with this dictionary. I want to iterate through the dictionary and prompt the user for the questions (which is the key) (i.e what is the number for the colour: color_key). I then want the user to put the value for the key that corresponds to the right colour.
I am getting this error:
userinput == input(color_key)
NameError: name 'userinput' is not defined
Can anyone help me please.
Based on assumptions that you want to make kind of "memory" game with colors and integers, code proposal for your game would be something like this:
import random
d = {'Red': 1, 'Green': 2, 'Blue': 3}
while 1==1:
rand1 = random.choice(list(d))
user_input = input("Please guess the code of "+rand1+" color:\n")
try:
int(user_input)
if(int(user_input) == d[rand1]):
print("Color code is correct!")
else:
print("Color code is incorrect!")
except ValueError:
if(user_input.lower() == "quit"):
print("Program will terminate now")
else:
print("Invalid input provided.")
Take in consideration few things important for these kind of exercises:
Despite python is not strictly typizied language, you have to take
care of exceptions in the user input
"While 1==1" generates something
called "dead loop". Make sure you always have exit condition for this
one - In our case out here, that is keyword "quit" on the input.
In case of keyword "quit" on the input, it has to be validated for both
upper and lowercase
EDIT:
According to your newest update, I am providing you the example of simple 3-operations based game:
import random
def detect_string_operation(elem1, elem2, operator):
result = ""
if(operator == "+"):
result = str(elem1 + elem2)
elif(operator == "-"):
result = str(elem1 - elem2)
elif(operator == "*"):
result = str(elem1 * elem2)
elif(operator == "/"):
result = str(elem1/elem2)
return result
operators_list = ["+", "-", "*"]
while 1==1:
elem1 = random.randint(0, 10)
elem2 = random.randint(0, 10)
operator_index = random.randint(0, len(operators_list)-1)
result_operation = detect_string_operation(elem1, elem2, operators_list[operator_index])
user_input = input("Please calculate following: "+str(elem1)+str(operators_list[operator_index])+str(elem2)+"=")
try:
int(user_input)
if(user_input == result_operation):
print("Result is correct!")
else:
print("Result is incorrect!")
except ValueError:
if(user_input.lower() == "quit"):
print("Program will terminate now")
break
else:
print("Invalid input provided.")
Note that I didn't implement division for a reason: for division totally random choice of values is not an option, since we need an integer as a result of division. Algorithm for generating divisor and divider pair is quite simple to be implemented in iterative way, but it is out of scope of your initial question.

Python number guessing game not displaying feedback correctly. What's the problem?

So I tried to make a game where the computer chooses a random 4 digit number out of 10 given numbers. The computer then compares the guess of the user with the random chosen code, and will give feedback accordingly:
G = correct digit that is correctly placed
C = correct digit, but incorrectly placed
F = the digit isn't in the code chosen by the computer
However, the feedback doesn't always output correctly.
Fox example, when I guess 9090, the feedback I get is F C F, while the feedback should consist of 4 letters.... How can I fix this?
#chooses the random pincode that needs to be hacked
import random
pincode = [
'1231', '9997', '8829', '6765', '9114', '5673', '0103', '4370', '8301', '1022'
]
name = None
#Main code for the game
def main():
global code
global guess
#Chooses random pincode
code = random.choice(pincode)
#Sets guessestaken to 0
guessesTaken = 0
while guessesTaken < 10:
#Makes sure every turn, an extra guess is added
guessesTaken = guessesTaken + 1
#Asks for user input
print("This is turn " + str(guessesTaken) + ". Try a code!")
guess = input()
#Easteregg codes
e1 = "1955"
e2 = "1980"
#Checks if only numbers have been inputted
if guess.isdigit() == False:
print("You can only use numbers, remember?")
guessesTaken = guessesTaken - 1
continue
#Checks whether guess is 4 numbers long
if len(guess) != len(code):
print("The code is only 4 numbers long! Try again!")
guessesTaken = guessesTaken - 1
continue
#Checks the code
if guess == code:
#In case the user guesses the code in 1 turn
if (guessesTaken) == 1:
print("Well done, " + name + "! You've hacked the code in " +
str(guessesTaken) + " turn!")
#In cases the user guesses the code in more than 1 turn
else:
print("Well done, " + name + "! You've hacked the code in " +
str(guessesTaken) + " turns!")
return
#Sets empty list for the feedback on the user inputted code
feedback = []
nodouble = []
#Iterates from 0 to 4
for i in range(4):
#Compares the items in the list to eachother
if guess[i] == code[i]:
#A match means the letter G is added to feedback
feedback.append("G")
nodouble.append(guess[i])
#Checks if the guess number is contained in the code
elif guess[i] in code:
#Makes sure the position of the numbers isn't the same
if guess[i] != code[i]:
if guess[i] not in nodouble:
#The letter is added to feedback[] if there's a match
feedback.append("C")
nodouble.append(guess[i])
#If the statements above are false, this is executed
elif guess[i] not in code:
#No match at all means an F is added to feedback[]
feedback.append("F")
nodouble.append(guess[i])
#Easteregg
if guess != code and guess == e1 or guess == e2:
print("Yeah!")
guessesTaken = guessesTaken - 1
else:
print(*feedback, sep=' ')
main()
You can try the game here:
https://repl.it/#optimusrobertus/Hack-The-Pincode
EDIT 2:
Here, you can see an example of what I mean.
Here is what I came up with. Let me know if it works.
from random import randint
class PinCodeGame(object):
def __init__(self):
self._attempt = 10
self._code = ['1231', '9997', '8829', '6765', '9114', '5673', '0103', '4370', '8301',
'1022']
self._easterEggs = ['1955', '1980', '1807', '0609']
def introduction(self):
print("Hi there stranger! What do I call you? ")
player_name = input()
return player_name
def show_game_rules(self):
print("10 turns. 4 numbers. The goal? Hack the pincode.")
print(
"For every number in the pincode you've come up with, I'll tell you whether it is correct AND correctly placed (G), correct but placed incorrectly (C) or just plain wrong (F)."
)
def tutorial_needed(self):
# Asks for tutorial
print("Do you want a tutorial? (yes / no)")
tutorial = input().lower()
# While loop for giving the tutorial
while tutorial != "no" or tutorial != "yes":
# Gives tutorial
if tutorial == "yes":
return True
# Skips tutorial
elif tutorial == "no":
return False
# Checks if the correct input has been given
else:
print("Please answer with either yes or no.")
tutorial = input()
def generate_code(self):
return self._code[randint(0, len(self._code))]
def is_valid_guess(self, guess):
return len(guess) == 4 and guess.isdigit()
def play(self, name):
attempts = 0
code = self.generate_code()
digits = [code.count(str(i)) for i in range(10)]
while attempts < self._attempt:
attempts += 1
print("Attempt #", attempts)
guess = input()
hints = ['F'] * 4
count_digits = [i for i in digits]
if self.is_valid_guess(guess):
if guess == code or guess in self._easterEggs:
print("Well done, " + name + "! You've hacked the code in " +
str(attempts) + " turn!")
return True, code
else:
for i, digit in enumerate(guess):
index = int(digit)
if count_digits[index] > 0 and code[i] == digit:
count_digits[index] -= 1
hints[i] = 'G'
elif count_digits[index] > 0:
count_digits[index] -= 1
hints[i] = 'C'
print(*hints, sep=' ')
else:
print("Invalid input, guess should be 4 digits long.")
attempts -= 1
return False, code
def main():
# initialise game
game = PinCodeGame()
player_name = game.introduction()
print("Hi, " + player_name)
if game.tutorial_needed():
game.show_game_rules()
while True:
result, code = game.play(player_name)
if result:
print(
"Oof. You've beaten me.... Do you want to be play again (and be beaten this time)? (yes / no)")
else:
print("Hahahahaha! You've lost! The correct code was " + code +
". Do you want to try again, and win this time? (yes / no)")
play_again = input().lower()
if play_again == "no":
return
main()

Excluding 0's from calculations

Hi I have been asked to write a program that will keep asking the user for numbers. The average should be given to 2 decimal places and if a 0 is entered it shouldnt be included in the calculation of the average.
so far I have this:
data = input()
numbers = []
while True:
data = input()
if data == "":
break
numbers.append(float(data))
count = len(numbers)
if count > 0:
newsum = sum(numbers)
average = newsum / float(count)
print("The average is {}".format(average))
Dumb question but how do you ensure the 0's arent considered in the calculation?
Correction: you are not appending the first input to the list
Modification: added an if statement to check whether the input is '0'
data = input()
numbers = []
numbers.append(float(data))
while True:
data = input()
if data == "":
break
if data == '0':
continue
numbers.append(float(data))
count = len(numbers)
if count > 0:
newsum = sum(numbers)
average = newsum / float(count)
print("The average is {}".format(average))

Duplicate word in hangman game Python

I have a problem, when in Hangman game there is a word like happy, it only append 1 'p' in the list...run my code and please tell me what to do?
check my loops.
import random
import time
File=open("Dict.txt",'r')
Data = File.read()
Word = Data.split("\n")
A = random.randint(0,len(Word)-1)
Dict = Word[A]
print(Dict)
Dash = []
print("\n\n\t\t\t","_ "*len(Dict),"\n\n")
i = 0
while i < len(Dict):
letter = str(input("\n\nEnter an alphabet: "))
if letter == "" or letter not in 'abcdefghijklmnopqrstuvwxyz' or len(letter) != 1:
print("\n\n\t\tPlease Enter Some valid thing\n\n")
time.sleep(2)
i = i - 1
if letter in Dict:
Dash.append(letter)
else:
print("This is not in the word")
i = i - 1
for item in Dict:
if item in Dash:
print(item, end = " ")
else:
print("_", end = " ")
i = i + 1
The error is with the "break" on Line 25: once you have filled in one space with the letter "p", the loop breaks and will not fill in the second space with "p".
You need to have a flag variable to remember whether any space has been successfully filled in, like this:
success = False
for c in range(len(Dict)):
if x == Dict[c]:
Dash[c] = x
success = True
if not success:
Lives -= 1
P.S. There's something wrong with the indentation of the code you have posted.

Counting Grades to print

Hopefully this will be very simple all I need help with is getting a count of the letter grades and then printing them along with the list.
Here is my code:
def getScores():
f_obj = open("scores.txt", "r")
data = f_obj.readlines() #read file into a list of record strings
f_obj.close()
return data
def displayData(data):
print("Name Avg Grade")#print headings
for record in data:
name, ex1, ex2, ex3 = record.split()
exam1 = float(ex1)
exam2 = float(ex2)
exam3 = float(ex3)
avg = round(exam1 + exam2 + exam3) / 3
if avg >= 100:
letterGrade = "A"
elif avg >= 89:
letterGrade = "B"
elif avg >= 79:
letterGrade = "C"
elif avg >= 69:
letterGrade = "D"
elif avg >= 59:
letterGrade = "F"
Just above here is where im stuck I cannot figure out how to do a count with the certain letter grades.
print("%-10s %5s %5s" % (name, round(avg, 1), letterGrade))
print()
print(
def addStudent():
name = input("Enter student name: ")
ex1 = int("Enter Exam 1 grade: ")
ex2 = int("Enter Exam 2 grade: ")
ex3 = int("Enter Exam 3 grade: ")
return name + "\t" + ex1 + "\t" + ex2 + "\t" + ex3
def storeData(data):
f_obj = open("scores.txt", "w")
f_obj.writelines(data)
f_obj.close()
def main():
scoreData = getScores() # read data file into a list
while True:
print("""
Program Options
1.) Display Students.
2.) Add a new student:
3.) Exit Program """)
option = input("Enter option 1, 2, or 3: ")
if option == "1":
displayData(scoreData)
elif option == "2":
scoreData.append(addItem()) # add record string to our list
elif option == "3":
storeData(scoreData)
print("Good bye.")
break
else:
print("Not a valid entry. Please enter 1, 2, or 3.")
main() # start the program
Hint: you already know how to determine if a grade is an A, B, C, etc. So all you need to do is increment a counter at the same time.
For example, you'd add in something like this to count the number of A grades:
if avg >= 100:
letterGrade = "A"
numAs += 1
Then do the same thing for each other grade type. Since this appears to be homework, I'll let you figure out how to do all this. Most importantly, even though Python isn't strict about this, think about the correct place to declare the counter variables.
Once you've got that working, here's an "extra credit" assignment: see if you can do all that using just a single array.

Resources