Edit: This post differs from Asking the user for input until they give a valid response because I do not end the loop based on data type of the response. Both strings and integers are valid. The loop should only kick-back if the two entries are different data types.
I'm trying to collect either two words, or two integers via input(). If both values are integers I want to calculate answer1**answer2.
If both are non-integers, I want to concatenate the strings. Finally, if the data-types do not match, I want to send the user to the beginning to enter two new values.
Here's my attempt. I apologize in advance for what you're about to see.
## collect first value
print("Please type a word or an integer:")
answer1 = input()
## check for blanks
if answer1 == "":
print("Blank space detected. Please retry.")
answer1 = input()
## collect second value
print("Please type another word or integer:")
answer2 = input()
## check for blanks
if answer2 == "":
print("Blank space detected. Please retry.")
answer2 = input()
## define test for integer status
def containsInt(intTest):
try:
int(intTest)
return True
except ValueError:
pass
## check for matching data types and produce final value
if containsInt(answer1) == True:
containsInt(answer2)
if containsInt(answer2) == True:
finalInt = (int(answer1))**(int(answer2))
print("\n")
print(finalInt)
else:
print("Sorry, the data types must match - both words or integers.")
continue
else:
containsInt(answer2)
if containsInt(answer2) !=True:
print("\n")
print(answer1 + answer2)
else:
print("Sorry, the data types must match - both words or integers.")
continue
I tried to use "continue" to get it to go back to the beginning, but it becomes angry at me. You can probably tell I'm a complete newb, and this is my first post. Please don't rip on me too hard. :(
This should work:
while True:
answer1 = input("Please type a word or an integer:")
# check for blanks
while answer1 == "":
answer1 = input("Blank space detected. Please retry.")
try:
answer1 = int(answer1)
except ValueError:
pass
answer2 = input("Please type another word or integer:")
# check for blanks
while answer2 == "":
answer2 = input("Blank space detected. Please retry.")
try:
answer2 = int(answer2)
except ValueError:
pass
if type(answer1) == type(answer2):
if type(answer1) == str:
print(answer1 + answer2)
break
elif type(answer1) == int:
print(answer1**answer2)
break
else:
print(f"Sorry, the data types of '{answer1}' and '{answer2}' do not match.")
continue
Do note that if you input a number like 1.5
it will be treated as a string.
so the inputs 1.5
and a
will result in 1.5a