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 3 months ago.
Improve this question
I wrote this code snippet:
lowestNumber = int(input("\nWhat would you like your lowest number to be?"))
highestNumber = int(input("What would you like your highest number to be?"))
number = random.randint(lowestNumber, highestNumber)
tries = 0
while tries < 10:
guess = int(input(f'\nEnter a number between', lowestNumber))
if guess == number:
print("You guessed correctly! The number was", number)
break
elif guess < number:
print("Too low!")
elif guess > number:
print("Too high!")
tries += 1
SyntaxError: bad input on line 22 in main.py.
Line 22 was guess = int(input(f'\nEnter a number between', lowestNumber)).
I searched it up on google and got nothing, I pasted it into OpenAI's code fixing and it also didn't help.
How can I fix this error?
When you wrote
guess = int(input(f'\nEnter a number between', lowestNumber))
it passed both the string and lowestNumber into the input function. However, you probably wanted to write something like Enter a number between (lowestNumber) and (highestNumber). To do this, you would have to write
guess = int(input(f'\nEnter a number between {lowestNumber} and {highestNumber}. '))
In my example, it passes in one object, the string, which contains lowestNumber and highestNumber in it. In your example, it passes in two objects, the string and lowestNumber.
The formatting you did in the input functions works in print statements, so the print statements are correct, but the input function is not.
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
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)))
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Here is my code:
name = input("What is your name? ")
print name + " do you want to play a game?"
answer = input("To play the game, type either yes or no. ")
if answer == yes:
print "Great," + name + "lets get started!"
elif answer == no:
print "Okay, good bye!"
import random
number = random.randint(1,50)
guess = input ("Pick a number between 1 and 50. This number cannot be a decimal. ")
if guess > number:
print "Your guess is too high!"
elif guess < number:
print "Your guess is too low!"
while guess != number:
print "Try again!"
else import random
number = random.randint(1,50)
if guess == number:
print "You guessed it!"
print "Great job."
print "Do you want to play again?"
while answer == yes:
import random
number = random.randint(1,50)
guess = input ("Pick a number between 1 and 50. This number cannot be a decimal. ")
if guess > number:
print "Your guess is too high!"
elif guess < number:
print "Your guess is too low!"
while guess != number:
print "Try again!"
if guess == number:
print "You guessed it!"
print "Great job."
print "Do you want to play again?
elif answer == no:
print "Okay. Good game " + name + "!"
print "Play again soon!"
Ok, my first question is why does python not recognize input for the name variable as a string.
The second question is the last elif statement keeps giving me a syntax error. I am not sure why.
The last question is can I loop this code any easier way?
In Python 2x versions, input() takes variable as integer, you could use raw_input() to take it as string.
So basically change your input() to raw_input() for taking the data as string.
In Python 3x versions there is no raw_input, there is only input() and it takes the data as string.
Second question;
elif guess < number:
print "Your guess is too low!"
while guess != number:
print "Try again!"
else import random
number = random.randint(1,50)
This is not a correct syntax, your else needs an if block above itself. You can't use else without an if block.If you think for a second, that makes sense.
Your last question is not fit with SO rules.
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 6 years ago.
Improve this question
I have 2 questions about my code. Why the program doesn't go in the second if statement. How can I end the loop?
from random import *
SecretNumber=randint(1,5)
Guess=int(input("Please enter Guess: "))
NumberofGuesses=1
SecretNumber=0
while Guess != SecretNumber:
NumberofGuesses=NumberofGuesses+1
if Guess>SecretNumber:
print("Please insert a smaller number")
else:
print("Please insert a bigger number")
if Guess==SecretNumber:
print("Number of Guesses: {0}".format(NumberofGuesses))
Your second if is outside the while loop, so it won't get hit until you guesss the secret number. The loop never ends because you never read another guess.
You also have a problem that you are overriding your random secret number with zero.
You need something like:
import random
SecretNumber=random.randint(1,5)
NumberofGuesses=0
while true:
Guess=int(input("Please enter Guess: "))
NumberofGuesses += 1
if Guess == SecretNumber:
break # Got it!
elif Guess>SecretNumber:
print("Please insert a smaller number")
else:
print("Please insert a bigger number")
print("Number of Guesses: {0}".format(NumberofGuesses))
It's because you're setting SecretNumber to 0. Remove it and it should work.