If function error. Not equals to function not working - python

I am writing this program and it works fine,
I leave it for sometime and the code stops working.
Please help me in this function;
Here is the code:
acceptables = [1, 2, 3, 4, 5, 6, 10]
try :
toss = input("Toss a number from 1 to 6 (10 included): ")
except ValueError:
print("Invalid")
if toss != acceptables:
print("Illegal Numbers!")
time.sleep(2)
exit()
else:
pass
So what should happen is, the user will enter a number in toss and it will check
if the number is from acceptables, if not it will quit the program.
But now, I entered number that is in acceptables and it still ends up showing
"Illegal Number" and quits the program.
Is this a new python3 update or something that I missed out on? Please help

You've got two problems:
toss = input(...) returns a string, but you want to compare that value to ints. Try a type conversion: toss = int(toss) to transform your str from "1" to 1.
You're checking if the number is in the list using if toss != acceptables: which will always be False because an int (or str at the moment) will never be equal to a list. You want to check if toss is in the list of acceptables. Try this instead: if toss in acceptables:

There are a few issues. First, this line:
toss = input("Toss a number from 1 to 6 (10 included): ")
will store the string value of whatever you submit into toss. You likely want this line to read:
toss = int(input("Toss a number from 1 to 6 (10 included): "))
to ensure you get an integer or a ValueError in the case the user types a non-integer string.
Secondly, this line:
if toss != acceptables:
is checking if toss, what would be an int, is not equal to a list, essentially doing this: if 5 != [1, 2, 3, 4, 5, 6, 10]. You instead likely want this to read:
if toss not in acceptables:
To check if this number is in your list of acceptable numbers.

Related

I am running into a Name error when I convert a string input to an int

I am very new to python and programming as a whole. I recently took up a python beginners course and got an assignment that I am having difficulties with, the assignment will be posted below.
"Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. Enter 7, 2, bob, 10, and 4 and match the output below."
I am currently trying to convert a string input to an int so I can compare it with a none type, when I do this I get a name error. Both the code and the error will be posted below
I am aware that there is a multitude of issues in this code and if you spot something feel free to let me know. Here is my code, please go easy on me.
Code:
Largest = None
smallest = None
while True:
try:
Numbers = int(input("Enter A number: "))
if Numbers == ('done'):
break
except:
print ('invalid number')
for Numbers in [Numbers]:
if Largest is None:
Largest = Numbers
elif Numbers > Largest:
Largest = Numbers
if smallest is None:
smallest = Numbers
elif Numbers < smallest:
smallest = Numbers
print (Largest)
print (smallest)
Error:
C:\Users\Noah\Desktop\py4e>throw_away.py
Enter A number: f
invalid number
Traceback (most recent call last):
File "C:\Users\Noah\Desktop\py4e\throw_away.py", line 10, in <module>
for Numbers in [Numbers]:
NameError: name 'Numbers' is not defined
This happens because, when you have an error, you go into your except clause, but you then move right on into processing your numbers. Because there was an error, the Numbers variable was not created.
You need a continue in your except clause.
By the way, for Numbers in [Numbers]: is wrong in several ways. First, you should not have the loop variable be the same as the thing you are iterating. Next, Numbers is not a list -- it's a single number. So, you don't need a for loop at all. Just delete that line.
You need to rewrite your script to make it work:
# In order to keep track of all numbers typed by the user,
# we will use this list. It needs to be allocated just once
# before the main loop begins.
Numbers = []
# Start the main loop
while True:
try:
# Ask for the user input
num = input("Enter A number: ")
# Before converting it to an integer, check if the input
# is the string 'done'
if num == ('done'):
# If it is, break the loop.
break
# Otherwise, try to convert it to a number
else:
num = int(num)
# In any case, if int(num) fails, this exception will be
# catched and this block will execute instead
except:
print ('invalid number')
# If no exceptions were raised, then it means everything is
# normal.
#
# Append the user input converted to a number to the list.
else:
Numbers.append(num)
# When outside of the loop, check if the list is empty.
if (len(Numbers) == 0):
print('No numbers were recorded. List is empty.')
# If its not empty, find the minimum and maximum number, and
# print them on the screen.
else:
print ('MAX: ', max(Numbers))
print ('MIN: ', min(Numbers))
NOTE: There are other ways to write this script and get the same output. This is one of many ways to solve your problem. There are ways to make this script even faster by taking out the min and max functions and using the smallest and Largest variables from your script. That's an exercise for you if you're curious about it.

Using If Else statements in addition to sets using Python

I have to create a fortune teller for school. I want the user to input a number between 1-9. But i also want to give an error message if they put in a different number. I'm using a set containing my numbers, but I can't call it in my if statements.
fortune_num = set([1, 2, 3, 4, 5, 6, 7, 8, 9])
user_num = input(f'Pick a number and find your fortune! Choose a number from 1 to 9 and hit enter: ')
print()
if user_num == fortune_num:
print(user_num)
else:
print('Error')
Use the keyword in to check set membership, also cast input into int:
fortune_num = set([1, 2, 3, 4, 5, 6, 7, 8, 9])
user_num = input(f'Pick a number and find your fortune!
\nChoose a number from 1 to 9 and hit enter: ')
print()
if int(user_num) in fortune_num: #this would throw an error if input is not int
print(user_num)
else:
print('Error')
You can use this code,
fortune_num = list(range(1,10))
user_num = input(f'Pick a number and find your fortune!\nChoose a number from 1 to 9 and hit enter: ')
if int(user_num) in fortune_num:
print(user_num)
else:
raise ValueError("You entered a wrong input!")
This would raise an actual Python error if the input is wrong.
If you want to give the user another chances to enter a correct input use this,
fortune_num = list(range(1,10))
while True:
try:
user_num = int(input(f'Pick a number and find your fortune!\nChoose a number from 1 to 9 and hit enter: '))
if user_num in fortune_num:
print(user_num)
break
else:
raise ValueError
except:
print("\nYou entered a wrong input. Please enter a valid number!")
Change the code as per your needs but this would do work as the perfect foundation.
First of all, input takes user input as a string. So even if they enter 1, that won't match your set, because your set is of int, and their input is the string '1', not the integer 1. Also, there's no need to use a set. A range object is easier to generate, and since it contains multiple numbers, the variable name should be plural. You also don't have your indentation correct. I don't see what the f in the input function is doing, and if you want a multi-line string, you need triple quotes. Also, if you have a carriage return in your string, putting \n in the string gives you two line breaks; I'm not sure that's intended. So one way of doing this is:
fortune_nums = [str(num) for num in range(1,10)]
user_num = input('''Pick a number and find your fortune!
Choose a number from 1 to 9 and hit enter: \n''')
print()
if user_num in fortune_nums:
print(user_num)
else:
print('Error')
If you want to get fancier, you can keep your fortune_nums as int, then do a try-except on converting the input to int, catching the invalid literal error:
fortune_nums = range(1,10)
user_num = input('''Pick a number and find your fortune!
Choose a number from 1 to 9 and hit enter: \n''')
print()
try:
if(int(user_num) in fortune_nums):
print(user_num)
except ValueError:
print("That's not a valid integer!")
if user_num == fortune_num: // instead of this; you can use keyword in int(user_num) in fortune_num:,
Also your print statement must be indented, otherwise you might get indentation error.

I can't understand this while loop code with try/except nested in (python)

5.2 Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. Enter 7, 2, bob, 10, and 4 and match the output below.
largest = None
smallest = None
while True:
try:
num = input("Enter a number: ")
if num == "done" : break
print(num)
if num > largest:
largest=num
if num < smallest:
smallest=num
except:
print("Invalid input")
print("Maximum is", largest)
print("Minimum is", smallest)
desired output: my output:
Invalid input 2 ← Mismatch
Maximum is 10 4
Minimum is 2 5
maximum is 5(it prints the last input)
minimum is None
I'm a total beginner at programming and python so if the error is obvious pls break it down as much as you could..thank you so much.
The program will never reach print("Invalid input") since there is no error that could be thrown above. If you were to cast num to an integer with num = int(num) after you've checked if num == "done", then the program would catch invalid inputs like "bob"
input() returns a string, so you need to cast the input to integer with int() before comparing it as a number. Also remove your unnecessary print(num).
So change:
print(num)
to:
num = int(num)
The problem is that you are using strings, not numbers. 10 is a number, it is stored as numeric data and you can do things like compare size, add, subtract, etc. Specifically it is an integer, a number with no decimal places (computers store numbers in a lot of different ways). '10' is a string, a set of characters. Those characters happen to represent a number, but the computer doesn't know that. As far as it can tell it is just text.
What you can do to convert a string to an integer is simply num = int(num). If the number can be converted to an integer, it will be. If it can't, you will get an error. That is why the instructions tell you to use a try/catch block. It will catch this error.
Your question already explains what you want to do
If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message
The explanation of why is that you need int(num) after you check for done, to try converting a string to an integer, and catch exception that happens for non integer inputs
I suggest you remove the try except, type anything but a number and observe the behavior

Loop - Input numbers to list, don't allow alphabetic input, break out by pressing enter ..?

been at this all day and made absolutely no progress, it's surely supposed to be pretty simple too but I'm new to Python. Google hasn't brought up much so this is my last resort!
It's supposed to be some basic code for manually putting numeric values into a list. If I add a 'print' line to the script I can see the values are being successfully entered as I go along, but I can't seem to add the right script for breaking out of the loop by leaving the input blank. Currently if I set anything to make it break, the script seems to freeze while it's running and I have to reset the console completely.
Also I'm wondering is there a way of ensuring the input is always an integer? It would be good to make things a bit cleaner and bring up an error message or something if the user enters anything non-numeric.
Here's the code.
values = []
while True:
a = raw_input('Enter numeric values. Leave blank to stop: ')
if a == (??????) :
break
values.append(float(a))
Thanks!
You can restrict to only numbers with
if a.isdigit():
So your function could look like
def accept_inputs():
values = []
while True:
a = raw_input('Enter numeric values. Leave blank to stop: ')
if a.isdigit():
values.append(float(a))
if not a:
return values
Testing
>>> accept_inputs()
Enter numeric values. Leave blank to stop: 5
Enter numeric values. Leave blank to stop: 42
Enter numeric values. Leave blank to stop: 73
Enter numeric values. Leave blank to stop: ab
Enter numeric values. Leave blank to stop: abc
Enter numeric values. Leave blank to stop:
[5, 42, 73]
My approach is similar to #CoryKramer, with small changes
>>> values = []
>>> while True:
val = raw_input('Enter Number : ')
if not val:
print values
elif val.isdigit():
values.append(int(val))
else:
print 'you have entered non - digit value'
Enter Number : 2
Enter Number : a
you have entered non - digit value
Enter Number : 3
Enter Number : 5
Enter Number : 6
Enter Number : 22
Enter Number : 546
Enter Number : 31s
you have entered non - digit value
Enter Number : 345678
Enter Number :
>>> values
[2, 3, 5, 6, 22, 546, 345678]
Strings have a built in function isdigit() that returns true if all the characters are numbers.
To break out if nothing is entered, use the len() function to detect if the string is empty.
More info here
You're code would look like this:
if a.isdigit():
#keep going, and add it to the list
elif len(a) == 0:
break #stop the loop

How do i do a Does not equal multiple numbers?

i'm using python 3.2.3 idle
here's my code:
number = input("please enter 1 or 2")
if number != 1 or 2: #this part is wrong
print("You didn't enter 1 or 2")
my code is incorrect. i want to make it so that if the user doesn't enter 1 or 2, error pops up. say they enter 1.5, 3, etc or something that isn't 1.0 or 2.0.
how do i do that using the != command?
The problem is that the code is parsed as
if ((number != 1) or 2):
and 2, being nonzero, is always True.
Instead I would suggest
if number not in (1, 2):
You can always use in/not in:
if number not in (1,2):
Don't forget to create an integer out of your number as well...
number = int(input("please enter 1 or 2"))
Your code as is will never give a True result since you're comparing strings to integers (which will always be inequal).
You can try this:
if number!=1 and number!=2

Categories

Resources