How do I break this while loop? [python] - python

I'm tying to make it so when you enter a digit value in the while loop, the loop ends and so does the program. However when I type "break" I get an invalid syntax error:(. Sorry for the bad coding, this is my first time.
print('Hello, world!')
print('What is your name?')
myName = input()
print('It is nice to met you, '+ myName)
print('The length of your name is:')
print(len(myName))
print('What is your age?')
myAge=input()
if myAge.isdigit():print('You will be ' + str(int(myAge) + 1) + ' in "one" year')
else: print('that is not a number. Lets try again, what is your age?')
C = 0
while (C<=3):
myAge2=input()
C+=1
if myAge2.isdigit():print('You will be ' + str(int(myAge2) + 1) + ' in "one" year')
break
else: print('Try again')

Indentation to apply the correct break
if myAge2.isdigit():
print('You will be ' + str(int(myAge2) + 1) + ' in "one" year')
break
else:
print('Try again')

I tried simplifying the code:
print('Hello, world!\nWhat is your name')
myName = input()
print('It is nice to met you, {}.\nThe length of your name is: {}'.format(myName, len(myName)))
print('What is your age?')
myAge=input()
if myAge.isdigit():
print('You will be ' + str(int(myAge) + 1) + ' in "one" year')
else:
print('that is not a number. Lets try again, what is your age?')
myAge2=input()
while myAge2.isdigit():
print('You will be ' + str(int(myAge2) + 1) + ' in "one" year')
break
else:
print('Try again')

Problem with the code indentation, otherwise everything is working perfectly.
print('Hello, world!')
print('What is your name?')
myName = input()
print('It is nice to met you, ' + myName)
print('The length of your name is:')
print(len(myName))
print('What is your age?')
myAge = input()
if myAge.isdigit():
print('You will be ' + str(int(myAge) + 1) + ' in "one" year')
else:
print('that is not a number. Lets try again, what is your age?')
C = 0
while (C <= 3):
myAge2 = input()
C += 1
if myAge2.isdigit():
print('You will be ' + str(int(myAge2) + 1) + ' in "one" year')
break
else:
print('Try again')
Output

Related

How to continue with number of guesses after ValueError in guessing game?

I'm going through the Automate the Boring Stuff with Python videos on youtube. I finished the one about random number guessing game and am now adding some stuff to it to make it more complete.
I added some code that makes it so that if you don't enter an integer (which creates a ValueError) the program tells you that you didn't enter an integer. However, the point of the game is that you only get 6 guesses, but when the error comes up it, it resets the number of guesses.
How can I make it so that the error doesn't reset the number of cases?
Here's the code:
# This is a guess the number game.
import random
print ('Hello, what is your name?')
name = input ()
name = name.strip()
print ('Well, ' + name + ' I am thinking of a number between 1 and 20.')
secretNumber = random.randint (1, 20)
print ('DEBUG: Secret number is ' + str(secretNumber))
while True:
try:
for guessesTaken in range (1, 7):
print ('Take a guess.')
guess = int (input ())
if guess < secretNumber:
print ('Your guess is too low.')
elif guess > secretNumber:
print ('Your guess is too high.')
else:
break # This condition is for the correct guess
if (guess == secretNumber and guessesTaken == 1):
print ('Good job, ' + name + '! You guessed my number in ' + str(guessesTaken) + ' guess.')
break
elif (guess == secretNumber and guessesTaken > 1):
print ('Good job, ' + name + '! You guessed my number in ' + str(guessesTaken) + ' guesses.')
break
else:
print ('Nope. The number I was thinkig of was ' + str(secretNumber))
break
except ValueError:
print ('You did not enter a number.') # This condition is for if a non-integer is entered.
I feel like I've tried every combination of where I can but the try and for loop, but can't seem to figure it out.
The outer while loop seems unnecessary because it allows you to try even after 6 attempts.
Therefore the break in the last three conditions will also be deleted.
You should put the try into the for loop so that if an exception is raised, the program will continue to count the number of attempts.
I would do something like:
# This is a guess the number game.
import random
print('Hello, what is your name?')
name = input()
name = name.strip()
print('Well, ' + name + ' I am thinking of a number between 1 and 20.')
secretNumber = random.randint(1, 20)
print('DEBUG: Secret number is ' + str(secretNumber))
for guessesTaken in range(1, 7):
try:
print('Take a guess.')
guess = int(input())
if guess < secretNumber:
print('Your guess is too low.')
elif guess > secretNumber:
print('Your guess is too high.')
else:
break # This condition is for the correct guess
except ValueError:
print('You did not enter a number.') # This condition is for if a non-integer is entered.
if (guess == secretNumber and guessesTaken == 1):
print('Good job, ' + name + '! You guessed my number in ' + str(guessesTaken) + ' guess.')
elif (guess == secretNumber and guessesTaken > 1):
print('Good job, ' + name + '! You guessed my number in ' + str(guessesTaken) + ' guesses.')
else:
print('Nope. The number I was thinkig of was ' + str(secretNumber))
The except block also should be moved, to be related to the try block, under the block of the loop because we don't want to stop the for loop as I mentioned before.
This is a guess the number game.
import random
print ('Hello, what is your name?')
name = input ()
guess = 0
name = name.strip()
print ('Well, ' + name + ' I am thinking of a number between 1 and 20.')
secretNumber = random.randint (1, 20)
print ('DEBUG: Secret number is ' + str(secretNumber))
while True:
for guessesTaken in range (1, 7):
try:
print ('Take a guess.')
guess = int (input ())
if guess < secretNumber:
print ('Your guess is too low.')
elif guess > secretNumber:
print ('Your guess is too high.')
else:
break # This condition is for the correct guess
except ValueError:
print ('You did not enter a number.') # This condition is for if a non-integer is entered.
if (guess == secretNumber and guessesTaken == 1):
print ('Good job, ' + name + '! You guessed my number in ' + str(guessesTaken) + ' guess.')
break
elif (guess == secretNumber and guessesTaken > 1):
print ('Good job, ' + name + '! You guessed my number in ' + str(guessesTaken) + ' guesses.')
break
else:
print ('Nope. The number I was thinkig of was ' + str(secretNumber))
break

Why do i get "str" object not callable error [duplicate]

This question already has answers here:
Why does code like `str = str(...)` cause a TypeError, but only the second time?
(20 answers)
Closed 2 years ago.
I am trying to learn Python. I am currently writing my first program and following Automate the Boring Stuff. I have run into an error that I cannot understand. I am running python 3.9.1. The lines in question run perfectly fine on their own, but give me the following error:
line 11, in <module>
print ('Pick a number.')
TypeError: 'str' object is not callable
Here is the total code:
import random
print ('Hello! What is your name?')
name = input()
print = ('Hi, ' + name + '. I am thinking of a number between -99 and 99.')
secretNumber = random.randint(-99,99)
for guessesTaken in range(1,7):
print ('Pick a number.')
guess = int(input())
if guess < secretNumber:
print ('Your guess is too low. Guess again.')
elif guess > secretNumber:
print('Your guess is too high. Guess again.')
else:
break # This means the guess was correct
if guess == secretNumber:
print ('Good job, ' + name + '. You guessed the value in ' + str(guessesTaken) + ' guesses.')
else:
print ('You did not guess the number. The correct number was ' + str(secretNumber) + '.')
The problem is in the line 6 actually, where you try to assign an value to the print:
print = ('Hi, ' + name + '. I am thinking of a number between -99 and 99.')
You should delete that = and the code will work :)
import random
print('Hello! What is your name?')
name = input()
print('Hi, ' + name + '. I am thinking of a number between -99 and 99.')
secretNumber = random.randint(-99,99)
for guessesTaken in range(1,7):
print ('Pick a number.')
guess = int(input())
if guess < secretNumber:
print ('Your guess is too low. Guess again.')
elif guess > secretNumber:
print('Your guess is too high. Guess again.')
else:
break # This means the guess was correct
if guess == secretNumber:
print ('Good job, ' + name + '. You guessed the value in ' + str(guessesTaken) + ' guesses.')
else:
print ('You did not guess the number. The correct number was ' + str(secretNumber) + '.')
Because of your line
print = ('Hi, ' + name + '. I am thinking of a number between -99 and 99.')
where your redefined the built-in function print to be a string.
Remove = from that command:
print('Hi, ' + name + '. I am thinking of a number between -99 and 99.')

When executing code Unexpected EOF while Parsing?

I tried to use this code i found on the internet to test some stuff
my code:
print('what is your age')
myAge = input()
print('you will be ' + str(int(myAge) + 1 ) + 'in one year'
but did not work and said unexpected EOF in parsing
(i am new to this stuff and im just testing these stuff this out)
You need to close the last print bracket:
print('what is your age')
myAge = input()
print('you will be ' + str(int(myAge) + 1 ) + ' in one year')
Because of no ')' at the end of 3rd line it throws error
myAge = input('what is your age\n')
print('you will be ' + str(int(myAge) + 1) + ' in one year')
We can combine the first print line and input () as
myAge = input('what is your age\n')
use have missing )
use the format method , much readable not casting
print('what is your age')
myAge = int(input())
print('you will be {} in one year'.format(myAge+1))

Check whether a number lies between two other numbers

For some reason my code won't return False EVER and I cant figure it out?
I think the issue is with how my between function is written but it makes sense to me. Also I am struggling to get my restart function to work. If somebody could help me with those 2 areas I would be extremely grateful.
def between(a,b,c):
if a>b and b<c:
Rnum =True
else:
Rnum=False
def main(): #main function need in all programs for automated testing
print ("This program will ask the user for 3 numbers and determine if
the second number lies betweenthe first and the third")
print()
while True:
numone=input('Please enter the first number - the low number:')
if numone.isdigit():
numone=int(numone)
break
else:
print('Invalid response. Please enter a whole number.')
while True:
numtwo=input('Please enter the second number - the test number: ')
if numtwo.isdigit():
numtwo=int(numtwo)
break
else:
print('Invalid response. Please enter a whole number.')
while True:
numthree=input('Please enter the third number - the high number:')
if numthree.isdigit():
numthree=int(numthree)
break
else:
print('Invalid response. Please enter a whole number.')
sprint()
number =between(numone,numtwo,numthree)
print('The statement ' + str(numone) + ' lies between ' + str(numtwo) + ' and ' + str(numthree) + ' is True.'"\n")
#Restart question
while True:
restart = input('Would you like to play again (Y/N)? ')
if restart == 'Y' or restart == 'y':
print('Restarting!' + ('\n' * 2))
break
if restart == 'N' or restart == 'n':
print('Thank you for playing.' + ('\n' *2))
break
else:
print("Invalid response. Please answer with a 'Y' or 'N'")
if restart == 'N' or restart == 'n':
break
else:
continue
if __name__ == '__main__' :
main() #excucte main function
The logic of your between function was slightly wrong (I've rename the variables to make it slightly clearer). In addition, you were not returning the value of the function so it was basically doing nothing. You were also always printing "True".
I have modified your code to return the result of the between function. I have made the result of this function a variable called true_or_false which is then printed at the end of each game.
In order to get your code to loop, all you need is another while loop which you can break out of if the user does not want to continue.
def between(low,test,high):
if low < test < high:
return True
else:
return False
def main(): #main function need in all programs for automated testing
print ("This program will ask the user for 3 numbers and determine if\nthe second number lies betweenthe first and the third")
while True:
while True:
numone=input('\nPlease enter the first number - the low number:')
if numone.isdigit():
numone=int(numone)
break
else:
print('Invalid response. Please enter a whole number.')
while True:
numtwo=input('Please enter the second number - the test number: ')
if numtwo.isdigit():
numtwo=int(numtwo)
break
else:
print('Invalid response. Please enter a whole number.')
while True:
numthree=input('Please enter the third number - the high number:')
if numthree.isdigit():
numthree=int(numthree)
break
else:
print('Invalid response. Please enter a whole number.')
true_or_false =between(numone,numtwo,numthree)
print('The statement ' + str(numtwo) + ' lies between ' + str(numone) + ' and ' + str(numthree) + ' is ' + str(true_or_false) + "\n")
restart = ""
while restart.upper() != "Y":
restart = input('Would you like to play again (Y/N)? ')
if restart.upper() == "Y":
print('Restarting!')
elif restart.upper() == "N":
print ('Thank you for playing.')
sys.exit()
else:
print("Invalid response. Please answer with a 'Y' or 'N'")
if __name__ == '__main__' :
main() #excucte main function
You have small mistake, either in the problem definition or in the example code. Anyways if you modify it a bit:
def between(a,b,c): if b>a and b<c: return 'True'
else: return 'False'
print('The statement ' + str(numtwo) + ' lies between '
+ str(numone) + ' and ' + str(numthree) + ' is ' +
between(a,b,c) +"\n")

Why doesn't Python like line 31?

Why doesn't Python like the commented print line when it is uncommented and the other line is not there?
# This is a guess the number game
import random
guessesTaken = 0
myName = input('Hi there! What is your name?')
number = random.randint(1, 20)
print('Well ' + myName + ' I am thinking of a number between 1 and 20')
while guessesTaken < 6:
guess = int(input('Try and guess what it is!')) # There are 4 spaces in front of print.
# guess = int(input ())
guessesTaken = guessesTaken + 1
if guess < number:
print('Your guess is too low') # There are 8 spaces in front of print.
if guess > number:
print('Your guess is too high')
if guess == number:
break
if guess == number:
guessesTaken = str(guessesTaken)
# print('Good Job, ' + myName + '! You guessed my number ' + number + ' in ' + guessesTaken + ' guesses!')
print('Good Job, ' + myName + '! You guessed my number in ' + guessesTaken + ' guesses!')
if guess != number:
number = str(number)
print('I am sorry. The number I was thinking of was ' + number + ' Thanks for playing, though.')
input('\n\nPress Enter to exit')
Because number is an integer. Turn it into a string too:
print('Good Job, ' + myName + '! You guessed my number ' + str(number) + ' in ' + guessesTaken + ' guesses!')
However, it'd be much better to use str.format() string formatting:
print('Good Job, {0}! You guessed my number {1} in {2} guesses!'.format(
myName, number, guessesTaken))
String formatting converts inputs for you; see the Format String Syntax documentation for more details on what formatting options you have.
number is an integer. You can't add integers and strings, as the error message you received almost certainly told you.
Convert it to a string using str(number).
The problem is that number is an integer. As the error message you received stated, you can't add integers and strings together.
You can convert it into a string using str(number) like I have done below.
This is what it should be:
print('Good Job, ' + myName + '! You guessed my number ' + str(number) + ' in ' + guessesTaken + ' guesses!')

Categories

Resources