Hi guy’s I’m trying to write a python program here and I’m just learning at the moment. what I’m trying to do is get the user to enter a 6 digit number and if they enter a number which is not 6 digits I want an error message to come us stating they must enter a 6 digit number. I have a function called def example_check_message(m): where I have stated that the number must be 6 digits and I have a function called def example_get_number(): when the user enters the number the get number function should call the def example_check_message(m) function to check the number being entered is correct but nothing is happening. I know I’m close to it but just can’t see where I’m going wrong.
def example_check_message(m):
b = False,
try:
if m == int >= '100000' and '<1000000':
b = True
except:
print 'You must enter a number'
return b
def example_get_number():
example_check_message(1)
b = False
while b == False:
num = raw_input('Please enter a 6 digit number:')
if example_check_message(num) == True:
b = True
continue
value = int(num)
return value
if __name__ == '__main__':
example_check_message(1)
example_get_number()
I think you want something like:
def example_check_message(m):
try:
m = int(m)
if m >= 100000 and m < 1000000:
return m # <- return something useful!
except:
print 'You must enter a number'
return False
but there are errors in this - ill give you some hint where. this shouldn't work as-is, you'll still need to do some work and learning.
def example_get_number():
example_check_message(1)
b = False
while b == False: # not b is the right way here
num = raw_input('Please enter a 6 digit number:')
if example_check_message(num) == True: # This could be simpler
b = True
continue # <- no need to continue here, just return
value = int(num) # <- do this already on the input!
return value
Related
I need to make a function to make that will give me an angle classification like acute right or obtuse and I need it to loop until the user wants to exit the function:
this is my code so far:
side_a = float(input('Enter length of side a: '))
side_b = float(input('Enter length of side b: '))
side_c = float(input('Enter length of side c: '))
def is_valid_triangle(a,b,c):
if a+b>=c and b+c>=a and c+a>=b:
return True
else:
return False
# Function definition for type of triangle
def type_of_triangle(a,b,c):
if a==b and b==c:
print('Triangle is Equilateral.')
elif a==b or b==c or a==c:
print('Triangle is Isosceles.')
else:
print('Triangle is Scalane')
return False
if is_valid_triangle(side_a, side_b, side_c):
type_of_triangle(side_a, side_b, side_c)
else:
print('Tringle is not possible from given sides.')
def triangle_angle (a, b, c, ) :
a = int(input ("enter side a: "))
b = int(input("enter side b : "))
c = int(input("enter side c : "))
I'm assuming you want to know how to constantly loop code.
You can use:
try:
while True:
pass # replace with whatever code you want to run
except KeyboardInterrupt:
print('Exiting...')
Which will constantly loop until the user presses Ctrl+C.
I think this answers your question.
Hi I am trying to check if the user has put in a letter and then let them know it is a letter and they need to put in a number.
it keeps giving me a error whenever this happens, I understand it may be because I am trying to convert a int to a string but I am at a lose to trying to figure this out.
I thought the below code would check to see if its a number input and fail it or pass it depending on what they put. however it doesn't seem to work.
is there anyway around this.
def weapons_(numguns,numknifes,numbombs,numswords):
print(numguns)
aaa = int(str(input("""Enter you're number accordinly to the list above:""")))
while True:
try:
number = int(aaa)
print("this is a num, thank you")
break
except ValueError:
print("this is not a number, please try again")
if aaa <= 50:
print (x)
elif aaa <= 100:
print (y)
elif 101 <= 150:
print (m + p)
elif 151 <= 200:
print (z)
weapons_("numguns","numknifes","numbombs","numswords")
Try this function:
def isNum (var):
flag = True
while (flag):
try:
val = int(var)
flag = False
except ValueError:
var = input("No.. input is not a number! Please enter a number: ")
return int(var)
It keeps asking for a number until the input value is an int. It finally returns the value as output.
Here is a sample screenshot of the output:
sample
Try this code. I put the variables x, y, m, p, z into quotes since they were not defined.
Since you've casted aaa into a number, You should not use aaa anymore to compare with (50, 100, etc.) but the variable number instead. In addition, if the cast fails, the code will show the exception message and ask the use for a new number.
while True:
try:
aaa = input("""Enter you're number accordinly to the list above:""")
number = int(aaa)
print("this is a num, thank you")
if number <= 50:
print ("x")
elif number <= 100:
print ("y")
elif 101 <= 150:
print ("m + p")
elif 151 <= 200:
print ("z")
break
except ValueError:
print("this is not a number, please try again")
Try using regex
import re
def checkInt(string):
ex = re.compile(r'[1-9][0-9]*')
return bool(ex.match(string))
You can use this function like this
aaa = input("""Enter you're number accordinly to the list above:""")
if checkInt(aaa): aaa = int(aaa)
else:
print('Not a Integer')
exit()
# the code you posted on the question
I have this assignment to create a program that asks user to input any positive integer repeatedly or type anything else to end and generate the sum, count and average of the numbers. My teacher wants all the code in these this structure with these three def’s only
This is the code I have, any suggestions on how to get it to work?
def calcAverage(total,count):
sum = 0
count = 0
average = sum / count
def inputNumber(message):
while True:
try:
userInput = int(input(message))
count = count + 1
sum = sum + entry
if userInput < 0:
raise ValueError
except ValueError:
main()
else:
return userInput
break
entry = inputNumber('Type any positive integer, anything else to quit')
def main():
print('Sum')
print(sum)
print('Average')
print(average)
print('Total Numbers')
print(count)
The question is not well explained + we don't really get what the boundaries are. Moreover, you should clearly state what is not working. Now, to give you some hint, this is how I would do it:
input = None
L = list()
while True:
try:
input = int(input('Type any positive integer, anything else to quit: '))
if input < 0:
break
else:
L.append(input)
except:
break
S = sum(L)
I think you don't need to use exceptions here. Condition statements would make it clearer.
I would put the valid inputs in a list until the user make a invalid input. When it happens, just get out of your while loop using a break statement and return the result.
I want to write a program with this logic.
A value is presented of the user.
Commence a loop
Wait for user input
If the user enters the displayed value less 13 then
Display the value entered by the user and go to top of loop.
Otherwise exit the loop
You just need two while loops. One that keeps the main program going forever, and another that breaks and resets the value of a once an answer is wrong.
while True:
a = 2363
not_wrong = True
while not_wrong:
their_response = int(raw_input("What is the value of {} - 13?".format(a)))
if their_response == (a - 13):
a = a -13
else:
not_wrong = False
Although you're supposed to show your attempt at coding towards a solution and posting when you encounter a problem, you could do something like the following:
a = 2363
b = 13
while True:
try:
c = int(input('Subtract {0} from {1}: '.format(b, a))
except ValueError:
print('Please enter an integer.')
continue
if a-b == c:
a = a-b
else:
print('Incorrect. Restarting...')
a = 2363
# break
(use raw_input instead of input if you're using Python2)
This creates an infinite loop that will try to convert the input into an integer (or print a statement pleading for the correct input type), and then use logic to check if a-b == c. If so, we set the value of a to this new value a-b. Otherwise, we restart the loop. You can uncomment the break command if you don't want an infinite loop.
Your logic is correct, might want to look into while loop, and input. While loops keeps going until a condition is met:
while (condition):
# will keep doing something here until condition is met
Example of while loop:
x = 10
while x >= 0:
x -= 1
print(x)
This will print x until it hits 0 so the output would be 9 8 7 6 5 4 3 2 1 0 in new lines on console.
input allows the user to enter stuff from console:
x = input("Enter your answer: ")
This will prompt the user to "Enter your answer: " and store what ever value user enter into the variable x. (Variable meaning like a container or a box)
Put it all together and you get something like:
a = 2363 #change to what you want to start with
b = 13 #change to minus from a
while a-b > 0: #keeps going until if a-b is a negative number
print("%d - %d = ?" %(a, b)) #asks the question
user_input = int(input("Enter your answer: ")) #gets a user input and change it from string type to int type so we can compare it
if (a-b) == user_input: #compares the answer to our answer
print("Correct answer!")
a -= b #changes a to be new value
else:
print("Wrong answer")
print("All done!")
Now this program stops at a = 7 because I don't know if you wanted to keep going with negative number. If you do just edited the condition of the while loop. I'm sure you can manage that.
I am trying to return the number if it is an INT and between numbers, an error occurs when you enter a letter . also you have to input the correct value twice to get an input:
def get_number():
b = False
while b == False:
try:
n = (input('Please enter a 6 digit number'))
except ValueError:
continue
if n >= 100000 and n <= 1000000:
b = True
break
return n
if __name__ == '__main__':
get_number()
print get_number()
`
Changed input to raw_input , it now work if someone enters a letter. however when i enter the correct input ,it will keep on looping:
def get_number():
b = False
while b == False:
try:
n = (raw_input('Please enter a 6 digit number'))
except ValueError:
continue
if n >= 100000 and n <= 1000000:
b = True
break
return n
if __name__ == '__main__':
get_number()
print get_number()
There are a few problems with your code.
you could just use input to evaluate whatever the unser entered, but that's dangerous; better use raw_input to get a string and try to cast that string to int explicitly
also, if you are using input, then you'd have to catch NameError and SyntaxError (and maybe some more) instead of ValueError
currently, your if condition would allow a 7-digit number (1000000) to be entered; also, you can simplify the condition using comparison chaining
no need for the boolean variable; just break or return from the loop
you call your function twice, and print only the result of the second call
You could try something like this:
def get_number():
while True:
try:
n = int(raw_input('Please enter a 6 digit number '))
if 100000 <= n < 1000000:
return n
except ValueError:
continue
if __name__ == '__main__':
print get_number()