#This will loop the try statement until an integer is entered as the guess1 variable
while True:
#The try statement will see if the guess variable is given an integer value,
#if not then it will print "You did not enter an integer. This is not a
#valid answer
try:
#This will allow the user to enter their answer and
#store it in the guess1 variable
guess1 = int(input(""))
#This will break the while loop if an integer is entered as the guess1 variable
break
except ValueError:
print("You did not enter an integer. This is not a valid answer. Please enter a valid integer")
print("Answer the quesiton appropiately" + "What is " + (str(first2) + op + str(second2) + "?")
if guess1 == answer1:
#If the guess1 variable is equal to the answer1 variable, then
#"Correct!" will be printed and one point would be
#added to the score
print("Correct!")
score += 1
else:
#Else "Incorrect" would be printed
print ("Incorrect")
The shell states that there is an invalid syntax with the colon when I typed 'guess1 == answer1:'.
The problem is that you didn't close a tag on the second line in your except statement. Add an extra ")" to the end.
print("Answer the quesiton appropiately" + "What is " + (str(first2) + op + str(second2) + "?"))
Related
How can I use the variable 'guess' in my guessfunction() in the main function (for i in range (1,6)? I get the error that guess is not defined. Initially everything worked fine without the guessfunction, but I wanted to add the possiblity of wrong input from the user and that got me stuck.
I saw on stackexchange that it is bad practice to use global inside a function, but even with global I don't know how to solve my issue.
Is there also a way to change the int(guess) if it is possible to get the variable from the function?
Thank you!
import random, sys
print("Hello. What is your name?")
name = str(input())
print("Well, " + name + ", I am thinking of a number between 1 and 20.")
number = random.randint(1, 20)
def guessfunction():
print("Take a guess.")
guess = input()
for number_attempts in range(0,3):
try:
return guess
except ValueError:
print("Please enter a number in figures not as a word")
print("You didn't enter a number in figures after 3 tries, program ended")
sys.exit()
for i in range(1,6):
guessfunction()
if int(guess) != number:
if int(guess) < number:
print("Your guess is too low")
else:
print("Your guess is too high")
elif int(guess) == number:
print("Good job, " + name + "! You guessed my number in " + str(i) + " guesses")
sys.exit()
print("Nope. The number I was thinking of was " +str(number))
you need to initialise it in your for loop:
guess = guessfunction()
I am currently new to Python and trying to construct a program that takes two integers and outputs whether they are larger, smaller than each other or both equal. I also want to add a while loop which asks for 2 more sets of integers each time, otherwise if the user types "quit" the program ends. Only issue is, I think my casting is off as when I type quit, it actually compares that. So if I typed quit twice it would state they're equal which is true rather than stop the program.
onenumber = int(input("Please enter your first number to compare:"))
twonumber = int(input("Please enter your second number to compare:"))
if onenumber > twonumber:
print (onenumber, "is the biggest!")
elif twonumber > onenumber:
print (twonumber, "is the biggest!")
else:
print ("Both are equal!")
while onenumber != "quit":
onenumber = input("Please enter your first number to compare, or type quit:")
twonumber = input("Please enter your second number to compare:")
if onenumber > twonumber:
print (onenumber, "is the biggest!")
elif twonumber > onenumber:
print (twonumber, "is the biggest!")
else:
print ("Both are equal!")
I changed your code slightly to begin in the while loop. Ideally, you want as few lines of code as you can and as you had two repeated lines I removed them.
Now that both number variables are not cast as int we can use the in-built string function .isdigit() which returns a True or False if the variable is a digit. This helps us out by ensuring there won't be an error when comparing them.
Happy to answer any questions you have!
while True:
number_one = input("Please enter your first number to compare or type 'quit':")
number_two = input("Please enter your second number to compare:")
if number_one.isdigit() and number_two.isdigit():
number_one = int(number_one)
number_two = int(number_two)
if number_one > number_two:
print(number_one, "is the biggest!")
elif number_two > number_one:
print(number_two, "is the biggest!")
else:
print("Both are equal!")
elif number_one == "quit":
print("Thanks for playing!")
exit()
else:
print("Please enter a number or type 'quit'!")
Actually your program does exactly what it should do. But think about it, your condition is stating: As long as onenumber is not "quit" execute all commands inside the while loop. So if your onenumber variable is "quit" it will still perform the comparison ONE TIME more before it ends the program. But after that your program will stop. But obviously this won't happen because an exception will occur. You can verify it with below code:
number1 = "proceed"
while number1 != 'quit':
number1 = str(input("declare number1"))
number2 = str(input("declare number2"))
try:
if int(number1) > int(number2):
print("number1 is is bigger than number2")
elif int(number1) < int(number2):
print("number2 is bigger than number1")
else:
print("both numbers are equal")
except:
pass
One solution for example without Exception handling would be the following:
number1 = "proceed"
while number1 != 'quit':
number1 = str(input("declare number1"))
number2 = str(input("declare number2"))
if number1 != 'quit':
if int(number1) > int(number2):
print("number1 is is bigger than number2")
elif int(number1) < int(number2):
print("number2 is bigger than number1")
else:
print("both numbers are equal")
Its easier to ask for forgiveness than permission.
https://docs.python.org/3.4/glossary.html
number_1 = input("Please enter your first number to compare or type 'quit':")
number_2 = input("Please enter your second number to compare:")
try:
smaller = int(number_1) < int(number_2)
same = int(number_1) is int(number_2)
if smaller:
print(number_1, "is the smaller")
else:
print(number_2, "is the biggest")
if same:
print("Both are equal")
except ValueError:
if number_1 == "quit"
print("Thanks for playing!")
I'm doing some Python exercises and I came across a frustrating error:
line 18, in <module>
modulo()
NameError: name 'modulo' is not defined
Code is below:
number = input("Please enter a number: ")
if number.isdigit():
def modulo():
answer = int(number) % 2
if answer == 0:
print("Your number, " + number + " is even.")
elif answer > 0:
print("Your number, " + number + " is odd.")
else:
print("Error. Please try again.")
else:
print("Please try again")
modulo()
Make modulo accept an argument, define it outside the if-statement
def modulo(num):
answer = int(num) % 2
if answer == 0:
print("Your number, " + num + " is even.")
elif answer > 0:
print("Your number, " + num + " is odd.")
else:
print("Error. Please try again.")
number = input("Please enter a number: ")
if number.isdigit():
modulo(number)
else:
print("Please try again")
You should write your function outside the if statement, in this case the function will be defined ONLY if number.isdigit() is True.
I have this problem when i run the program it all goes good an all, but when a user gets the right answer, the code does not print neither print("Good Job!") or print("Correct"). what is wrong with the code ?
import random
firstNumber = random.randint(1, 50)
secondNumber = random.randint(1, 50)
result = firstNumber + secondNumber
result = int(result)
print("Hello ! What\'s your name ? ")
name = input()
print("Hello !"+" "+ name)
print("Ok !"+" "+ name +" "+ "let\'s start !")
print("What is"+ " " + str(firstNumber) +"+"+ str(secondNumber))
userAnswer = int(input("Your answer : "))
while (userAnswer != result) :
if (userAnswer > result) :
print("Wrong")
else:
print("Wrong")
userAnswer = int(input("Your answer : "))
if (userAnswer == result):
print("Correct")
print("Good Job!")
break
input("\n\n Press to exit")
The problem is that your while-loop will only run as long as the first answer is wrong. Everything that is indented after while (userAnswer != result) will be ignored by Python if the first answer is right. So logically a first correct answer can never reach print("Correct"), since that would require the answer to be both wrong (to start the while loop) and right (to get to "Correct").
One option is to get rid of the while-loop, and just use if's. You get two chances this way, then you lose.
if (userAnswer == result):
print("Well done!")
else:
print("Wrong")
userAnswer = int(input("Your answer : "))
if (userAnswer == result):
print("Correct")
print("Good Job!")
else:
print("Nope all wrong you lose")
Another option is to make an infinite loop using While. (like #csharpcoder said)
while (True) :
userAnswer = int(input("Your answer : "))
if (userAnswer == result):
print("Correct")
print("Good Job!")
break
else:
print ("Wrong answer")
In the last option a wrong answer gets "Wrong answer" and the while-loop starts again, since True is of course still True. So you try again, until you get the right answer, which will bring you to "correct, good job" and then break (which stops the loop).
I struggled with while-loops and kind of getting it in my head that indentation means Python will treat it as 'one thing' and skip it all if I start it with something that's False.
If the answer is correct, then
while (userAnswer != result) :
will cause the loop contents to be skipped.
First of all, you get input outside of your loop and then don't do anything with it. If your answer is correct on the first try, you will get no output because userAnswer != result will be False immediately and your while loop won't run.
Some other points:
if (userAnswer > result) :
print("Wrong")
else:
print("Wrong")
is redundant because you are guaranteed to fall into one of these, as you will only get here if the answer is wrong (and therefore > or < result). Just print "Wrong" without a condition, as the only reason this would run is if the answer was wrong.
print("Correct")
print("Good Job!")
You can use \n to print on a new line instead of having multiple print statements together. Usually you only use multiple prints together for readability, but print("Correct\nGood job!") isn't that much less readable.
if (userAnswer == result):
#...
break
You don't need break here because the answer is already correct and the loop won't repeat anyway.
print("Hello !"+" "+ name)
print("Ok !"+" "+ name +" "+ "let\'s start !")
print("What is"+ " " + str(firstNumber) +"+"+ str(secondNumber))
Here, you append string literals to string literals ("Hello!" + " "). You don't need to do that as you can just write "Hello! ".
result = firstNumber + secondNumber
result = int(result)
The result (pun not intended) is already an integer, so you don't need to convert it.
How about using a infinite while loop something like this :
while (True) :
userAnswer = int(input("Your answer : "))
if (userAnswer == result):
print("Correct")
print("Good Job!")
break
else:
print ("Wrong answer")
In your logic if you enter the wrong answer first time and correct answer afterwards , then it will work as per your requirement , but if you enter the correct answer first time it will simple skip the while loop .
I played around a bit to refactor, in an attempt to make it more clear:
import random
name = input("Hello ! What's your name? ")
print("Hello, {name}!".format(name=name))
print("Ok, {name}, let's start!".format(name=name))
first_number = random.randint(1, 50)
second_number = random.randint(1, 50)
correct_answer = first_number + second_number
print("What is, '{first} + {second}'?".format(first=first_number,
second=second_number))
user_answer = None
while user_answer != correct_answer:
try:
user_answer = int(input("Your answer : ")) # ValueError will be raised if non integer value given
except ValueError:
print("Invalid Input!")
user_answer = None
if user_answer:
if user_answer == correct_answer:
print("Correct")
print("Good Job!")
else:
print('--> Wrong, try again!')
input("\n<< Press any key to exit >>")
if op == '+':
left1 = random.randint(1,100)
right1 = random.randint(1,100)
print ("What is " + (str(left1) + op + str(right1) + "?"))
answer = eval(str(left1) + op + str(right1))
guess = int(input(""))
if guess == answer:
print("Correct!")
score + 1
elif guess != answer:
print("Incorrect")
else:
except ValueError:
print("Expected integer")
I tried except ValueError, but it stated that it was invalid syntax. I'm trying to get the code to force the user to enter an integer for the answer, if they don't then it tells them that they are supposed to enter an integer.
ValueError is not a function; it is a class (an Exception subclass).
You need to use except as part of a try statement, it cannot be used on its own; you need to put any code you want 'protected' inside the try:
if op == '+':
left1 = random.randint(1,100)
right1 = random.randint(1,100)
print ("What is " + (str(left1) + op + str(right1) + "?"))
answer = eval(str(left1) + op + str(right1))
try:
guess = int(input(""))
except ValueError:
print("Expected integer")
else:
if guess == answer:
print("Correct!")
score = score + 1 # don't forget to *store* the sum!
else:
print("Incorrect")
You probably want to read the canonical Stack Overflow question on user input in Python to learn more about this: Asking the user for input until they give a valid response, as well as the section on handling exceptions in the Python tutorial.