Why following code doesn't run an exception for negative inputs? - python-2.7

I want to write a simple code when user enters his age, it will give in how many years user will be 100 years. But I have assigned an exception if the user enters a negative number to give a value error. But the code runs regardless even if I enter a negative number without raising an exception. Why is that? Thanks! I'm using python 2.7
try:
age = raw_input("Please enter your age: ")
if age < 0:
raise ValueError ('%d is not a positive number' )
except ValueError as err:
print ("You've entered an incorrect age input %s" %err)
else:
print("You will be 100 in %d" % (100 - int(age)))

raw_input returns a string, so age is a string containing whatever you put - "-3" for example. Not an integer.
When comparing an integer to a string, "-3" < 0, the integer always "comes first" (is smaller than the string), just as an implementation detail, so your if will always be False. Cast to an int, the ValueError will already catch an invalid cast:
age = int(raw_input("Please enter your age: "))

Related

Python readability

Greetings stackoverflow,
I am pretty new to both this website and python.
I wrote a simple program to create a list of devisors based on a user inputted number, the program works (as far as I know)
But I am pretty sure my syntax is extremely amateurish, so I ask the fluent among you, what can I do to make this:
divisors = []
def devisors(x):
while True:
try:
for i in range(1,x+1):
if x%i==0:
divisors.append(i)
if x==i:
break
except ValueError, TypeError:
return "Invalid input."
continue
print "The list of divisors of",x,"Are: ", divisors
choice1= raw_input("Would you like to use devisors program?(Y/N): ")
while True:
try:
if choice1 in yes:
x = int(raw_input("Please enter a number: "))
devisors(x)
elif choice1 in no:
print "Alright, bye bye."
break
else:
print "invalid input"
choice1= raw_input("Would you like to use devisors program(Y/N): ")
continue
except ValueError, TypeError:
print "Invalid input, try again."
try:
choice2= raw_input("Would you like to try again?(Y/N): ")
if choice2 in yes:
divisors = []
continue
devisors(x)
elif choice2 in no:
print "Alright, bye bye. "
break
else:
print "invalid input"
choice2= raw_input("Would you like to try again?(Y/N): ")
continue
except ValueError, TypeError:
print "Invalid input, try again."
Better written?
I want you to go berserk on this code, tell me (If you feel like it) what could be done to improve it, to write less lines, and mistakes I made.
Also I am not sure if this is something allowed on stackoverflow, if not, please let me know and I'll delete this.
Thank you.
Looking forward to the feedback.
First of all, we do have a dedicated Stack Exchange Code Review site, but you're not the only one asking for a code review here.
The first thing I noticed is that you are trying to hard to put everything in a single method.
Whenever you are faced with a problem or task you should try to divide it into the smallest possible problems. Afterwards we can implement the solution to these small problems as functions.
In your example your tasks are the following:
Get user input of a number
Get the divisors of that number
Print the divisors
Ask if the user wants to give it another try
Let's start with the 2nd point of our list:
def divisors_of(x):
if x < 0:
raise ValueError("Value cannot be smaller than 0")
divisors = []
for i in range(1, x + 1):
if x % i == 0:
divisors.append(i)
return divisors
That doesn't look too bad, does it?
After implementing the user input for a number and printing the result, we already get something like this:
try:
num = int(raw_input("Please enter a number: "))
divisors = divisors_of(num)
print "The divisors of ", num, " are: ", divisors
except (ValueError, TypeError) as ex:
print ex.message
Looking at our task list we still don't ask the user for another try. Again, IMHO it's more readable if we put the logic for that in a function. This has two additional benefits, we can convert the yes/no choice to a boolean and the written code is reuseable:
def yes_no_choice(text):
while True:
choice = raw_input(text)
if choice in "yes":
return True
# Returning like this is called early return
# As we jump out of the function, the code after
# the if is automatically the else statement
# The code is shorter and more readable
if choice in "no":
return False
print "Invalid answer"
Our final result looks like this:
while True:
try:
num = int(raw_input("Please enter a number: "))
divisors = divisors_of(num)
print "The divisors of ", num, " are: ", divisors
except (ValueError, TypeError) as ex:
print ex.message
if not yes_no_choice("Would you like to try again?(Y/N): "):
print "Bye!"
break
# else we will loop
Oh, and try not to use global variables if you don't have to. I'm looking at your divisors = []

Using for loop within if statements in Python

I am really having a hard time with loop statements for python, please see below:
I want it to check the users age, so if they are over 18, it will say "old enough, if they are over 16, it will say "almost there" and if they are younger than this, it will say "sorry you're too young"
I got the following code below:
age = int(raw_input("Enter your age:"))
if age >= 18:
print "You are old enough!"
elif age >= 16:
print "Almost there"
else:
print "You're just too young"
my problem is, how do I write code the includes an if statement and a for loop that will print out all the numbers from 0 that are less than the user's inputted age?
do I say:
for age in range (0,num)
if num <= age
print ....
else:
print...
Please kindly help. I'm new at this and still learning :(
So you could construct a variable that contains a list of numbers that is smaller than the user's age. You can construct this using python's range function; something like range(age) would do this nicely.
Then you need to use a for loop to loop through all these numbers and print them to the command line. Something like for x in range(age) would be a good place to start.
Then, in the loop, you'd just need to turn x from an integer into a string using the str() function, and print it to the command line.
So as pseudo-code:
if the age is greater than 18:
print that they're old enough
else if the age is greater than 16:
print that they're nearly old enough
otherwise:
print that they're not old enough.
for each number between 0 and age:
print the number
Come back when you have some code and we can help you with any trouble you have.

I am writing a simple number program but an error pops up when I use elif saying I need a colon but I have one already

number = raw_input
print (raw_input('Please enter a number between 1 - 50 :'))
if number <= 10:
print('your number is between 0-10')
elif number <= 20 and >=11: <---- when i put >=11: it gives the error
print('your number is between 11-20')
elif number <
elif number <= 20 and >=11:
^
SyntaxError: invalid syntax
any tips or ideas?
I would take a took this code that I just wrote:
number = int(input("Please enter a number between 1 - 50:"))
if number <= 10:
print("Your number is between 0-10")
elif number <= 20 and number >= 11:
print("Your number is between 11-20")
First, to answer your question, you needed to say "elif number <= 20 and number >= 11:
This is because the 'and' in Python separates the two statements, if you will. Thus after the 'and' you need to remind Python which variable you are using.
On a side note, I only have Python 3 installed so 'raw_input' did not work (as it has been removed). I would consider using input instead in the future as it will stay supported. The only problem is that it returns a string, so you need to cast it to an integer to do what you want to do.
Also one more thing, you can comment in Python by using a hash:
#this is a comment and Python will ignore it
EDIT: Python 2.7's 'raw_input' is equivalent to Pythons 3's 'input' so continue to use that unless you upgrade to Python 3.
Try this code:
def get_number(number):
if (number < 10):
print "number<10 ",number
elif (number>=11 and number<=20):
print "11<number>20 ",number
elif (number<50):
print "number<50 ",number
else:
print "type proper number"
number = raw_input("enter number between 1 - 50");
get_number(int(number)) ##raw_input reads string, so convert number in int

Exception Handling with Boolean Expressions

Is it possible to include a boolean expression like I've done below while exception handling using try/except?
For example:
while True:
try:
grade = float(input('Please enter your your score:'))
break
except ValueError:
print('Please enter a numeric value, you dingus!')
except (grade > 1):
print('Not a valid number, please re-enter:')
except NameError:
print('Please enter a numeric value, you dingus!')
I'd like for string inputs to be handled by 'except NameError.' I'd like for numerics greater than 1 to be handled by printing 'Not a valid number, please re-enter:'
As is, the program handles strings and valid numeric inputs as intended. However, when I input numbers greater than 1, the program accepts my input and does nothing else. No except commands are executed and nothing is passed on to the function found below this exception handling piece of code. The program just stops and no error is given to help with debugging.
Give this a shot:
while True:
try:
grade = float(input('Please enter your your score:'))
if grade > 1:
raise ValueError
except ValueError:
print('Not a valid number, please re-enter.')
except NameError:
print('Please enter a numeric value, you dingus!')
except SyntaxError:
print('Please enter something, anything!?')

make a program choose number 1 until 100

How to make the program choose a value from 1 to 100? The program cannot print the correct value
while True:
regage = raw_input('Enter your age:')
if regage not in range(1,100):
print 'Please put an apropriate number for your age'
else:
print 'you are', regage,'years old'
This should work. The problem was that raw_input returns a string, so the value should be converted to an integer before you can check if it's in the array of integers that range returns.
while True:
regage = raw_input('Enter your age:')
if int(regage) not in range(1,101):
print 'Please put an apropriate number for your age'
else:
print 'you are', regage,'years old'
Also, I changed the range to include 100.