+ 1
How do I enter numeric and string values in this code?
I need the program to terminate when entering the word - exit. But how can this be done? ############## import random i = 0 y = random.randrange(0, 99) while i < 1: x = int(input('Number: ')) if x == y: print('You Won! Number = ', y) i = i + 1 elif x > y: print('Lower') elif x < y: print('Upper')
4 Respuestas
+ 5
To allow the user to enter both numeric and string values in this code, you can use a try-except block to handle the input.
https://code.sololearn.com/cNNbVKypF2dd/?ref=app
+ 4
Your input converts the value into an int. Maybe you should check at that stage if the string is equal to exit and if not, convert to int.
+ 2
Sadaam Linux Kishor Ramanan Pls avoid giving finished code as answer, because it makes the OP to skip the most important part of learning. Prefer giving hints for the OP to find the solution.
BTW, Sadaam, a try-except block can do, but is not a good choice - exceptions are meant to handle real problems. A better way is just testing if the input is a numeric string. str class has a method which does it.
0
You can do something like this
import random
i = 0
y = random.randrange(0, 99)
while i < 1:
x = input('Number: ')
if x.isdigit():
x = int(x)
if x == y:
print('You Won! Number = ', y)
i = i + 1
elif x > y:
print('Lower')
elif x < y:
print('Upper')
elif x.lower() == "end":
exit()
else:
print("Invalid input")