If statement not executing what it should - python

mylist = []
for i in range(0,101,2):
mylist.append(i)
length = len(mylist)
middle_index = length // 2
first_half = mylist[:middle_index]
second_half = mylist[middle_index:]
userRandomNumber = str(input('Please input a random number from 0-100: '))
while True:
if userRandomNumber.isdigit():
break
else:
userRandomNumber = input('Please input a number!: ')
print(first_half)
print(second_half)
if userRandomNumber in first_half:
print('you got it')
elif userRandomNumber in second_half:
print('you got it')
else:
print('false!')
I am making a program where the user has to guess the number in the random list generated automatically. But the problem is when I run the code and input a number that is actually in the list the if statement does not work the way it should!
What is wrong with the code here? Please help!

input returns a string. So, the number you actually enter is converted to string. Even if it didn't, the str would.
Your lists are full of integers. So there is a difference between an integer and string number. It is checking if the string number is in the list.
Of course, it isn't. So the in operator returns False
input('Please input a random number from 0-100: ')
Try this:
if int(userRandomNumber) in first_half:
print('you got it')
elif int(userRandomNumber) in second_half:
print('you got it')
else:
print('false!')

Here this is code:
number=input("Type a number:")
mylist = []
for i in range(0,101,2):
mylist.insert(1,i)
length = len(mylist)
middle_index = length // 2
first_half = mylist[:middle_index]
second_half = mylist[middle_index:]
if int(number) in first_half:
print('you got it')
elif int(number) in second_half:
print('you got it')
else:
print("Nope, "+"'"+"number"+"'"+" not found in the list")
print(first_half)
print(second_half)

In your code, these set of code -
userRandomNumber = str(input('Please input a random number from 0-100: '))
while True:
if userRandomNumber.isdigit():
break
else:
userRandomNumber = input('Please input a number!: ')
can be changed into this -
while True:
try:
userRandomNumber = int(input('Please input a random number from 0-100: '))
break
except:
pass
If you do not know what try and except does, then check this - Python Exception Handling
The rest of the code can be the same, and it will work.

mylist = [i for i in range(0, 101, 2)]
middle_index = len(mylist) // 2
first_half, second_half = mylist[:middle_index], mylist[middle_index:]
print(first_half, second_half, sep='\n')
userRandomNumber = ''
while not userRandomNumber.isdigit():
userRandomNumber = input('Please input a random number from 0-100: ')
userRandomNumber = int(userRandomNumber)
# I think the point of splitting the list into two parts is probably to determine which part belongs to
# the number entered. Otherwise, if the output is 'you got it', then splitting the list makes no sense.
if userRandomNumber in first_half:
print('you got it in the first half')
elif userRandomNumber in second_half:
print('you got it in the second half')
else:
print('false!')

Related

How to stop a while loop processing integers with a string

I'm processing integer inputs from a user and would like for the user to signal that they are done with inputs by typing in 'q' to show they are completed with their inputs.
Here's my code so far:
(Still very much a beginner so don't flame me too much)
def main():
print("Please enter some numbers. Type 'q' to quit.")
count = 0
total = 0
num=[]
num = int(input("Enter a number: "))
while num != "q":
num = int(input("Enter a number: "))
count += 1
total += num
del record[-1]
print (num)
print("The average of the numbers is", total / count)
main()
Any feedback is helpful!
You probably get a ValueError when you run that code. That's python's way of telling you that you've fed a value into a function that can't handle that type of value.
Check the Exceptions docs for more details.
In this case, you're trying to feed the letter "q" into a function that is expecting int() on line 6. Think of int() as a machine that only handles integers. You just tried to stick a letter into a machine that's not equipped to handle letters and instead of bursting into flames, it's rejecting your input and putting on the breaks.
You'll probably want to wrap your conversion from str to int in a try: statement to handle the exception.
def main():
num = None
while num != "q":
num = input("Enter number: ")
# try handles exceptions and does something with them
try:
num = int(num)
# if an exception of "ValueError" happens, print out a warning and keep going
except ValueError as e:
print(f'that was not a number: {e}')
pass
# if num looks like an integer
if isinstance (num, (int, float)):
print('got a number')
Test:
Enter number: 1
got a number
Enter number: 2
got a number
Enter number: alligator
that was not a number: invalid literal for int() with base 10: 'alligator'
Enter number: -10
got a number
Enter number: 45
got a number
Enter number: 6.0222
that was not a number: invalid literal for int() with base 10: '6.0222'
I'll leave it to you to figure out why 6.02222 "was not a number."
changing your code as little as possible, you should have...
def main():
print("Please enter some numbers. Type 'q' to quit.")
count = 0
total = 0
num=[]
num.append(input("Enter a number: "))
while num[-1] != "q":
num.append(input("Enter a number: "))
count += 1
try:
total += int(num[-1])
except ValueError as e:
print('input not an integer')
break
print (num)
print("The average of the numbers is", total / count)
main()
You may attempt it the way:
def main():
num_list = [] #list for holding in user inputs
while True:
my_num = input("Please enter some numbers. Type 'q' to quit.")
if my_num != 'q':
num_list.append(int(my_num)) #add user input as integer to holding list as long as it is not 'q'
else: #if user enters 'q'
print(f'The Average of {num_list} is {sum(num_list)/len(num_list)}') #calculate the average of entered numbers by divide the sum of all list elements by the length of list and display the result
break #terminate loop
main()

How to accept user input of a sequence?

I'm new to python and I'm trying to help out a friend with her code. The code receives input from a user until the input is 0, using a while loop. I'm not used to the python syntax, so I'm a little confused as to how to receive user input. I don't know what I'm doing wrong. Here's my code:
sum = 0
number = input()
while number != 0:
number = input()
sum += number
if number == 0:
break
In your example, both while number != 0: and if number == 0: break are controlling when to exit the loop. To avoid repeating yourself, you can just replace the first condition with while True and only keep the break.
Also, you're adding, so it is a good idea to turn the read input (which is a character string) into a number with something like int(input()).
Finally, using a variable name like sum is a bad idea, since this 'shadows' the built-in name sum.
Taking all that together, here's an alternative:
total = 0
while True:
number = int(input())
total += number
if number == 0:
break
print(total)
No need last if, and also make inputs int typed:
sum = 0
number = int(input())
while number != 0:
number = int(input())
sum += number
You can actually do:
number=1
while number!=0:
number = int(input())
# Declare list for all inputs
input_list = []
# start the loop
while True:
# prompt user input
user_input = int(input("Input an element: "))
# print user input
print("Your current input is: ", user_input)
# if user input not equal to 0
if user_input != 0:
# append user input into the list
input_list.append(user_input)
# else stop the loop
else:
break
# sum up all the inputs in the list and print the result out
input_sum = sum(input_list)
print ("The sum is: ", input_sum)
Or
If you don't want to use list.
input_list = 0
while True:
user_input = int(input("Input an element: "))
print("Your current input is: ", user_input)
if user_input != 0:
input_list += user_input
else:
break
print ("The sum is: ", input_list)
Note:
raw_input('Text here') # Python 2.x
input('Text here') # Python 3.x

How to return to the top of a loop if the else statement is reached

I hope the title is explanation enough. Basically, the user inputs a number and the number has to be between 1 and 147. If it is, the next required input is reached(num_guess). But we need to have the user try again if the number is not within the parameters. But I cannot figure out how to do this. Thanks in advance.
word_correct = False
def length_check(x):
while (word_correct == False):
if x >= 1 and x <= 147:
return word_correct == True
break
else:
print("Try another number")
# print(input("Please enter a word length: ")) ## ignore me
word_length = input("Please enter a word length: ")
length_check(word_length)
num_guess = raw_input("Please enter an amount of guesses: ")
try this
word_correct = False
def length_check(x):
while (word_correct == False):
if x >= 1 and x <= 147:
return word_correct == True
else:
print("Try another number")
new_word= input("Please enter a word length: ")
length_check(new_word)
word_length = input("Please enter a word length: ")
length_check(word_length)
num_guess = raw_input("Please enter an amount of guesses: ")
I would not try to put the loop inside word_check. Separate the responsibility for checking the length from the control flow & printing messages.
You can use an infinite loop, that is only broken out of when a valid value is input.
Also don't forget to convert to int. I am presuming you are using python 3? There is the possibility for the user to enter something that is not a valid integer (e.g. "abc"), so use an exception to handle that. If you are using python 2, swap input for raw_input.
def length_check(x):
return x >= 1 and x <= 147
while True:
try:
word_length = int(input("Please enter a word length: "))
except ValueError:
print('please enter a valid number')
continue
if(length_check(word_length)):
break
print("Try another number")
Notice that this method involves only a single instance of input. This will make life easier later. For example, if you want to change the message and you don't have to remember to change it in two places or assign it to some string variable.
Basically you don't need a break after return.Once the compiler encounters return,it doesn't go through the next statements.
What's the error in your code?
The implementation is not proper.
Use of break or return not in desired place
The code for your requirement can be implemented as follows -
def length_check(x):
while(1):
temp = input()
if temp >= 1 and temp <= 147:
return
else:
print 'Enter proper length'
This should solve your problem.
This strategy is much more concise, and utilizes recursion. No while loop is needed for what you are trying to do:
def main(warning=''):
if warning:
print(warning)
word_length = input("Please enter a word length: ")
if word_length >= 1 and word_length <= 147:
num_guess = raw_input("Please enter an amount of guesses: ")
else:
main(warning="Try another number")
#... now do something with num_guess
You may try this
word_correct = False
def length_check(x):
while (word_correct == False):
if x >= 1 and x <= 147:
word_correct == True
break
else:
x = input("Try another number")
# print(input("Please enter a word length: ")) ## ignore me
return
word_length = input("Please enter a word length: ")
length_check(word_length)
This might work:
else:
word_length = input("Try another number")
length_check(word_length)
In the event of a wrong guess (the else) you ask the user for another input to word_length and then run the checking function length_check again. User can go through this as many times as they like (ie keep taking the else branch by entering a wrong value) until they get the number correct, and satisfy the if condition.
You might be able to get away without using break if you use this.
A while True with break in block works like a do{} until() in other language, so as below program to satisfy the problem statement. Another point is to take care of recursion limit there is no hard limit in code to break out.
hint = "Please enter a word length: "
while True:
x = int(raw_input(hint).strip())
if 1 <= x <= 147:
break
else:
hint = "Try another number"
num_guess = int(raw_input("Please enter an amount of guesses: ").strip())

Adding onto an input prompt after the user inputs

I'm trying to make a "pi-practicing' program in python, and I want the user's input, if correct, to be placed next to the "3.".
I have:
numbers = [1,4,1,5,9,2,6,5]
def sequence():
i = input("3.")
y = int(i)
if y == numbers[0]:
print ("Good job!")
#??????
numbers.pop(0)
sequence()
else:
print("nope")
sequence()
sequence()
So when prompted, if the user enters 1 as the first number, I want the next input prompt to be 3.1, so the user has to enter 4, and so on.
Thank you in advance!
-rt
You don't need recursion a simple while loop would do. It's generally not good practice to leverage global variables:
def sequence():
numbers = [1,4,1,5,9,2,6,5]
prompt = '3.'
while numbers:
i = input(prompt)
y = int(i)
if y == numbers[0]:
print ("Good job!")
prompt += i
numbers.pop(0)
else:
print("nope")
sequence()

Python ask for user input without a newline?

I just started python a few days ago and have been working on a calculator (not extremely basic, but also not advanced). The problem doesn't prevent code from running or anything, it is just a visual thing.
Output in the console looks like this (stuff in parenthesis is explaining what is happening and is not actually part of the output):
4 (user prompted for first number, press enter afterwards)
+ (user prompted for an operator, press enter afterwards
5 (user prompted for second number, press enter afterwards)
9.00000 (answer is printed)
Process finished with exit code 0
Basically what I want it to look like is this when I'm entering it into the console:
4+5
9.00000
I don't want it to start a newline after I enter a number or operator or whatever, it looks more like an actual calculator when it prints along one line. Is this possible to do and if so how? Btw I know end="" works with print but not with input since it doesn't accept arguments. Also I know the whole calculator thing is kind of redundant considering you can make calculations really easily in the python IDLE but I thought it was a good way for me to learn. Here is the entire code if you need it:
import math
while True:
try:
firstNumber = float(input())
break
except ValueError:
print("Please enter a number... ", end="")
while True:
operators = ['+', '-', '*', '/', '!', '^']
userOperator = str(input())
if userOperator in operators:
break
else:
print("Enter a valid operator... ", end="")
if userOperator == operators[4]:
answer = math.factorial(firstNumber)
print(answer)
pause = input()
raise SystemExit
while True:
try:
secondNumber = float(input())
break
except ValueError:
print("Please enter a number... ", end="")
if userOperator == operators[0]:
answer = firstNumber + secondNumber
print('%.5f' % round(answer, 5))
elif userOperator == operators[1]:
answer = firstNumber - secondNumber
print('%.5f' % round(answer, 5))
elif userOperator == operators[2]:
answer = firstNumber * secondNumber
print('%.5f' % round(answer, 5))
elif userOperator == operators[3]:
answer = firstNumber / secondNumber
print('%.5f' % round(answer, 5))
elif userOperator == operators[5]:
answer = firstNumber ** secondNumber
print('%.5f' % round(answer, 5))
pause = input()
raise SystemExit
Your problem is that you're asking for input() without specifying what you want. So if you take a look at the first one: firstNumber = float(input()) It's executing properly, but you hit enter it gives an error which is only then you're specifying what you want.
Try replacing with these:
...
try
firstNumber = float(input("Please enter a number... "))
...
userOperator = str(input("Enter a valid operator... "))
...
secondNumber = float(input("Please enter a number... "))
Is that what you're looking for?
Using my method I suggested:
Please enter a number... 5
Enter a valid operator... +
Please enter a number... 6
11.00000
Using your method:
Please enter a number... 5
Enter a valid operator... +
Please enter a number... 6
11.00000
Extra newlines which is what I'm assuming you're referring to.
That's a nice exercise, and as I wrote in the comments, I would ignore whitespaces, take the expression as a whole from the user and then parse it and calculate the result. Here's a small demo:
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
def calc(expr):
if is_number(expr):
return float(expr)
arr = expr.split('+')
if len(arr) > 1:
return sum(map(calc, arr))
arr = expr.split('-')
if len(arr) > 1:
return reduce(lambda x,y: x-y, map(calc, arr))
arr = expr.split('*')
if len(arr) > 1:
return reduce(lambda x,y: x*y, map(calc, arr), 1)
arr = expr.split('/')
if len(arr) > 1:
return reduce(lambda x,y: x/y, map(calc, arr))
print calc("3+4-2 *2/ 2") # 5

Categories