Python user input (lists) - python

Hi again i was coding my text based game and came across another problem. My code:
print("\nPath 1 - bookkeeper", "\n Path 2 - mississippi", "\n Path 3 - sleeplessness", "\n Path 4 - keenness", "\n Path 5 - suddenness")
path_way = input("Scan the word you want by "
"\ntyping here to figure out the number associated "
"\nwith each letter to add them up : ")
foreign_lang = []
occurences = []
for character in path_way:
if character not in foreign_lang:
foreign_lang.append(character)
occurences.append(1)
else:
foreign_index = foreign_lang.index(character)
occurences[foreign_index] = occurences[foreign_index] + 1
for index in range(len(foreign_lang)):
print(foreign_lang[index], "-->", occurences[index])
print("Now that you added up you numbers use that number and")
while True:
try:
act_3 = int(input("Enter the number of henchmen you want to fight : "))
if act_3==8:
print("\n You easily fight the 8 henchmen and defeat them to proceed with the path!")
break
else:
print("Sorry you have been killed as the henchmen overwhelmed you as there were too many of them")
except:
print("Sorry you have been kicked from the agency for quitting on the mission")
So I want to lead the user back to the list question instead of the while loop question if they enter the wrong answer in the while loop question. Does anyone know how I can do it?
https://trinket.io/python3/6f8defd82c

If I am comprehending your question correctly, then you can simply create a function and call it in your while loop.
def func():
print("\nPath 1 - bookkeeper", "\n Path 2 - mississippi",
"\n Path 3 - sleeplessness", "\n Path 4 - keenness",
"\n Path 5 - suddenness")
path_way = input("Scan the word you want by "
"\ntyping here to figure out the number associated "
"\nwith each letter to add them up : ")
foreign_lang = []
occurences = []
for character in path_way:
if character not in foreign_lang:
foreign_lang.append(character)
occurences.append(1)
else:
foreign_index = foreign_lang.index(character)
occurences[foreign_index] = occurences[foreign_index] + 1
for index in range(len(foreign_lang)):
print(foreign_lang[index], "-->", occurences[index])
print("Now that you added up you numbers use that number and")
while True:
func()
try:
act_3 = int(input("Enter the number of henchmen you want to fight : "))
if act_3 == 8:
print("\n You easily fight the 8 henchmen and defeat them to proceed with the path!")
break
else:
print("Sorry you have been killed as the henchmen overwhelmed you as there were too many of them")
except:
print( "Sorry you have been kicked from the agency for quitting on the mission")
This will show your list of paths/questions until user enters correct option.

Related

Why colorama make printing slower in python (Thonny)?

It's my RPG assignment for our school. I made an RPG program about an encounter with a Pirate and conversing with him with a guessing game. When I didn't use Colorama, the program runs normal but when using it, it slows down the program when running. I submitted the got 18 or 20 which is not bad, and I suspected it's how my program runs that's why I didn't get the perfect score.
I'm wondering if you guys can help me how to run the program faster when using Colorama? I just really wanted to learn how to solve this kind of issue.
import random
import time
import colorama
from colorama import Fore, Back, Style
talk_again = 'y'
while talk_again == 'y':
print("\nThere is a pirate coming down the road...")
time.sleep(2)
try:
user_option = int(input("\nWhat would you like to do? \n [1] To greet! \n [2] To play a game of chance \n [3] To walk on \n>>> "))
greetings= ["Hello stranger", "Hi there stranger!","Ahoy stranger!","Hey","*He stops, staring at you & didn't say anything*"]
inventory = ["Sword", "Shield","Dagger","Choker","Healing potion", "Red gem", "Red diamond","Sword", "Armour"]
leaving = ["Argghhh!!!", "Arrgh!Shut up!","Dammit! Arrgghh!!!"]
# lowercase items in inventory list, so we can compare wager input text
lowercase_inventory = [x.lower() for x in inventory]
def speak(text): #This is pirate conversation function colored in red
colorama.init(autoreset=True) # Automatically back to default color again
print(Fore.RED + '\t\t\t\t' + text)
def guess_my_number(): # the guessing number game
colorama.init(autoreset=True)
speak("Great! Let's play game of chance.")
time.sleep(1.5)
speak("I have a magic pen we can play for. What can you wager?")
time.sleep(1.5)
print("This is your inventory:" , lowercase_inventory)
wager = input(">>> ").lower()
# if wager item available in lowercased inventory
if wager.lower() in lowercase_inventory:
speak("That is acceptable!, Let's play the game of chance!")
time.sleep(1.5)
speak("I've thought of number between 1 to 100, you have 10 trys to guess it")
time.sleep(1.5)
speak("If you guess correctly, magic pen will be added to your inventor")
time.sleep(1.5)
speak("Otherwise you will lose " + wager + " from your inventory")
time.sleep(1.5)
speak("Make your guess:")
random_number = random.randint(1,100)
count = 10
main_game = True
# while loop will keep runing either guessed number matches random number or count number reaches 1
while main_game and count > 0:
try:
guess = int(input(">>> "))
except ValueError:
speak("Arrghh! I said guess numbers from 1 to 100 only!! Do you wanna play or not?")
else:
if count == 0:
speak("HA HA HA!! You lose!")
# count decreses by one every time.
lowercase_inventory.remove(wager)
print("Your current inventory:", lowercase_inventory)
break
if guess == random_number:
speak("Darn it!.. You won in " + str(11 - count)+ " guesses") #str(11 - count) means subtract the guesses from 11
lowercase_inventory.append('Magic pen')
print("The magic pen has been added in your inventory.\nYour inventory now: ", lowercase_inventory)
break
elif guess > random_number:
speak("Lower the number kid! Guess again!")
count-=1 # count decreses by one every time.
speak(str(count)+" "+ "chances left!!")
elif guess < random_number:
speak("Make it higher!Guess again!")
count-=1 # count decreses by one every time.
speak(str(count)+" "+ "chances left!!")
else:
speak("You don't have this item in your inventory, We can't play!")
except ValueError:
print("\nType 1, 2 and 3 only!")
else:
while True:
if user_option == 1:
print("\nType to greet the pirate:")
input(">>> ")
speak(random.choice(greetings))
elif user_option == 2:
guess_my_number()
elif user_option == 3:
leave_input = input("\nWhat would you like to say on leaving?:\n>>> ")
if leave_input == 'nothing':
speak("*He glances at you, then looks away after he walk passeed you, minding his own business*")
else:
speak(random.choice(leaving))
talk_again = input("\nPlay again?(y/n) " )
if talk_again == 'n':
print("\n Goodbye!")
break
user_option = int(input("\nWhat would you like to do? \n[1] to greet! \n[2] to play a game of chance \n[3] to walk on \n>>> "))

Lottery program that lets a user choose how many times they wish to play at once

I'm trying to make a lottery program that can output results after a user inputs their numbers. But I want the option to allow the user to also be able to pick "how many weeks they play for", that being, how many times the program outputs results that are randomized. Basically use the numbers they inputted to play multiple games of lottery with the same numbers x amount of times they wish. I want to know how to make my function repeat based on how many times they wish to play.
Here's my incomplete code.
import random
NUMBER_OF_PICKS = 3
MINIMUM_SELECTION = 1
MAXIMUM_SELECTION = 36
MONEY_WON = 10000
OFFSETT = 4
USER = input("Please enter your name:")
print("Hi " + USER + " good luck ")
WEEKS_PLAYED = input("How many weeks do you want to play: ")
def verify(playerNumbers, winningNumbers):
if playerNumbers == winningNumbers:
print("Congratulations! You Win ${}!".format(MONEY_WON))
print("Your numbers: ", playerNumbers, )
print("The winning lottery numbers were: ", winningNumbers)
else:
print("Sorry, you lose...")
print("Your numbers: ", playerNumbers)
print("The winning lottery numbers were: ", winningNumbers)
# 'get_user_nums', gets user numbers and puts into a sorted list for x in WEEKS_PLAYED:
def get_user_nums():
user_nums = []
while len(user_nums) < NUMBER_OF_PICKS:
nums = input("Pick a number {} through {}: ".format(MINIMUM_SELECTION, MAXIMUM_SELECTION))
try:
nums = int(nums)
except:
print("Sorry your input must be an integer!")
continue
if MINIMUM_SELECTION <= nums <= MAXIMUM_SELECTION:
if nums not in user_nums:
user_nums.append(nums)
else:
print("Sorry, you have already inputted that number")
else:
print("Sorry, Your number was not in range")
return sorted(user_nums)
# 'get_winning_nums', creates a sorted list with random nums ranging from 0-9 with a range of 3 values
def get_winning_nums():
return sorted(random.sample(range(MINIMUM_SELECTION, MAXIMUM_SELECTION), NUMBER_OF_PICKS))
# 'menu', creates the main menu to choose game or exit program
def play_pick_n():
user_nums = get_user_nums()
winning_nums = get_winning_nums()
verify(user_nums, winning_nums)
# 'main', calls the other functions
def main():
# lottery_menu()
while True:
choice = input("\nPlay?: Yes or No: ")
if choice == 'Yes':
string = "\n[Play Pick {}]".format(NUMBER_OF_PICKS) + "selected!"
dotted = '\n' + len(string) * "-"
print(dotted, string, dotted)
play_pick_n()
break
elif choice == 'No':
print("Thanks for playing!\n")
break
print("Sorry, that is not a valid input. \nPlease enter either Yes or No")
if __name__ == '__main__':
main()
Thanks for any help.
if you ant to use the same numbers for all weeks, use:
user_nums = get_user_nums()
for week in range(0, WEEKS_PLAYED):
winning_nums = get_winning_nums()
verify(user_nums, winning_nums)
You might want to move the question for the number of weeks inside your play_pick_n function, so the player can decide per bunch of numbers who long they should run.

Trying to add an external Score File to a Python Guessing Game

I'm creating a Python guessing game for school.
The game its self works fine, but I need to add an external score file (.txt)
I've tried a lot of different ways to implement this but where I'm having trouble is;
If the userName is existing in the file, how do I update that userName's score line.
The last method (in the code) was just a test to have a new userName added to the file if it was not found. This seemed to have over written the file, without adding the new userName.
# Import random library
import random
import os
# Welcome User to the game
print("Welcome to the game")
# Collect user details
userName = input("Please enter your Name: ")
# Roll the die for the number of guesses
print("Rolling the Dice!")
diceRoll = random.randint(1,6)
print("You have %d Guesses: " %diceRoll)
# Random picks the number to guess
number = random.randint(1,99)
guesses = 0
win = 0
lose = 0
# Loop checks the users input against the randint and supplies a hint, or breaks if correct
while guesses < diceRoll:
guess = int(input("Enter a number from 0 to 99: "))
guesses += 1
print("This is guess %d " %guesses)
if guess > 100:
print("Number out of range. Lose a turn")
if guess < number:
print("You guessed to low")
elif guess > number:
print("you guessed to high")
elif guess == number:
guesses = str(guesses)
print("You Win! you guessed the right number in",guesses + " turns")
win = +1
break
# If the user cannot guess the number in time, they receive a message
if guess !=number:
number = str(number)
print("You Lose. The number was: ",number)
lose = +1
with open('scoreList.txt', 'r') as scoreRead:
with open('scoreList.txt', 'w') as scoreWrite:
data = scoreRead.readlines()
for line in data:
if userName not in line:
scoreWrite.write(userName + "\n")
scoreRead.close()
scoreWrite.close()
It doesn't matter so much what the formatting of the score file looks like, as long as I can edit existing scores when they enter their name at the start of the game. Add a new user if it doesn't exist. Then print the scores at the end of each game.
I'm at a complete loss.
You have multiple mistakes in your final block. You open scoreList.txt but do the write operations outside of the with .. as block. Outside this block, the file is closed. Also because you are using with .. as, you don't have to close the files manually in the end.
And then, you iterate over all lines and would write the name for each line, that does not contain it, so potentially many times. And you open the file with 'w', telling it to overwrite. If you want to append, use 'a'.
Try it like this:
with open('scoreList.txt', 'r') as scoreRead:
data = scoreRead.readlines()
with open('scoreList.txt', 'a') as scoreWrite:
if userName + "\n" not in data:
scoreWrite.write(userName + "\n")
Also note, that you are currently writing each name into the score list and not only those, that won the game.
I believe you can accomplish this using the json module, as it will allow the use of data from a dictionary in the JSON file format.
A dictionary would be the superior method to storing users and associated scores, because it is easier to access these values in python, if using an associated text file.
I have updated your code with a working solution:
#! usr/bin/python
# Import random library
import random
import os
import json
# Welcome User to the game
print("Welcome to the game")
# Collect user details
userName = input("Please enter your Name: ")
#Added section
current_player = {"name": userName,
"wins": 0,
"losses": 0,
}
try:
with open('scores.json', 'r') as f:
data = json.load(f)
for i in data['players']:
if i["name"] == current_player["name"]:
current_player["wins"] = i["wins"]
current_player["losses"] = i["losses"]
except:
pass
print(current_player)
#end added section
"""begin game"""
# Roll the die for the number of guesses
print("Rolling the Dice!")
diceRoll = random.randint(1,6)
print("You have %d Guesses: " %diceRoll)
# Random picks the number to guess
number = random.randint(1,99)
guesses = 0
win = 0
lose = 0
# Loop checks the users input against the randint and supplies a hint, or breaks if correct
while guesses < diceRoll:
guess = int(input("Enter a number from 0 to 99: "))
guesses += 1
print("This is guess %d " %guesses)
if guess > 100:
print("Number out of range. Lose a turn")
if guess < number:
print("You guessed to low")
elif guess > number:
print("you guessed to high")
elif guess == number:
guesses = str(guesses)
print("You Win! you guessed the right number in", guesses + " turns")
win = +1
break
# If the user cannot guess the number in time, they receive a message
if guess !=number:
number = str(number)
print("You Lose. The number was: ", number)
lose = +1
"""end game"""
#added section
current_player["wins"] += win
current_player["losses"] += lose
try:
for i in data['players']:
if current_player["name"] == i["name"]:
i["wins"] = current_player["wins"]
i["losses"] = current_player["losses"]
if current_player not in data['players']:
data['players'].append(current_player)
print("Current Scores:\n")
for i in data['players']:
print(i["name"], ": wins", i["wins"], " losses: ", i["losses"])
with open('scores.json', 'w') as f:
f.write(json.dumps(data))
except:
start_dict = {"players":[current_player]}
with open('scores.json', 'w') as f:
f.write(json.dumps(start_dict))
print("Current Scores:\n")
for i in start_dict['players']:
print(i["name"], ": wins", i["wins"], " losses: ", i["losses"])
#end added section
This will check if the current player exists in the JSON file, then add their scores to the current player dictionary.
At the end of the game, it will check to see if:
The file scores.json exists, and will create it if it doesn't.
The current player exists in the scores.JSON file, and will update their score if they do. If they don't it will add a new user to the JSON file.
Then will print the score list accordingly.
Careful though, if a username is misspelt in any way, a new user will be created.
You can also manually update the scores in the .json file, if desired.

Self teaching python. Having trouble with score incrementing after each round

TL:DR Trying to set up a scoring system, it doesn't seem to go up when you get than answer right
As the title says I'm teaching myself python, thus this is only the second code I have written (hints in why I'm learning python). I'm more than happy to take criticism on everything from syntax to how to better comment. With that being said, let's get to my issue.
This is a small guessing game. The book I'm reading taught the "for guessTaken" and subsequent code. My problem is in one small aspect of my code. The scoring system won't increment.
I set up the code in the for loop called games then try to have it display at that start of each round and go up with each correct guess. However, it will display 0 for the first few rounds then it will show 2 ( or whatever your current score is I think...). I think the problem is I'm calling the score +1 int in an if statement but I've moved the code around and can't figure it out.
I am aware that it's not beautiful! There are also a few bugs (number of games played isn't what you enter.)Right now I'm only working on the scoring system.
#this is a guess the number game.
import random
#Get's user's name
print("Hello. Welcome to Print's guessing game. Please enter your name: ")
userName = input()
#askes if they are ready
print("Are you ready to play " + userName + "?")
ready = input().lower()
if ready == 'yes' :
print("Let's get started")
else:
while ready != 'yes':
print("Let me know when you are ready")
ready = input().lower()
#Game start
#number of games
games = int(input("How many games would you like to play?"))
if games >= 1:
print("Let's get started")
for games in range (int(games), 1, -1):
while games != 1:
print("I am thinking of a number between 1 and 20 ")
secretNumber = random.randint(1, 20)
score = 0
print("Current score: " + str(score))
print("Debug: " + str(secretNumber))
for guessTaken in range (7, 1, -1):
print("you have " + str(guessTaken - 1 ) + " guesses left")
guess = int(input())
if guess < secretNumber:
print("Your guess is to low. Please guess again")
elif guess > secretNumber:
print("Your guess is too high. Maybe something a little lower?")
else:
break # This conditon is for the right guess.
if guess == secretNumber:
print("good Job " + userName + "! you guessed the number right!")
score = int(score + 1)
print("your score is " + str(score))
games = int(games - 1)
else:
print("Nope, the number I was thinking of was " + str(secretNumber))
print("you have " + str(games) + " games left")
elif games == 0:
while games == 0:
print("Would you like to exit? Yes or No ")
exit = input().lower()
if exit == 'yes':
quit()
else:
games = int(input("How many games would you like to play?"))
else:
print("wtf")
Your score variable is being initialized to zero every time your code goes through the while loop. If you want it to track the total score for all of the games, initialize it right after your print("Let's get started"). This will reset their score whenever they tell you how many games they want to play.
If you don't want their score to reset until they quit your program, you will have to initialize it at the beginning of your program. Up by your import random would work well.

How to save the users name and last 3 scores to a text file?

I need to write the last three scores of students and their names into a text file for the teacher's program to read and sort later.
I still don't know how to save the last 3 scores
I have tried this so far:
#Task 2
import random
name_score = []
myclass1= open("class1.txt","a")#Opens the text files
myclass2= open("class2.txt","a")#Opens the text files
myclass3= open ("class3.txt","a")#Opens the text files
def main():
name=input("Please enter your name:")#asks the user for their name and then stores it in the variable name
if name==(""):#checks if the name entered is blank
print ("please enter a valid name")#prints an error mesage if the user did not enter their name
main()#branches back to the main fuction (the beggining of the program), so the user will be asked to enter their name again
class_name(name)#branches to the class name function where the rest of the program will run
def class_name(yourName):
try:#This function will try to run the following but will ignore any errors
class_no=int(input("Please enter your class - 1,2 or 3:"))#Asks the user for an input
if class_no not in range(1, 3):
print("Please enter the correct class - either 1,2 or 3!")
class_name(yourName)
except:
print("Please enter the correct class - either 1,2 or 3!")#asks the user to enter the right class
class_name(yourName)#Branches back to the class choice
score=0#sets the score to zero
#add in class no. checking
for count in range (1,11):#Starts the loop
numbers=[random.randint (1,11),
random.randint (1,11)]#generates the random numbers for the program
operator=random.choice(["x","-","+"])#generates the random operator
if operator=="x":#checks if the generated is an "x"
solution =numbers[0]*numbers[1]#the program works out the answer
question="{0} * {1}=".format(numbers[0], numbers [1])#outputs the question to the user
elif operator=="+":#checks if the generated operator is an "+"
solution=numbers[0]+numbers[1]#the program works out the answer
question="{0} + {1}=".format(numbers[0], numbers [1])#outputs the question to the user
elif operator=="-":
solution=numbers[0]-numbers[1]#the program works out the answer
question="{0} - {1}=".format(numbers[0], numbers [1])#outputs the question to the user
try:
answer = int(input(question))
if answer == solution:#checks if the users answer equals the correct answer
score += 1 #if the answer is correct the program adds one to the score
print("Correct! Your score is, {0}".format(score))#the program outputs correct to the user and then outputs the users score
else:
print("Your answer is not correct")# fail safe - if try / else statment fails program will display error message
except:
print("Your answer is not correct")#if anything else is inputted output the following
if score >=5:
print("Congratulations {0} you have finished your ten questions your total score is {1} which is over half.".format(yourName,score))#when the user has finished there ten quetions the program outputs their final score
else:
print("Better luck next time {0}, your score is {1} which is lower than half".format(yourName,score))
name_score.append(yourName)
name_score.append(score)
if class_no ==1:
myclass1.write("{0}\n".format(name_score))
if class_no ==2:
myclass2.write("{0}\n".format(name_score))
if class_no ==3:
myclass3.write("{0}\n".format(name_score))
myclass1.close()
myclass2.close()
myclass3.close()
Your program seems to be working just fine now.
I've re-factored your code to follow the PEP8 guidelines, you should really try to make it more clear to read.
Removed the try/except blocks, not needed here. Don't use try/except without a exception(ValueError, KeyError...). Also, use with open(...) as ... instead of open/close, it will close the file for you.
# Task 2
import random
def main():
your_name = ""
while your_name == "":
your_name = input("Please enter your name:") # asks the user for their name and then stores it in the variable name
class_no = ""
while class_no not in ["1", "2", "3"]:
class_no = input("Please enter your class - 1, 2 or 3:") # Asks the user for an input
score = 0
for _ in range(10):
number1 = random.randint(1, 11)
number2 = random.randint(1, 11)
operator = random.choice("*-+")
question = ("{0} {1} {2}".format(number1,operator,number2))
solution = eval(question)
answer = input(question+" = ")
if answer == str(solution):
score += 1
print("Correct! Your score is, ", score)
else:
print("Your answer is not correct")
print("Congratulations {0}, you have finished your ten questions!".format(your_name))
if score >= 5:
print("Your total score is {0} which is over half.".format(score))
else:
print("Better luck next time {0}, your score is {1} which is lower than half".format(your_name, score))
with open("class%s.txt" % class_no, "a") as my_class:
my_class.write("{0}\n".format([your_name, score]))
main()

Categories