Using If Else statements in addition to sets using Python - 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.

Related

Python given number exists in list or not

a = [1,2,3,4,5,6]
print(a)
s=input("Enter a number from the list given \n")
if s in a:
print("the number given is", s)
else:
print("please select the number given in the list")
When I give 2 as input, the if statement is not being checked directly; the else part is printed. But if provide the value hardcoded in the program, the code is working as expected.
If my input is any number from the list, it should print that number. If not, the other part should be printed.
s=int(input("Enter a number from the list given \n"))
I believe
You are taking string as an input and not int. Try using
s = int(input("Some value")
You can change your if condition like this:
a = [1,2,3,4,5,6]
print(a)
s = input("Enter a number from the list given: ")
if s in set(str(e) for e in a):
print("the number given is", s)
else:
print("please select the number given in the list")
In this way you do not have to convert the user input to int which is fraught with problems if the value(s) entered cannot be converted to int.
An alternative is to use exception handling as follows:
a = [1, 2, 3, 4, 5, 6]
while True:
try:
print(a)
s = int(input("Enter a number from the list given: "))
if s in a:
print("the number given is", s)
break
else:
raise ValueError("please select the number given in the list")
except ValueError as ve:
print(ve)

If function error. Not equals to function not working

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.

How do I sum numbers from user input in python?(only if they are even numbers)

I am new to programming, and I'm trying to make a code to get six numbers from a user and sum only even numbers but it keeps error like, "unsupported operand type(s) for %: 'list' and 'int' How can I do with it?
Also, I want to make like this,
Enter a value: 1
Is it even number?:no
Enter a value: 2
Is it even number?:yes
Enter a value: 3
Is it even number?:no
Enter a value: 6
Is it even number?:yes
but it keeps like this,
Enter a value: 1
Enter a value: 2
Enter a value: 3
Enter a value: 4
Enter a value: 5
Is it even number?:
Is it even number?:
Is it even number?:
Is it even number?:
Is it even number?:
How can I fix this?
anyone who can fix this problem please let me know
Python 3.7
numbers = [int(input('Enter a value: ')) for i in range(6)]
question = [input('Is it even number?: ') for i in range(6)]
list1 = [] #evens
list2 = [] #odds
if numbers % 2 ==0:
list1.append
else:
list2.append
sum = sum(list1)
print(sum)
And I'd appreciate it if you could let me know if you knew the better code
This should do it. Note that there is no real need to ask the user if the number is even, but if you do want to ask, you can just add question = input('Is it even number?: ').lower() in the loop and then do if question=='yes'. Moreover, note that you cannot perform % on a list; it has to be on a single number.
evens = []
odds = []
for i in range(6):
number = int(input('Enter a value: '))
if number%2==0:
evens.append(number)
else:
odds.append(number)
print(sum(evens))
you are running the first two input statements in for loops and print at the same time.
You can just take inputs first 6 times and store them in a list. After that you can check each input and store in even and odd lists while printing if its even or odd. and print the sum at last.
Your if condition makes no sense:
if numbers % 2 == 0:
What is the value of [1, 2, 3, 6] % 2? There is no such thing as "a list, modulo 2". Modulus is defined between two scalar numbers.
Instead, you have to consider each integer in turn. This is not an operation you get to vectorize; that is a capability of NumPy, once you get that far.
for i in range(6):
num = int(input('Enter a value: '))
# From here, handle the *one* number before you loop back for the next.
If you want to show running sum. You can do something like :
import sys
sum_so_far = 0
while True:
raw_input = input('Enter an integer: ')
try:
input_int = int(raw_input)
if input_int == 0:
sys.exit(0)
elif input_int % 2 == 0:
sum_so_far = sum_so_far + input_int
print("Sum of Even integers is {}. Enter another integer er or 0 to exit".format(sum_so_far))
else:
print("You entered an Odd integer. Enter another integer or 0 to exit")
except ValueError:
print("You entered wrong value. Enter an integer or 0 to exit!!!")

Validating int numbers in a certain range. Python-3.x [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 2 years ago.
I am making this game where the user has to choose from 5 options. So, he must type any number from 1 to 5 to choose an option. Now here is the problem I am facing, I just can't figure out a way in which the user cannot type in any other character except the int numbers from 1 to 5, and if he does type in a wrong character, how should I show his error and make him type in the input again? Here is what I've tried:
def validateOpt(v):
try:
x = int(v)
if int(v)<=0:
x=validateOpt(input("Please enter a valid number: "))
elif int(v)>5:
x=validateOpt(input("Please enter a valid number: "))
return x
except:
x=validateOpt(input("Please enter a valid number: "))
return x
Here validateOpt is to validate the number for the option, i.e., 1,2,3,4,5. It works fine, but whenever I type 33,22, 55, or any other int number from 1 to 5 twice (not thrice or even four times, but only twice), it doesn't show any error and moves on, and that, I suppose, is wrong. I am just a beginner.
You can do this with a while loop, something like this should be a good start:
def getValidInt(prompt, mini, maxi):
# Go forever if necessary, return will stop
while True:
# Output the prompt without newline.
print(prompt, end="")
# Get line input, try convert to int, make None if invalid.
try:
intVal = int(input())
except ValueError:
intVal = None
# If valid and within range, return it.
if intVal is not None and intVal >= mini and intVal <= maxi:
return intVal
Then call it with something like:
numOneToFive = getValidInt("Enter a number, 1 to 5 inclusive: ", 1, 5)
use a while loop instead of recursion, you can check the user data and return if its valid, although you might want to consider a break out clause should the user want to exit or quit without a valid input.
def get_input(minimum, maximum):
while True:
try:
x = int(input(f"please enter a valid number from {minimum} to {maximum}: "))
if minimum <= x <= maximum:
return x
except ValueError as ve:
print("Thats not a valid input")
value = get_input(1, 5)
Use for loop in the range between 1 and 5
Try this code, it will keep prompting user till he enters 5, note that this may cause stackoverflow if recursion is too deep:
def f():
x = input("Enter an integer between 1 and 5:")
try:
x = int(x)
if x<=0 or x>5:
f()
except:
f()
f()

python - inputting numbers that start with 0

I'm making a program in python. It is suppose to take in a GTIN number and put in a list and then check if it's valid. The program works, but as soon as I enter a GTIN number that starts with a 0, I get a "invalid token (, line 1)" error. I really need a solution because some products have their GTIN numbers starting with a 0.
when I input a number for example:
96080832
The program works great.
When i put in a number like:
00256986
I get an error:
invalid token (<string>, line 1)
pointing to this line:
inputtedInt = int(input("Enter the gtin number: "))
Whole def:
def chooseOption(inputInt):
while(inputInt > 0 and inputInt < 4):
if(inputInt == 1):
print("you picked option number 1")
showOptions()
break
elif(inputInt == 2):
print(" ")
inputtedInt = int(input("Enter the gtin number: "))
gtin = map(int,str(inputtedInt))
checkValidity(gtin, 2)
print(" ")
showOptions()
break
elif(inputInt == 3):
print("you picked option number 3")
showOptions()
break
else:
option = int(input("Error - enter a number from 1 to 3. : "))
chooseOption(option)
Thanks in advance.
You seem to be using Python 2. In Python 2, input tries to evaluate the input string as a Python expression, and a leading 0 on a numeric literal in Python 2 syntax means that the number is in octal, or base 8. Since 8 and 9 are not valid digits in base 8, this input constitutes a syntax error.
If you were supposed to be using Python 3, get on Python 3. If you're supposed to be on Python 2, use raw_input instead of input.
Additionally, if you care about preserving things like leading zeros, you should keep the input as a string and only call int on it when you want to do math on it as an integer.
Error is raised because you are mapping str ant/to int in line:
gtin = map(int,str(inputtedInt))
for example if you ty to run:
a = 005
You will get following error:
File "<stdin>", line 1
a = 005
^
SyntaxError: invalid token
Sollution -> you should use stringsfor GTIN number :)

Categories

Resources