python: raw_input function back to top again - python

I have a raw_function looks like:
number = raw_input('number (empty to finish): ')
if len(number) == 0:
print
print
print 'finished'
print
print
return def()
else:
pass
while True:
try:
column2 = int(raw_input('Enter column: '))
break
except ValueError:
print 'You did not supply an integer. Please try again. '
When i finish answering my second raw_input, I would like to return to first raw_input.
How can I do this?
Thanks in advance.

while True:
number = raw_input('number (empty to finish): ')
if not number:
print "\n\nfinished\n\n\n"
return def()
while True:
try:
column2 = int(raw_input('Enter column: '))
break
except ValueError:
print 'You did not supply an integer. Please try again. '

Related

I have a problem with elif statement and else statement and dictionary in python

The Code
men = {1111111111: 'Amal', 2222222222: 'Mohammed', 3333333333: 'Khadijah', 4444444444: 'Abdullah', 5555555555: 'Rawan',
6666666666: 'Faisal', 7777777777: 'Layla'}
def mo():
r1 = input('Please Enter The Number: ')
r = int(r1)
if r in men:
print(men[r])
elif len(str(r)) > 10:
print('This is invalid number')
elif len(str(r)) < 10:
print('This is invalid number')
elif r not in men:
print('Sorry, the number is not found')
else:
print('This is invalid number')
what I want is that the console print 'This is invalid number' if i have entered any data type in the console except integer but error show up in the console page
OutPut
Please Enter The Number: d
Traceback (most recent call last):
File "C:\Users\walee\PycharmProjects\pythonProject\main.py", line 19, in <module>
mo()
File "C:\Users\walee\PycharmProjects\pythonProject\main.py", line 7, in mo
r = int(r1)
ValueError: invalid literal for int() with base 10: 'd'
Process finished with exit code 1
first screenshot
second screenshot
You can use a try catch block here to catch the errors. You will either want to get a different user input if it is invalid, or just exit the program.
try:
r = int(r1)
except:
print("This is invalid number")
I would use str.isdigit() to do this. This function returns a boolean which is True when the string is made only out of numbers and False otherwise. Here's the code:
def mo():
r1 = input('Please Enter The Number: ')
if not r1.isdigit():
print("This is invalid number")
else:
r = int(r1)
if r in men:
print(men[r])
elif len(str(r)) > 10:
print('This is invalid number')
elif len(str(r)) < 10:
print('This is invalid number')
elif r not in men:
print('Sorry, the number is not found')
else:
print('This is invalid number')
So, first check whether the input is a number. If it isn't, print that the input is invalid and stop excuting the code, in order to prevent the program from crashing anyway. If it is a number, continue with the rest of the code.
However, I noticed that your code can be simplified into the following:
def mo():
r1 = input('Please Enter The Number: ')
if not r1.isdigit() or len(r1)!=10:
print('This is invalid number')
else:
r = int(r1)
if r in men:
print(men[r])
else:
print('Sorry, the number is not found')
This code works in the following way:
First, it checks whether the input is a number and its length is equal to 10 ( or, its length is not bigger and not smaller than 10). Then it converts the input into a number and checks whether the number is in the dictionary.
Wrap the input statement in a while True loop. Break out of the loop if they enter a number.
while True:
r1 = input("Enter the number: ")
if r1.isdigit():
break
else:
print("Invalid number, please try again")
r1 = int(r1)
# ... continue with rest of the code

How can I start over from middle of the program if the input goes wrong

# nested loop # finding the large number.
system = 1
while system:
number1 = input('1st value: ')
try:
int(number1)
except ValueError:
try:
float(number1)
except ValueError:
print('Error: This is not a Number. Try again')
break
number2 = input('2nd value: ')
try:
int(number2)
except ValueError:
try:
float(number2)
except ValueError:
print('Error: This is not a Number. Try again')
break
number3 = input('3rd value: ')
try:
int(number3)
except ValueError:
try:
float(number3)
except ValueError:
print('Error: This is not a Number. Try again')
break
number4 = input('4th value: ')
try:
int(number4)
except ValueError:
try:
float(number4)
except ValueError:
print('Error: This is not a Number. Try again')
break
list = [float(number1), float(number2), float(number3), float(number4)]
large_number = list[0]
total = 0
small_number = list[0]
# we assumed that the largest number is the first one on the "list" variable
for line_value in list:
if line_value > large_number:
large_number = line_value
print(f'the largest number of the list is:{large_number}')
for line_value in list:
if line_value < small_number:
small_number = line_value
print(f'the smallest number is: {small_number}')
for line_value in list:
total += line_value
print(f'and the sum is: {total}')
break
I was practicing and it came here. Now I want to restart everything following by a error massage when ever the user enters a character other then number. Now the error massage is showing, but as I failed to restart it after the massage I just broke the loop.. please help me. I am just 3 days old in any type of coding.
You should never repeat code, what you can do is write a function which gets the number for you:
def get_number(x):
n = input (f"Enter the {x} value: ")
try: return float(n)
except ValueError: return get_number(x) #this will call the function each time the error would be raised
while True: #You can just use while True: instead of declaring a variable just for that
number1 = get_number("1st")
number2 = get_number("2nd")
number3 = get_number("3rd")
number4 = get_number("4th")
list = [number1, number2, number3, number4] #From here on the code stays unchanged

Better way to ask user input in integer form in Python?

So I'm kind of very beginner to programming and just learning yet the basics. Now I would like to have my python program to ask the user to give a number and keep asking with a loop if string or something else is given instead.
So this is the best I came out with:
value = False
while value == False:
a = input("Give a number: ")
b = 0
c = b
try:
int(a)
except ValueError:
print("No way")
b += 1
if c == b:
value = True
So is there easier and better way to do this?
You can use this:
while True:
try:
a = int(input("Give a number: "))
break
except ValueError:
print("No way")
or this:
while True:
a = input("Give a number: ")
if a.isdigit():
break
print("No way")
while True:
try:
a = int(input("Give a number: "))
break
except ValueError:
print("No way")
continue
This will continue to prompt the user for an integer till they give one.
value = True
while value == True:
a = input("Give a number: ")
try:
int(a)
except ValueError:
print("No way")
continue
print("Yay a Number:", a)
value = False
Is this what you need?

How can my code only accept integers in Python?

My code distinguishes whether the input is valid or not. It's not supposed to accept zero or words. If the user plugs zero in, it works and says "anything but zero", "try again" BUT when it asks again, it accepts anything. What do I do to make it continue to ask until there is a valid input??
So far I got:
A = raw_input('Enter A: ')
try:
A = float(A)
if A == 0:
print "anything but zero"
A = raw_input("Try again")
except ValueError:
print "HEY! that is not a float!"
A = raw_input("Try again")
Please help! Thank you all!
You need to use a loop:
while True:
A = raw_input('Enter A:')
try:
A = float(A)
except ValueError:
print "enter a float!"
else:
if A == 0:
print "Enter not 0"
else:
break
The simplest approach is use a while loop and to move all the logic inside the try breaking if the cast is successful and not equal to 0:
while True:
try:
A = float(raw_input('Enter A: '))
if A != 0:
break
print "anything but zero"
except ValueError:
print "HEY! that is not a float!"
If you actually only want integers you should be casting to int not float.
Use a while loop:
valid = false
while not valid:
A = raw_input('Enter A: ')
try:
A = float(A)
if A == 0:
print "anything but zero"
A = raw_input("Try again")
else:
valid = true
except ValueError:
print "HEY! that is not a float!"
A = raw_input("Try again")
Hope this helps :)
while 1==1:
A = raw_input('Enter A: ')
try:
A = float(A)
if A == 0:
print "anything but zero"
A = raw_input("Try again")
else:
#valid input
break
except ValueError:
print "HEY! that is not a float!"

Why doesn't my code enter a loop?

def is_number(s):
try:
float(s)
return True
except ValueError:
return False
flag = True
while flag != False:
numInput = raw_input("Enter your first number: ")
if is_number(numInput):
numInput = float(numInput)
flag = True
break
else:
print "Error, only numbers are allowed"
I do not see the problem.
Why doesn't it enter a loop?
Doesn't print anything, just gets stuck.
flag = False is not required here:
else:
print "Error, only numbers are allowed"
flag = False <--- remove this
Simply use:
while True:
numInput = raw_input("Enter your first number: ")
if is_number(numInput):
numInput = float(numInput)
break
else:
print "Error, only numbers are allowed"
demo:
Enter your first number: foo
Error, only numbers are allowed
Enter your first number: bar
Error, only numbers are allowed
Enter your first number: 123
try this:
while True:
numInput = raw_input("Enter your first number: ")
try:
numInput = float(numInput)
break
except:
print "Error, only numbers are allowed"

Categories