I've been set the task to design a small game which includes a text file which is 'encrypted' and a 'decrypted' version of the text file. The user is shown the 'encrypted' list (which has been read in and appended to an array) with some clues e.g. A = # (I'm using a dictionary to store possible values of the symbols.)
My problem is: I have created the whole game but i have added an option to my menu to allow the End-User to compare the words they have substituted in with the 'decrypted' list (also read into an array) to see if they have completed the game.
I have tried the following code and have tested the game through to me being 100% sure the words were identical and the Python Shell printed "Sorry! Try Again!"
Here's The Code:
def compareFiles():
for eachLine in range(len(rsef)):
if rsef[eachLine] == rssf[eachLine]:
print("Congratulations! Puzzle Solved!")
else:
print("Sorry! Try Again!")
secMenu()
For Context:
secMenu() is my menu
rsef is my 'encrypted' array
rssf is the 'decrypted' array which i want to compare to.
EDIT:
Which Option Would You Like To Choose?
Option Number: 1
--------------------------------
1. View The Encrypted Words With Some Clues.
A+/084&"
A3MANA+
8N203:
,1$&
!-MN
.A7&33&
AMA71N
&-&641'2
A))85
9&330M
This is the Sorted List:
Which Option Would You Like To Choose?
Option Number: 5
ACQUIRED
ALMANAC
INSULT
JOKE
HYMN
GAZELLE
AMAZON
EYEBROWS
AFFIX
VELLUM
Here's to check if all items in both lists are identical:
def compareFiles():
if rsef == rssf:
print("Congratulations! Puzzle Solved!")
else:
print("Sorry! Try Again!")
secMenu()
If you insist on looping, the one below :)
def compareFiles():
for eachLine in range(len(rsef)):
if rsef[eachLine] != rssf[eachLine]:
print("Sorry! Try Again!")
secMenu()
return 0 #exit the function, use this if you need it.
print("Congratulations! Puzzle Solved!")
Related
I'm really new in Coding, with Python.
I was trying to make a Vocabulary exercise program for a Language that i am learning it right now. So the concept is, if the word "abhängen" is shown at the Console, i have to write "von" which is the right word to come after that word, which is "abhängen". And the program will show if its right or wrong, and loops the input to get the right answer.
But since there are tons of vocabulary, i have to make same loop over and over again just by using while True and changing a,b,c for the variables and the word between "". Is there a way to make it shorter maybe by using list or something?
And if its possible, can i somehow make the order of the questions randomly? Since this code always shows the first question as abhängen and second as abrechnen.
Sorry if this was some kind of dumb question to ask, have nowhere to ask haha
have a nice day guys
while True:
a = input("abhängen ")
if a == "von":
print("You're right")
break
else:
print("Wrong")
while True:
c = input("abrechnen ")
if c == "mit":
print("You're right")
break
else:
print("Wrong")
It looks like a great example to learn usage of lists in Python.
You can use list of tuples and random module for this task. See random.shuffle documentation here
words_and_answers = [("abhängen ", "von"), ("abrechnen ", "mit")]
random.shuffle(words_and_answers)
for input_word, correct_answer in words_and_answers:
while True:
user_response = input(input_word)
if user_response == correct_answer:
print("You're right")
break
else:
print("Wrong")
I think a possible solution is to use a dictionary in which the keys are the words "abhängen", "abrechnen", ecc... And the values are the correct words that come after. So you can write a thing like this:
vocabulary = {
"abhängen" : "von",
"abrechnen" : "mit"
}
for i in vocabulary:
a = input(i + " ")
if a == vocabulary[i]:
print("You are right")
else:
print("Wrong")
Note that in this case the loop is not infinite! This method allows you to have more than one word correct for each key
For the randomly access to the keys, you can make a list with the keys and use the random.shuffle() method, like this:
import random
keys = list(vocabulary.keys())
random.shuffle(keys)
And then your loop will be:
for i in keys:
...
I am doing a simple project for my first python course and I am stuck in one part which I have no idea how to continue.
So in this part user should input a vehicle id that he/she wants to rent. After putting the vehicle ID, my code starts to search for that vehicle ID in the Vehicle.txt text file. If the code finds the VehicleID variable and also finds that it is "A" (which means available), it starts printing details for that specific car.
My Vehicle.txt text file looks like this;
XJY-604,Hyundai Getz,O,0,45.00,A
AJB-123,BMW mini,P,200,65.00,A
WYN-482,Ford Fiesta,O,0,40,A
BKV-943,Ford Ikon,P,150,60,A
JMB-535,Ford Flex,O,0,50,A
FKI-232,Fiat Egea,O,0,30,A
KLE-154,Toyota Corolla,O,0,40,A
ITO-444,Renault Clio,O,0,55,A
MAA-321,Honda Civic,O,0,70,A
IRK-948,Hyundai i20,O,0,30,A
TRY-475,Peugeot 2008,O,0,50,A
IBM-984,Skoda Superb,O,0,60,A
KRI-365,Opel Corsa,O,0,50,A
PMA-760,Citreon C3,O,0,55,A
NGT-407,KIA Sportage,O,0,60,A
So until this far, everything is fine; if the code finds the Vehicle ID (and the condition "A") then the code starts to print details as I want (if the condition is different or vehicle ID is not found it also prints appropriate error massages which are also perfectly working as I want).
My problem starts after this part:
After printing the details from the car, my code should change that specific car's condition from "A" (available) to "R" (rented) in the Vehicle.txt text file.
For example, let's say the user entered the Vehicle ID TRY-475 --> After this input, my excepted change in the Vehicle.txt text file is;
excepted change
But the actual change in the text file is;
actual change
My code looks like this;
from datetime import datetime
now = datetime.now()
dateandtime = now.strftime("%d/%m/%Y %H:%M:%S")
def rentVehicle():
VehicleID = input("Please enter the vehicle ID you want to rent: ")
with open("Vehicle.txt","r+") as f1:
for line in f1:
l = line.split(",")
if l[0] == VehicleID and l[5] == "A\n" or l[5] == "A":
renterID = input("Please enter your ID: ")
startingodometer = input("Please enter the current odometer reading: ")
print("\nCar",l[0],"is rented to", renterID,"\n")
print("\t\t******************** Vehicle Details ********************\n")
print("Vehicle ID =",l[0],"\t\tDescription =",l[1],"\t\tDaily Rate =",l[4],"\tStatus =",l[5],"\n")
print("Renter ID =",renterID,"\tDate/time of rent =",dateandtime,"\tRent Starting Odometer =",startingodometer)
f1.write(l[5].replace(l[5],"R\n"))
print("\nRenting vehicle is successful!")
break
elif l[0] == VehicleID and l[5] == "R\n" or l[5] == "R":
print("\nThe vehicle you entered is rented. Please display available cars from the main menu.")
break
else:
print("\nThe vehicle ID you entered does not exist. Please enter a valid vehicle ID.")
break
rentVehicle()
I think the problem is in line 17 ( f1.write(l[5].replace(l[5],"R\n"))). I searched for the other options but they also didn't give my excepted output in the Vehicle.txt text file. Additionally, I am not allowed to change my file name or add these lines to another file (manually or in the code) as it is restricted in my project work. I should only update the current Vehicle.txt via code. I would be very glad if someone solve this. For a beginner, these problems are really challenging sometimes. Thanks in advance.
the problem in your code is here:
with open("Vehicle.txt","r+") as f1:
for line in f1:
l = line.split(",")
if l[0] == VehicleID and l[5] == "A\n" or l[5] == "A":
renterID = input("Please enter your ID: ")
startingodometer = input("Please enter the current odometer reading: ")
~~~~~~~~~~~~~~~~~~~
f1.write(l[5].replace(l[5],"R\n"))
~~~~~~~~~~~~~~~~~~~
break
elif l[0] == VehicleID and l[5] == "R\n" or l[5] == "R":
print("\nThe vehicle you entered is rented. Please display available cars from the main menu.")
break
else:
print("nothing found")
break
I supposed that you are not very familiar with how does the file reading work on the background ... To put it simply, there is a buffer of a specific length (for example 1028B) whihc means it is going to read 1028B of text. The reason why it is this way is that you are unable to efficiently know, how long the line will be, and also reading from a file is slow, therefore reading as much as possible in the shortest time possible is what everyone is aiming for.
Now to your code, what happend there is that your whole file got loaded into the mentioned buffer and a file pointer ended up at the end of the file.
What you should do and is recommended to do is not to rewrite the file you are currently reading (you can check out some articles about how files actually work, sorry I am not 100% sure right now whether it even lets you to write to a file that you are reading ...).
Therefore, what you need to do, is this (this is pseudocode, in order for you to do it yourself, to gain more experience :)):
with open("Vehicle.txt","r+") as read_file:
with open("Vehicle2.txt","w+") as write_file:
for line in read_file:
if (your checks):
... (setting up)
write_file.write(f"{l[0]},{l[1]},{l[2]},{l[3]},{l[4]},{edited_thing}")
else:
write_file.write(line)
// after this, you can eighter rename these files or delete the original one and then rename the other one ther:
// vehicle.txt -> temp.txt ; Vehicle2.txt => Vehicle.txt ; delete temp.txt ?
I hope this answer helps and I wish you a nice programming journey ;)
EDIT:
I just noticed that you have multiple checks there. if you do not really need to break it, I recommend you using continue which will immediatelly start the next iteration.
I'm currently working on a guessing game assignment. The assignment uses a dictionary to store the course name which is the key and the course number which is the value. The user guesses the course number of the course name given. If the value matches the key then it should print "correct!" and vice versa.
I have gotten the program to display the keys one at a time with an input statement separating them. I've gotten the correct/incorrect counters working. I'm not able to get an if statement working which is supposed to check if the value matches the key. It prints incorrect every time regardless of if the answer is correct. I realize there's probably something wrong with the condition of the if statement because i'm not really sure how to extract one value at a time.
Here's what I have so far:
# Mainline
def main():
programming_courses={"Computer Concepts":"IT 1025",\
"Programming Logic":"IT 1050",\
"Java Programming":"IT 2670",\
"C++ Programming":"IT 2650",\
"Python Programming":"IT 2800"}
print ("Learn your programming courses!\n")
correct=0
incorrect=0
v=0
# Game Loop
for key in programming_courses.keys():
print(key)
answer = input("Enter the Course Number: ")
if answer != programming_courses.values():
print("Incorrect")
incorrect += 1
else:
print("Correct!")
correct += 1
# Display correct and incorrect answers
print ("You missed ",incorrect," courses.")
print ("You got ",correct," courses.\n")
# Entry Point
response=""
while (response!="n"):
main()
response=input("\n\nPlay again?(y/n)\n# ")
Your problem is here:
if answer != programming_courses.values():
programming_courses.values() is a list of all the values in the dictionary. If you don't understand what's happening in your program, it's really helpful to just print stuff out and see if it looks like what you expect.
What you want is the specific value for the key you're on right now, which you need to look up from the dictionary like so:
if answer != programming_courses[key]:
Also, iterating over a dict gives you the keys by default, so you can just say:
for key in programming_courses:
You don't need to use .keys() there.
Your problem is when you are checking your dict. Currently your code is comparing the answer to a list of all the values in the dict:
out[]:
dict_values(['IT 1025', 'IT 1050', 'IT 2670', 'IT 2650', 'IT 2800'])
If you change to the following it works, by taking the specific value from the dict with the given key:
for key in programming_courses.keys():
print(key)
answer = input("Enter the Course Number: ")
if answer != programming_courses[key]:
print("Incorrect")
incorrect += 1
else:
print("Correct!")
correct += 1
you could try this
if answer != programming_courses[key]:
I am currently writing a code for my GCSE coursework and I am kind of stuck with my for loop which also contains an if-else statement.
I have done a code similar to this earlier in the program and it works perfectly fine but for some reason this part doesn't and I was wondering if someone could help me.
What I am trying to do is make a quiz type program and the part that I need help with is choosing the subject that the user wants to do.
The user has to type in their preferred subject but if they type the subject in wrong, or type in something invalid, then the program should allow the user to type it in again.
So far, if you type in a subject correctly the first time, the program will proceed to the next stage.
However, if you type it incorrectly the first time, it will ask the user to try again. But if you type it in correctly the second time, it will again ask the user to try again. Instead of having the program make the user type the subject again, even though it should've been valid the when they typed it in correctly, I want the program to proceed to the next stage.
Available subjects:
subjects = []
algebra = ("algebra")
computing = ("computing")
subjects.append(algebra)
subjects.append(computing)
Part that I need help with:
with open("student_file.csv", "a+") as studentfile:
studentfileReader = csv.reader(studentfile, delimiter = ',')
studentfileWriter = csv.writer(studentfile, delimiter = ',')
print("Available subjects:\n-Algebra\n-Computing\n")
ChosenSubject = input("What subject would you like to do? ")
ChosenSubject.lower()
for i in range(2):
if ChosenSubject in subjects:
print("\n")
break
else:
print("\nPlease try again.")
ChosenSubject == input("What subject would you like to do?")
ChosenSubject.lower()
if ChosenSubject in subjects:
print("working")
else:
print("You keep typing in something incorrect.\nPlease restart the program.")
In the else block, perhaps you'd want to replace the '==' with '='.
Also do you want to give the user just two tries or keep asking them until they answer correctly? (The latter is what I inferred from your question, for that I'd recommend using continue)
The for loop just iterates over a collection of objects. Consider a list my_list = ['a', 'b', 'c']. On each iteration over my_list using for loop, it fetches one of the elements in order without repetition. range(2) is equivalent to [0, 1].
Try this:
print("Available subjects:\n-Algebra\n-Computing\n")
for i in range(2):
# `i` is 0 on first iteration and 1 on second. We are not using `i` anywhere since all we want is to loop :)
chosen_subject = input("What subject would you like to do? ")
if chosen_subject.lower() in subjects:
print("\n")
break
if chosen_subject.lower() in subjects:
print("working")
else:
print("You keep typing in something incorrect.\nPlease restart the program.")
This is not an optimal solution, but since your learning I will try to keep it as close as your solution. Your problem is that calling ChosenSubject.lower() does not change the actual value in ChosenSubject.
Here is a working example:
print("Available subjects:\n-Algebra\n-Computing\n")
ChosenSubject = input("What subject would you like to do? ")
subjects = ["algebra", "computing"]
for i in range(2):
if ChosenSubject.lower() in subjects:
print("\n")
break
else:
print("\nPlease try again.")
ChosenSubject = input("What subject would you like to do?") #not '=='
if ChosenSubject.lower() in subjects:
print("working")
else:
print("You keep typing in something incorrect.\nPlease restart the program.")
This from the doc:
This method returns a copy of the string in which all case-based
characters have been lowercased.
I am currently a new student learning python. This is my first real experience doing much computer coding. For my project I must create a fill in the blank quiz with three different levels of difficulty. Once the user chooses a difficulty the game should print a different paragraph based on the difficulty. Each section of the game works fine but I am having trouble creating the "difficulty chooser." No matter the difficulty I choose, the game rolls through the easy, medium, and the hard level in order and then crashes.
Below I have included the introductory text and the difficulty chooser. I would love some help. I am sure there are really obvious things I don't see. Thank you!
def introduction():
print '''Welcome to Kevin's European Geography Quizzes.
Test your knowledge of European geography. \n'''
difficulty = raw_input('''Do you want to play an easy, medium, or hard game?
Please type the number 1 for easy, 2 for medium, or 3 for hard.\n''' )
game_chooser(difficulty)
def game_chooser(difficulty):
cursor = 0
difficulty_choice = [easy_game(), medium_game(), hard_game()]
#each element of the above list links to a procedure and starts one of the
#mini-games.
while cursor < len(difficulty_choice):
if difficulty != cursor:
cursor += 1
else:
difficulty_choice[cursor]
break
You can do with if else if you only want to print something but if you have separate code block for each level then define a function for each level and use this pattern :
You can define the function blocks and call them basis on user input something like:
# define the function blocks
def hard():
print ("Hard mode code goes here.\n")
def medium():
print ("medium mode code goes here\n")
def easy():
print ("easy mode code goes here\n")
def lazy():
print ("i don't want to play\n")
# Now map the function to user input
difficulty_choice = {0 : hard,
1 : medium,
4 : lazy,
9 : easy,
}
user_input=int(input("which mode do you want to choose : \n press 0 for hard \n press 1 for medium \n press 4 for lazy \n press 9 for easy "))
difficulty_choice[user_input]()
Then invocation of function block will be:
difficulty_choice[num]()
Add a conditional for the input.
if difficulty == 'easy':
print("here is an easy game")
elif difficulty == 'medium':
print('here is a medium game')
elif difficulty == 'hard':
print('here is hard')
else:
print('Please enter valid input (easy, medium, hard)')
Under each if statement put your game code.
The reason your code goes through all the difficulties is because of this line:
difficulty_choice = [easy_game(), medium_game(), hard_game()]
When Python sees something like easy_game(), it calls the easy_game function and replaces it with the result. You don't want to call the function yet though, so you can take off the parenthesis to store just the function instead:
difficulty_choice = [easy_game, medium_game, hard_game]
This will mean you have to call the function after you take it out of the array.
As for the crash, when you use raw_input() you get a string back. That means when you type in the 1 to decide for an easy game, you get the character 1, which is represented by the number 49. That's why your code goes through everything and crashes: Your 1 is really a 49. In fact, if you type 1 < '1' into the interpreter, you'll get True back.
To fix that, you can pass the result of raw_input() to the int() function, which will parse it and give you the proper integer (or throw an exception if it can't be parsed). The last line of introduction would then look like game_chooser(int(difficulty)).
You could also skip most of the code of game_chooser by just indexing into the array (that's what they're for, after all):
def game_chooser(difficulty):
# the lack of parens here means you get the function itself, not what it returns
difficulty_choice = [easy_game, medium_game, hard_game]
#each element of the above list links to a procedure and starts one of the
#mini-games.
# note the parens to actually call the retrieved function now
difficulty_choice[difficulty]()