I am doing a simple program just to the program say if a number is even or not and to when the raw_input isn't a number, the program will complain about it:
def f():
t = raw_input('Enter a number and we will send an inormation: ')
if t != type(int):
print 'is this a number?'
elif int(t) % 2 == 0:
print t
print 'it is an even number'
elif int(t) % 2 > 0:
print t
print 'it is an odd number'
else:
print '???'
but when the program run it returns ONLY the if condition (when i write 90 or a word it returns 'is this a number?'. it should only return this if I Write a string). And I can't figure out where is the problem.
Many errors here.
First, use isintance to test if a variable is an int. Do not use type(t) != int.
Then you do the int(t) operation multiple times.
In addition, it seems that t is a global var, which is not recommended to use, especially for beginners.
Last you have a else at the end but a number is odd or even. There is no other alternatives. To test is a number is odd use if t & 1:.
You can use if t.isdigit():
type(int) returns the type of the object which will never be a value. So it will always be false.
This is caused by the fact that raw_input always returns a string, even if there is only numbers used. You need to type cast it as int and then check if it is odd or even, and catch an exception if it is not able to be converted to int. This is how you should do it:
def f():
try:
t = int(raw_input("Enter a number"))
except ValueError:
print "is this an integer?"
else:
if t % 2 == 0:
print t
print " is even"
else:
print t
print " is odd"
The else after the except block only runs if the exception is not thrown. Also, as #Julien Goupy says, the number is either odd or even, so you don't need the third else statement
Edit: It seems that elif after the try...except block does not work, so I have changed it to else
Related
For an assignment for class, I am needing to create a program that returns if a number is even or odd, while having the main function get user input and displays the output, while another function checks whether the number is even or odd. My python knowledge so far is very basic.
Here is what I've got so far.
def check(number):
if (number % 2) == 0:
return True
else:
return False
def main():
number = int(input("Enter an integer: "))
if check is True:
print("This is an even number.")
elif check is False:
print("This is an odd number.")
__name__ == "__main__"
main()
When I run the code, I get the input prompt, but nothing in return after.
check is a function, so it should be like
if check(number):
print("This is an even number.")
else:
print("This is an odd number.")
Python is very flexible, you don't even need a function.
I would take advantage of f-strings and a ternary:
number = int(input("Enter an integer: "))
print(f'This is an {"odd" if (number % 2) else "even"} number')
Example:
Enter an integer: 2
This is an even number
Enter an integer: 3
This is an odd number
As you are basic this is not the best function for check using bool.
def check(num):
return num % 2 == 0 # return True if even otherwise odd
This code is simple and easily to read rapidly.
I am a new learner for Python. I have a question about while loop.
I wrote a program below to look for square roots.
When I input anything but integers, the message "is not an integer" shows up and it repeats itself until I input correct data(integers).
My question is, why does it end loop when it return value on line 5, return(int(val))?
Thank you for your attention.
def readInt():
while True:
val = input('Enter an integer: ')
try:
return(int(val))
except ValueError:
print(val, "is not an integer")
g = readInt()
print("The square of the number you entered is", g**2)
To answer your original question, 'return' effectively exits the loop and provide the result that follows the 'return' statement, but you have to explicity print it like so:
def read_int(num1, num2):
while True:
return num1 + num2
print(read_int(12, 15))
If you simply put 'read_int(12, 14)' instead of 'print(read_int(12, 15))' in this scenario, you won't print anything but you will exit the loop.
If you allow me, here are some modifications to your original code:
def read_int(): # functions must be lowercase (Python convention)
while True:
val = input('Enter an integer: ')
try:
val = int(val) # converts the value entered to an integer
minimum_value = 0 # There is no need to evaluate a negative number as it will be positive anyway
maximum_value = 1000000 # Also, a number above 1 million would be pretty big
if minimum_value <= val <= maximum_value:
result = val ** 2
print(f'The square of the number you entered is {result}.')
# This print statement is equivalent to the following:
# print('The square of the number you entered is {}.'.format(result))
break # exits the loop: else you input an integer forever.
else:
print(f'Value must be between {minimum_value} and {maximum_value}.')
except ValueError: # If input is not an integer, print this message and go back to the beginning of the loop.
print(val, 'is not an integer.')
# There must be 2 blank lines before and after a function block
read_int()
With the final 'print' that you actually have at the end of your code, entering a string of text in the program generates an error. Now it doesn't ;). Hope this is useful in some way. Have a great day!
I'm very new to python, in fact, to programming in general. I'm trying to do a program that compares three numbers and determines which one is smaller. I got the code done, but now i need to make it only accept numbers, and still running when it finds a literal value. For example, code will be ok if you put any number, but when you type a string value it crashes. here is the code
num1=0;
num2=0;
num3=0;
num1=int((raw_input("Type below the first number \n")));
num2=int((raw_input("Type below the second number\n")));
num3=int((raw_input("Type below the third number \n")));
if (num1<num2) and (num1<num3):
print "%i is the smallest number of all three"% num1;
elif (num2<num1) and (num2<num3):
print "%i is the smallest number of all three"% num2;
elif (num3<num2) and (num3<num1):
print "%i is the smallest number of all three"% num3;
elif (num1==num2) or (num1==num3) or (num2==num3):
print "Two equal numbers have been written.";
A simple while loop. You may put this in a function.
while True:
try:
num1=int((raw_input("Type below the first number \n")))
break
except ValueError: # catch the *specific* exception
print("Enter numbers only")
Read more on exceptions:
Handling Exceptions in Python
The most important point is probably to separate concerns, ie. keeping user input separate from validation. You've gotten a couple of good solutions using exceptions. Here is a solution that manually validates the input:
def is_int(strval):
"""A string represents an int if all characters are digits.
Returns True if strval represents a valid int, otherwise False.
"""
for ch in strval:
if not ch.isdigit(): # if '0' <= ch <= '9':
return False
return True
def read_int(prompt='Type number: '):
"""Read one integer from user.
"""
while True:
val = raw_input(prompt)
if is_int(val):
return int(val, 10) # the 10 is the radix (base)
else:
print 'That is not a number.., try again'
numbers = []
for pos in 'first', 'second', 'third':
numbers.append(read_int('Type %s number: ' % pos))
to use the exception handling code, all you have to do is change is_int:
def is_int(strval):
try:
int(strval, 10)
except ValueError:
# int() raised an exception, so strval is not an int
return False
else:
# int() didn't raise an exception, so it is an int
return True
it is also possible to be a bit more concise when finding the smallest:
def smallest(a, b, c):
if b > a < c: # if a is less than both b and c..
return a
if a > b < c:
return b
if a > c < b:
return c
return "Error: two of the numbers must be equal!"
you can call it like so:
smallest(numbers[0], numbers[1], numbers[2])
but Python has a shorthand that does exactly that which looks like:
smallest(*numbers)
def getNumber(i):
try:
num = int(raw_input("type in number %s : " %i))
return num
except Exception as e:
print('This is not a valid number')
return getNumber(i)
numbers = []
for i in range(1,4):
numbers.append(getNumber(i))
print(numbers)
You can simply add the input getting code in try except block and handle the ValueError exception with some meaningful code.
try:
num1=int((raw_input("Type below the first number \n")));
num2=int((raw_input("Type below the second number\n")));
num3=int((raw_input("Type below the third number \n")));
except ValueError:
print "Please enter integer only."
exit(-1)
I'm having a problem with some coding that I'm doing for a school assignment, the same thing happened and I managed to fix it but I did so without knowing how I did it.
def number():
num = input("please enter the number of people that would like play:")
try:
if int(num) >= 2:
if int(num) <=7:
return num
else:
print("number must be 7 or less")
number()
else:
print("number must be greater than 2")
number()
except:
print("that is not a valid number. number must be between 2 and 7")
number()
number = number()
print(number,"people are playing")
This is the code which is causing the problem. If I enter an invalid number it works fine, I can just re-enter a new number, but as you can see I have wanted to print out the "number of people playing" but it returns with "none people are playing" but this is only after I have entered an invalid number. What can I do?
In the ideal case, without any errors, number() returns the entered num and all is well. However, in all other cases, you end the function with a recursive call to number() without actually returning anything. So the function implicitly returns None (i.e. nothing).
Just change every recursive call to return number() and it should work.
Btw. you should avoid recursion for this; see this answer on how to best ask the user repeatedly for valid input.
You need to use a loop rather than calling your routine again which will not have the effect you are looking for (look into recursion). Something like the following approach would be better:
def number():
while True:
num = input("please enter the number of people that would like play: ")
try:
num = int(num)
if num > 7:
print("number must be 7 or less")
elif num <= 2:
print("number must be greater than 2")
else:
return num
except:
print("that is not a valid number. number must be between 2 and 7")
number = number()
print(number, "people are playing")
The reason you are seeing None is that it is possible to reach the bottom of your function without a return being used. In this case Python defaults the returned value to None.
Question 1:
Just tried to execute the program but i am getting syntax error
i=input('Enter the value of i')
for j in range(10):
if i==j:
print'The value of i is %d'%(i)
elif i!=j:
print'Please enter a valid value'
else:
print 'This is not a number'
The difference between the below two codes is that code one will ask for input once and then loop trying to compare, while code two will ask for input each loop (10x)...
If your code is really indented as you put it here, the reason you are getting a syntax error is that your elif and else blocks are indented too far. Another problem with your code is that i can be either equal or not equal to j. There is no third option. Another problem is that the first time it comes across a number that is not equal to the number typed, it will say that it is not a valid value. Also, just saying "Please enter a valid value" will not make it so. Here is a better version of your code:
i = None
while True:
i = input("Enter the value of i")
if i.isdigit():
if int(i) in range(10):
print "The value of i is %d" % i
else:
print "Please enter a valid value"
else:
print "This is not a number"
As for question 2, the difference between the two is that in the first, i=input('Enter the value of i') will be executed before the loop, and in the second it will be executed for each iteration of the loop. (That is, one time for each time the loop is executed. Because range(10) returns ten items, it runs ten times.) More about for loops here, here, and here
You appear to be having a syntax error because of inconsistent levels of indentation in your code. Please try the following instead and adjust the program to suit whatever your needs might be.
#! /usr/bin/env python3
import sys
def main():
loop = True
while loop:
try:
i = int(input('Enter of the value of i: '))
except EOFError:
sys.exit()
except ValueError:
print('This is not a number')
else:
if 0 <= i <= 9:
print('The value of i is', i)
loop = False
else:
print('Please enter a valid value')
if __name__ == '__main__':
main()