Reduce line count or make this code more efficient [closed] - python

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
In my evergrowing quest for knowledge I would like to know if there is any way I can reduce the line count or make the code more efficient. Its for a game I have made and I have challenged myself to make it as short as I can, (in the original it was about twice as long as this :D)
import random
gameLives,hints,wonGame,levels,awardedLives,levelRange=3,6,0,[1,2,3,4,5,6,7,8,9,10],[1,3,5,7,10,12,15,20,0,0],[5,10,20,50,100,200,250,300,400,500]
def is_valid(guess):
try:
guess=int(guess)
return True,guess
except:
print("Try again, not a number")
repeat=1
def GameLevel(Range,gameLives,level,hints):
lives,hints,targetnumber,repeat=gameLives,hints,random.randint(1,1),1
print("LEVEL {}\nThinking...".format(level))
if level>1:
print("You now have {} lives remaining".format(gameLives))
if level==10:
print("Welcome to the hardest level\nNo bonus lives are awarded for the final level")
print("This number is between 1 and "+str(Range))
while repeat==1:
guess=input("What is your guess? ")
guess,repeat,targetnumber=guess.lower(),0,str(targetnumber)
if guess=="hint":
if level>=3:
if hints!=1:
targetnumber=int(targetnumber)
print("Number is between {} and {}".format((targetnumber // 10) * 10, (targetnumber // 10 + 1) * 10))
repeat,hints=1,hints-1
else:
print("Sorry you have ran out of hints :(")
repeat=1
else:
print("Hints are not available until level 3")
repeat=1
elif guess==targetnumber:
print("Well done, You have guessed my number!")
return lives,hints
elif guess!=targetnumber:
if is_valid(guess)==True:
print("Sorry that is not my number, you have lost a life. :(")
targetnumber,lives,repeat=int(targetnumber),lives-1,1
if lives<=0:
print("You have lost all your lives, so this means I win\nThe program will now end")
input("")
exit()
if guess<targetnumber:
print("The target number is higher")
else:
print("The target number is lower")
else:
repeat=1
print("Welcome to my number guessing game!\nI will think of a number between a certain range and you have to guess it.\nEach time you guess my number I will think of a harder one.\nYou will start with {} lives and {} hints, Good Luck!\nTo use your hint you will have to enter the word hint\nExtra lives will be awarded for each completed level".format(gameLives,(hints-1)))
a,b=0,0
for level in levels:
Range=levelRange[a]
gameLives,hints=GameLevel(Range,gameLives,level,hints)
if gameLives>0 and wonGame!=10:
addLives=awardedLives[b]
if addLives!=0:
print("You have gained {} extra lives".format(addLives))
gameLives+=addLives
wonGame+=1
a,b=a+1,b+1
score=gameLives+10*(hints-1)
print("Calculating your score.\nYour score is {} . Well done!".format(score))

This was the smallest that I ever managed to get the program with still working in the same way, in the question the code was 63 lines, I managed to reduce it to 29 lines;
import random; gameLives,hints,wonGame,levels,awardedLives,levelRange=3,6,0,[1,2,3,4,5,6,7,8,9,10],[1,3,5,7,10,12,15,20,0,0],[5,10,20,50,100,200,250,300,400,500]
def is_valid(y):
try:y=int(y);return True
except:print("Try again, not a number")
def GameLevel(Range,gameLives,level,hints):
lives,hints,targetnumber=gameLives,hints,random.randint(1,Range);print("LEVEL {}\nThinking...".format(level))
if level>1:print("You now have {} lives remaining".format(gameLives))
if level==int(levels[-1]):print("Welcome to the hardest level\nNo bonus lives are awarded for the final level")
print("This number is between 1 and "+str(Range))
while True:
guess=input("What is your guess? ");targetnumber=str(targetnumber)
if guess.lower()=="hint":
if level>=3:
if hints!=1:targetnumber,hints=int(targetnumber),hints-1;print("Number is between {} and {}".format((targetnumber // 10) * 10, (targetnumber // 10 + 1) * 10))
else:print("Sorry you have ran out of hints :(")
else:print("Hints are not available until level 3")
elif guess==targetnumber:print("Well done, You have guessed my number!");return lives,hints
elif guess!=targetnumber and is_valid(guess)==True:
print("Sorry that is not my number, you have lost a life. :(");guess,targetnumber,lives=int(guess),int(targetnumber),lives-1
if lives<=0:exit(input("You have lost all your lives, so this means I win\nThe program will now end\n"))
print("The target number is {}".format("higher" if (guess<targetnumber) else "lower"))
print("Welcome to my number guessing game!\nI will think of a number between a certain range and you have to guess it.\nEach time you guess my number I will think of a harder one.\nYou will start with {} lives and {} hints, Good Luck!\nTo use your hint you will have to enter the word hint\nExtra lives will be awarded for each completed level".format(gameLives,(hints-1)));a,b=0,0
for level in levels:
gameLives,hints=GameLevel((levelRange[a]),gameLives,level,hints)
if gameLives>0 and wonGame!=int(levels[-1]):
if awardedLives[b]>0:print("You have gained {} extra lives".format(awardedLives[b]));gameLives+=awardedLives[b]
wonGame+=1
a,b=a+1,b+1
input("Calculating your score.\nYour score is {} . Well done!".format(gameLives+10*(hints-1)))

Related

How do I stop a while loop if something happens inside a function that should stop the itterations?

Hello fellow programmers! I am a beginner to python and a couple months ago, I decided to start my own little project to help my understanding of the whole development process in Python. I briefly know all the basic syntax but I was wondering how I could make something inside a function call the end of the while loop.
I am creating a simple terminal number guessing game, and it works by the player having several tries of guessing a number between 1 and 10 (I currently made it to be just 1 to test some things in the code).
If a player gets the number correct, the level should end and the player will then progress to the next level of the game. I tried to make a variable and make a true false statement but I can't manipulate variables in function inside of a while loop.
I am wondering how I can make it so that the game just ends when the player gets the correct number, I will include my code down here so you guys will have more context:
import random
import numpy
import time
def get_name(time):
name = input("Before we start, what is your name? ")
time.sleep(2)
print("You said your name was: " + name)
# The Variable 'tries' is the indication of how many tries you have left
tries = 1
while tries < 6:
def try_again(get_number, random, time):
# This is to ask the player to try again
answer = (input(" Do you want to try again?"))
time.sleep(2)
if answer == "yes":
print("Alright!, well I am going to guess that you want to play again")
time.sleep(1)
print("You have used up: " + str(tries) + " Of your tries. Remember, when you use 5 tries without getting the correct number, the game ends")
else:
print("Thank you for playing the game, I hope you have better luck next time")
def find_rand_num(get_number, random, time):
num_list = [1,1]
number = random.choice(num_list)
# Asks the player for the number
ques = (input("guess your number, since this is the first level you need to choose a number between 1 and 10 "))
print(ques)
if ques == str(number):
time.sleep(2)
print("Congratulations! You got the number correct!")
try_again(get_number, random, time)
elif input != number:
time.sleep(2)
print("Oops, you got the number wrong")
try_again(get_number, random, time)
def get_number(random, try_again, find_rand_num, time):
# This chooses the number that the player will have to guess
time.sleep(3)
print("The computer is choosing a random number between 1 and 10... beep beep boop")
time.sleep(2)
find_rand_num(get_number, random, time)
if tries < 2:
get_name(time)
tries += 1
get_number(random, try_again, find_rand_num, time)
else:
tries += 1
get_number(random, try_again, find_rand_num, time)
if tries > 5:
break
I apologize for some of the formatting in the code, I tried my best to look as accurate as it is in my IDE. My dad would usually help me with those types of questions but it appears I know more python than my dad at this point since he works with front end web development. So, back to my original question, how do I make so that if this statement:
if ques == str(number):
time.sleep(2)
print("Congratulations! You got the number correct!")
try_again(get_number, random, time)
is true, the while loop ends? Also, how does my code look? I put some time into making it look neat and I am interested from an expert's point of view. I once read that in programming, less is more, so I am trying to accomplish more with less with my code.
Thank you for taking the time to read this, and I would be very grateful if some of you have any solutions to my problem. Have a great day!
There were too many bugs in your code. First of all, you never used the parameters you passed in your functions, so I don't see a reason for them to stay there. Then you need to return something out of your functions to use them for breaking conditions (for example True/False). Lastly, I guess calling functions separately is much more convenient in your case since you need to do some checking before proceeding (Not inside each other). So, this is the code I ended up with:
import random
import time
def get_name():
name = input("Before we start, what is your name? ")
time.sleep(2)
print("You said your name was: " + name)
def try_again():
answer = (input("Do you want to try again? "))
time.sleep(2)
# Added return True/False to check whether user wants to play again or not
if answer == "yes":
print("Alright!, well I am going to guess that you want to play again")
time.sleep(1)
print("You have used up: " + str(tries) + " Of your tries. Remember, when you use 5 tries without getting the correct number, the game ends")
return True
else:
print("Thank you for playing the game, I hope you have better luck next time")
return False
# Joined get_number and find_random_number since get_number was doing nothing than calling find_rand_num
def find_rand_num():
time.sleep(3)
print("The computer is choosing a random number between 1 and 10... beep beep boop")
time.sleep(2)
num_list = [1,1]
number = random.choice(num_list)
ques = (input("guess your number, since this is the first level you need to choose a number between 1 and 10 "))
print(ques)
if ques == str(number):
time.sleep(2)
print("Congratulations! You got the number correct!")
# Added return to check if correct answer is found or not
return "Found"
elif input != number:
time.sleep(2)
print("Oops, you got the number wrong")
tries = 1
while tries < 6:
if tries < 2:
get_name()
res = find_rand_num()
if res == "Found":
break
checker = try_again()
if checker is False:
break
# Removed redundant if/break since while will do it itself
tries += 1

How can i improve this? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I am currently self teaching myself Python , and this is my first program. I am doing some simple projects so i can improve. Would like to hear feedback on this one.
import random
print("There is a number between 1 and 100 guess it and you will win a price : ")
def guess():
# A simple guess game.
random_number = random.randint(1, 5)
flag = True
user_guess = []
while flag:
user_number = input("Enter the number : ")
user_guess.append(user_number)
if int(user_number) < random_number:
print("You have to go higher")
elif int(user_number) > random_number:
print("You have to go lower ")
else:
flag = False
print("Congrats you win !!! \nThe numbers of guesses before you won : ")
print(len(user_guess))
guess()
while True:
play_again = input("Do you like to play again ? : (y/n): ")
if play_again == 'y':
guess()
else:
print("Thank you for playing have a nice day!!! ")
break
Your program will throw an exception if the user enters an invalid (nondigit) character. Use isdigit to avoid such cases.
Converting user_number to integer every time you want to compare it with some other integer is costly, and frivolous. Convert it once and reassign it to user_number.
flag is not necessary. Use while True, and break when needed.
Keeping an entire list object just to count user input is a bit overkill. Have a single integer (count in my example) and use it.
You print "between 1 and 100" but your program creates a random integer between 1 and 5. I am not sure about your intentions with doing that (perhaps a debugging aid), but I presume it's a small mistake.
A minor suggestion, move the print("There is a number between 1 and 100 guess it and you will win a price : ") to the guess function since it makes more sense for the function to declare its own purpose.
Here's how I would make those changes to the guess function:
def guess():
print("There is a number between 1 and 100 guess it and you will win a price : ")
# A simple guess game.
random_number = random.randint(1, 100)
# flag = True obsolete
count = 0
while True:
user_number = input("Enter the number : ")
if (user_number.isdigit()):
user_number = int(user_number)
else:
print("Invalid:")
continue
count += 1
if user_number < random_number:
print("You have to go higher")
elif user_number > random_number:
print("You have to go lower ")
else:
print("Congrats you win !!! \nThe numbers of guesses before you won : ")
print(count)
break

Trying to add my first score counter (Python) (Beginner)

This is my first post here. I'm a total beginner in coding and I've created a little game to get some sort of practice. I'm having trouble adding a score counter to it. I've seen some similar posts but I didn't manage to figure it out.
Also can you guys/girls give me some tips on my code, any feedback is welcome (tell me what I can improve etc.)
Here is the code:
import random
import time
def game():
user_wins = 0
user_loses = 0
while True:
try:
number = int(input('Choose a number between 1 and 10: '))
if 0 <= number <= 10:
print('Rolling the dices {} time(s)!'.format(number))
break
else:
print("That's not quite what we were looking for.")
continue
except ValueError:
print("That's not quite what we were looking for.")
user_number = random.randint(1, 50)
computer_number = random.randint(1, 50)
time.sleep(1)
print("You've rolled {}".format(user_number))
time.sleep(1)
print('Bob rolled {}'.format(computer_number))
if computer_number > user_number:
time.sleep(0.5)
print('Bob Won')
user_loses += 1
elif computer_number < user_number:
time.sleep(0.5)
print("You've Won!")
user_wins += 1
elif computer_number == user_number:
time.sleep(0.5)
print('Seems like we have a little situation')
print("\nWins: {} \nLosses: {}".format(user_wins, user_loses))
time.sleep(0.5)
play_again = input(str("Would you like to play again (y/n)? "))
if play_again == 'y':
print("Ready?\n")
game()
else:
print("\nThank you for playing.")
game()
I want to add something like Your score: 1-0 or something similar. I've made some progress on that but when looping the values reset..
Welcome to programming! So I'm going to tell you how to implement it, so you can do it yourself as well :D. So here is what we will do:
We will have a variable outside the scope(click here) of the while loop to keep track of the score, say score = 0.
And each time someone succeeds, gets the right answer, we will increase that, by saying, score = score + 1. But that takes too much time to type that right D: So python has a shortcut! You say score += 1 somewhere in your code where you want to increase the score (in the while True loop, in this case). And then we will later print out the score (or anything) by referencing it:
print( "Your final score was %s" % str(score) ) - I know, what is that stupid str() for!? It is because our score is an integer. Since we can add and do operations on it(yeah I know soo cool).
Aaaand thats it :). If you need any further help, don't hesitate to ask it. Good luck :D.
Move this line before the while loop starts.
number = int(input('Choose a number between 1 and 10: '))
Also, it prompts to input between 1-10 but the if statement allows 0-10.
To add a counter start by assigning an initial to score to both players to 0.
user_number_score = 0
inside the If statements that determine who won the round for example if the user won add...
user_number_score = user_number_score + 1
I've found a way to do it. I had to start over, re-done the code from scratch and it's better looking too. Thank you all for the feedback.
Added it as image.

Creating a Quiz in Python - error [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
As a novice to Python myself, I encountered an error when trying to develop a Quiz program. I found that when the program generates two random numbers to add together, and the user attempts to enter in the correct values for the question, the program trips up and still prints that the input from the user is invalid.
def quiz():
print("The quiz will begin shortly")
print(numberone)
print("+")
print(numbertwo)
answerone=input("Answer:")
if answerone==(numberone + numbertwo):
print("Correct")
score+1
print("You're score is", score, ".")
else:
print("Incorrect")
print(numberone+numbertwo)
I do not understand what I am doing wrong, so any help would be much appreciated.
(NOTE: 'numberone' and numbertwo' are both defined)
Your issue is that input from your user is a string. You will need to convert it to an integer before you can compare it.
int(answerone)
so try this:
def quiz():
print("The quiz will begin shortly")
print(numberone)
print("+")
print(numbertwo)
answerone=input("Answer:")
if int(answerone)==(numberone + numbertwo):
print("Correct")
score += 1
print("You're score is {}.".format(str(score)))
else:
print("Incorrect")
print(numberone+numbertwo)
You'll either need to define numberone and numbertwo in the function quiz:
def quiz():
numberone = 6
numbertwo = 3 # etc.
Or, pass them as parameters:
def quiz(numberone, numbertwo):
print numberone #etc
You forgot to assign score while incrementing
is:
print("Correct")
score+1
print("You're score is", score, ".")
should be:
print("Correct")
score += 1
print("You're score is", score, ".")
There are bunch of problems in your code. Let's see one by one.
Your indentation is all wrong. You should first fix it.
numberone, numbertwo and score can't be accessed under this scope. One good idea is to pass them as function parameter.
Like this:
def quiz(numberone,numbertwo,score):
As answerone should be an integer, cast the input as int
Like this:
answerone=int(input("Answer:")) #if using python3
You are adding 1 with score, but aren't assigning it back.
Use score=score+1 or score+=1 rather score+1
Return score from the function to use the updated value of score for next call.
So, the working code can be like this:
def quiz(numberone,numbertwo,score):
print("The quiz will begin shortly")
print(numberone)
print("+")
print(numbertwo)
answerone=int(input("Answer:"))
if answerone==(numberone + numbertwo):
print("Correct")
score += 1
print("You're score is", score, ".")
else:
print("Incorrect")
print(numberone+numbertwo)
return score
You can call it like below:
score=0
while(score<10):
score=quiz(someRandNumber,anotherRandNumber,score)
else:
print "Your score is 10"

Python 3.1 number guessing game higher or lower loop

In the process of learning Python using the book 'Python Programming for the Absolute Beginner Third Edition' and struggling with a challenge that has been set.
I have to create a Number Guessing program where the player picks a number and the program tries to guess it by picking a random number then using higher or lower questions to get closer to the number. I've got most of it figured out but I'm struggling with the higher or lower loop. The trouble I'm having is that i can't get the program to not go above or below it's second to last guess i.e.
My number is 78
computer picks 50
i say higher
computer picks 80
i say lower
computer can then pick 12 (when i don't want it going below 50.
I'm using Python 3.1
Here is a copy of the code.
import random
computer_tries = 0
player_number = None
computer_guess = random.randint(1, 100)
print(
"""
Welcome Player to the fabulous number guessing game.
Please allow me to show you my incredible deduction skills
""")
question = None
while question != ("yes"):
question = input("Has the player picked a number? ")
question = question.lower()
if question == "yes":
print("\nI will now guess your number!!!\n")
while player_number == None:
computer_tries += 1
print(computer_guess, "\n")
confirmation = input("Is this the correct number? ")
confirmation = confirmation.lower()
if confirmation == "yes":
player_number = computer_guess
if computer_tries < 2:
print("I did it! I guessed your number was", computer_guess,
"and it only \ntook me", computer_tries,
"try to get it right!")
else:
print("I did it! I guessed your number was", computer_guess,
"and it only \ntook me", computer_tries,
"tries to get it right!")
else:
higher_lower = None
while higher_lower not in ("higher", "lower"):
higher_lower = input("Is my guess higher or lower"
+ " than your number? ")
higher_lower = higher_lower.lower()
if higher_lower == "higher":
higher = computer_guess
computer_guess = random.randint(higher, 101)
elif higher_lower == "lower":
lower = computer_guess
computer_guess = random.randint(0, lower)
else:
print("Please choose either higher or lower.")
input("\n\nPress the enter key to exit")
Thanks in advance for any help you folks can give.
Ally
I see the following problems with your code:
your random number generators are bound only on one side of the number spectrum, e.g. random.randint(0, lower) - so it's ignoring the higher bound. Similarly for computer_guess = random.randint(higher, 101).
I suggest you initialise higher and lower.
Some debug helps :)
Here's the working code:
import random
computer_tries = 0
player_number = None
computer_guess = random.randint(1, 100)
print(
"""
Welcome Player to the fabulous number guessing game.
Please allow me to show you my incredible deduction skills
""")
question = None
lower = 0 # initial lower guess
higher = 101 # initial higher guess
while question != ("yes"):
question = input("Has the player picked a number? ")
question = question.lower()
if question == "yes":
print("\nI will now guess your number!!!\n")
while player_number == None:
computer_tries += 1
print(computer_guess, "\n")
confirmation = input("Is this the correct number? ")
confirmation = confirmation.lower()
if confirmation == "yes":
player_number = computer_guess
if computer_tries < 2:
print("I did it! I guessed your number was", computer_guess,
"and it only \ntook me", computer_tries,
"try to get it right!")
else:
print("I did it! I guessed your number was", computer_guess,
"and it only \ntook me", computer_tries,
"tries to get it right!")
else:
higher_lower = None
while higher_lower not in ("higher", "lower"):
higher_lower = input("Is my guess higher or lower"
+ " than your number? ")
higher_lower = higher_lower.lower()
if higher_lower == "higher":
higher = computer_guess
computer_guess = random.randint(lower+1, higher-1)
elif higher_lower == "lower":
lower = computer_guess
computer_guess = random.randint(lower+1, higher-1)
else:
print("Please choose either higher or lower.")
print("DEBUG: number must be " + str(lower) + " < x < " + str(higher))
input("\n\nPress the enter key to exit")
You have to store something like min_comp_guess and max_comp_guess
Then, when you are about to "guess" number you have to generate it for a valid range (obviously min_comp_guess up to max_comp_guess).
I'm always second! :)
You are never storing the upper and lower bounds to the possible numbers. In your example, as soon as your program picks 50 and you say "higher", you need to store somewhere the information that "the number is definitely higher than 50". The same goes for when you answer "lower".
I may be completely wrong but whilst testing your code I found that by choosing the programs number was higher than my chosen number it would increase the number instead or a presumable decrease, not making it any closer to the number I had guessed. A similar higher/lower program I created had the same problem, to fix the problem I simply switched the more than and less than signs around, hopefully you find this helpful and could apply this to your program.

Categories