This question already has answers here:
Python input does not compare properly [closed]
(2 answers)
Closed 3 years ago.
I am using an If statement inside a for loop but the If statement is getting skipped even after the condition is met
x=raw_input().split(" ")
c=[]
for a in x:
b=1
if a<0:
print "Please enter a number greater than or equal to 0"
else:
if(a==1 or a==0 ):
print "1"
for i in range(1,int(a)+1):
b=b*i
c.append(str(b))
print ",".join(c)
the program is to find factorial, i am getting the result. If someone enters a negative number, it should not return a factorial but this does. I just want to know why is the if and else conditions getting skipped.
Comparing string with number returns False as result
'-2'< 0 ---> False --> if condition will be skipped
Convert the string to integer since factorial are only applied to integer
int('-2') < 0 ---> True --> if condition will be executed
x = raw_input().split(" ") returns strings data type in a list
so you can't use int for the entire list x,
only one string at the time
When invoking the if condition you are considering only one element in the list,
then convert from string to int before comparing to 0 --> int(a) < 0
The second point is related to indentation print (",".join(c))
should be included inside the else loop
Also
if(a==1 or a==0 ):
print "1"
is not needed as it has been take care in the for loop below
The code is as follow
x=raw_input().split(" ")
c=[]
for a in x:
b=1
if int(a) < 0:
print "Please enter a number greater than or equal to 0"
else:
for i in range(1,int(a)+1):
b=b*i
c.append(str(b))
print ",".join(c)
You might want to convert the input into int before doing int operations. Change this
x=raw_input().split(" ")
to
x=map(int, raw_input().split(" "))
x="-2 3 6 -3".split(" ")
c=[]
for a in x:
b=1
if int(a)<0:
print ("Please enter a number greater than or equal to 0" )
continue
else:
if(a==1 or a==0 ):
print ("1" )
for i in range(1,int(a)+1):
b=b*i
c.append(str(b))
print (",".join(c))
o/p:
Please enter a number greater than or equal to 0
Please enter a number greater than or equal to 0
6,720
Two changes, int(a) in if condition and if you wish not to calculate the factorial for negative numbers then add continue
Related
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 4 months ago.
try:
x = int(input("Enter Your Number first = ")) or float(input("Enter Your Number first = "))
y = int(input("Enter Your Number first = ")) or float(input("Enter Your Number first = "))
except:
print("Error,Invalid Input")
I know I am wrong, I was just wondering why I am unable to use it. As I am not getting any errors. When I try to put float value inside the input it returns me to my second case, which is Error, Invalid Input. I am using (or) operator so that I can validate integer and float values in one place. (or) the operator should execute the code when one of the conditions is true right? But why cannot we use Or operator with an integer? The code will work if you remove int from the code.
While you can use the or operator to select the the first truthy value between to values (or the latter, if the first one is falsy), it doesn't work in this case because trying to convert into int a string which represents a float value doesn't return a falsy value, it raises an Exception, which is why you go into your except clause
A logically sound way to write your code would be
x = input("Enter Your Number first = ")
try:
num = int(x)
except:
num = float(x)
Not the best way to do it, but it works
Another example:
x = 10/0 or 3 #ZeroDivisionError
x = 0/10 or 3 # x is 3 because 0 is a falsy value
Generally, we use or case to check some conditions. For example if x<3 or x>5: This if block works of both cases. However, in your situation you are trying to get some input from user and using x = int(input("Enter Your Number first = ")) or float(input("Enter Your Number first = ")). So, when I enter a value it gets number as string and when you write int(input()) it convert it to integer and assign to x. So OR is not logically suitable for here. What will computer work it this situation? What you want to achieve? If you want take argument as float just write float(input()) because when you enter integer it can be taken as float also.
try:
x = float(input("Enter Your Number first = ")) or int(input("Enter Your Number first = "))
y = float(input("Enter Your Number first = ")) or int(input("Enter Your Number first = "))
except:
print("Error,Invalid Input")
operators = input("Choose operations (*, -, +, /)")
if operators == "*":
print(float(x*y)) or print(int(x*y))
elif operators == "-":
print(float(x-y)) or print(int(x-y))
elif operators == "+":
print(float(x+y)) or print(int(x+y))
elif operators == "/":
print(float(x/y)) or print(int(x/y))
well, i just figured it out,
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!!!")
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 5 years ago.
I was hoping to create a code to output if a next number entered is Up, Down or Same as the first one. I wanted it to exit when '0' is entered. I also wanted it to print the 'Up', 'Down', or 'Same' result at the end when exited with '0' instead of each time a number is entered.(if user enters: 4, 6, 1, 1, then 0 to exit, the final output will be Up, Down, Same printed.) Please tell me what I am missing, here is what i have so far:
firstNumber = input('Please enter your first number:')
nextNumber=input('Enter the next number(0 to finish)')
while nextNumber !=0:
if firstNumber<nextNumber:
print ('Up')
elif firstNumber>nextNumber:
print ('Down')
elif firstNumber==nextNumber:
print ('Same')
firstNumber = nextNumber
nextNumber=input('Enter the next number(0 to finish)')
You are comparing string, not numbers.
You should cast your input to integers with int().
here:
try:
firstNumber = int(input('Please enter your first number:'))
nextNumber = int(input('Enter the next number(0 to finish)'))
except ValueError:
# Handle cast error here
pass
while nextNumber !=0:
...
Note
As blubberdiblub explained:
< > compare pointer code of strings, that means "8" < "10" returns False while 8 < 10 returns True
input
The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.
So use
int(input(...))
This question already has answers here:
Is it possible to implement a Python for range loop without an iterator variable?
(15 answers)
Closed 3 months ago.
So I have this assignment and I have a question about a part I don't know how to do, can you guys help me?
def main():
# Please see the comments
largest = 0
for index in range(3): # Enter the value(s) in the parenthesis to run the loop 3 times
number1 = int(input("Please enter the first number: "))
number2 = int(input("Please enter the second number: "))
number3 = int(input("Please enter the third number: "))
# insert call to function find_largest after this comment.
# find_largest will take in three parameters and will return the largest of the 3 numbers
result = find_largest(number1, number2, number3)
# insert the statement to print the three numbers entered and the largest number after this comment.
print("The numbers you entered were, \n", [number1, number2, number3])
print ("The largest of the numbers you entered is", result)
def find_largest(a, b, c):
# insert parameters in the parenthesis
# Write the code for this function here.
# find_largest will take in three parameters and will return the largest of the 3 numbers
# These three numbers are passed in as parameters from the main function
# Hint: if and elif - no loop needed here
if (a > b) and (a > c):
largest = a
elif (b > a) and (b > c):
largest = b
else:
largest = c
return largest
main() # this is the call to main() that will make the program run
So, my question is the part:
for index in range(3): # Enter the value(s) in the parenthesis to run the loop 3 times
I don't know what to add so the loop run 2 more times after it has found the largest number
The loop you have makes the first two iterations of the loop pointless, as each time you loop, you are reassigning new numbers to the three number variables. As a result, only the numbers entered in the last iteration of the loop are ever used for anything. I think this would make more sense:
numbers = []
for i in range(3):
input = int(input("Enter number: "))
numbers.append(input)
This will give you a list called numbers with 3 numbers in it entered by the user. Then you can do what you want with them. Having said that, you really don't need a for loop to do this. As Craig Burgler mentioned.
Alternatively(though this doesn't use range...):
number1 = 0
number2 = 0
number3 = 0
for i in (number1, number2, number3):
i = int(input("Enter number: "))
The code as written will ask for three numbers three times, overwriting the first and second set of numbers that the user enters. If the assignment is to get three numbers from the user and tell the user which is largest, then you do not need the for loop. The three input statements will do the trick.
Write a program that will prompt the user for two integers, each of which is greater
than 0. The program will display and count the number of divisors that the two integers have in
common.
Additional requirements:
if the integer is less than 1 tell the user there is a problem and then prompt them for the
integer again.
This is what I have written so far, but I am stuck here I dont know how to incorporate both numbers. Essentially I do not know where to go from here or if 'here' is even correct???
Please help...[This is my first time with python]
integer1 = input("Enter an integer: ")
integer2 = input("Enter an integer: ")
print integer1, ": " ,
i = 1
while i <= integer1 and integer2 :
if integer1 or integer2 < 1 :
print input("Enter an integer: ")
if integer1%i == 0 and integer2%i == 0 :
print i ,
i = i + 1
Try to do one step after the other. And try to break down your task into simple steps. In your example it could be something like:
Get first number
Get second number
Calculate
This you can break down futher
Get first number:
Get Number from User
Loop while Number is not ok
...
This way you can see that the validation should not be inside the while loop.
Another tip: test each step separately. This way you will find that if integer1 or integer2 < 1 or while i <= integer1 and integer2 will not work the way you think they do.
This is not how logical operators work in Python or programming in general.
while i <= integer1 and integer2 :
In Python integer2 is a separate logical statement that is always true.
Try instead:
while i <= integer1 and i <= integer2
You'll want to move the code that
validates your input outside of the
loop.
Your print i doesn't need a
comma.
The syntax in your flow
control needs a bit of work, for
example if integer1 or integer2 <
1: should be if ((integer1 < 1) or
(integer2 < 1)):.
First we should do a simple way to get both integers; noting there could be multiple errors. (Even better would be raw_input and checking the number resolves to an int).
integer1 = -1
integer2 = -1
while(integer1 < 1):
integer1 = input("Enter integer 1: ")
while(integer2 < 1):
integer2 = input("Enter integer 2: ")
factor_list1 = [] # store factor list of first number
double_factor_count = 0
# generate the factor list of the first number
for i in range(1, integer1+1): # range(1,5+1) is the list [1,2,3,4,5]
if integer1 % i == 0:
factor_list1.append(i)
for j in range(1, integer2+1):
if integer2 % j == 0 and j in factor_list1:
print j,
double_factor_count += 1
print "\n double count:", double_factor_count
Possibly you want to change it to range(2, integer1) if you want to skip 1 and the integer typed in as numbers.
Note your original code wasn't indented (so didn't appear as code in the forums, and that and and or combine expressions (e.g., things that are True or False). So you meant if integer1 < 1 or integer2 < 1:.
Your code is actually very close, but you have a few problems:
You're not validating integer1 and integer2 correctly (though I suspect you know that, since you're just printing the replacement value).
Your loop test is broken. What you've written means "i is less than integer1, and also integer2 isn't zero".
You can also improve your code in a couple of ways:
Ensuring that your input is not only >= 1, but also an integer.
Using a for loop instead of a while loop, using Python's excellent iterables support.
Here's how to make sure that what the user typed was an integer:
integer1 = 0
while not integer1:
try:
# raw_input() ensures the user can't type arbitrary code
# int() throws a ValueError if what they typed wasn't an integer
integer1 = int(raw_input("Enter the first integer: "))
if integer1 < 1:
print "You must enter an integer greater than 0!"
integer1 = 0 # so that our while statement loops again
except ValueError:
# the user typed something other than an integer
print "You must enter an integer!"
The while, try, and if statements here ensure that the user will be forced to enter a valid integer before your code continues. Here's an example of what the user sees:
Enter the first integer: 6.6
You must enter an integer!
Enter the first integer: -5
You must enter an integer greater than 0!
Enter the first integer: sys.exit(0)
You must enter an integer!
Enter the first integer: 12
Enter the second integer:
And this is how I'd recommend setting up your loop:
# min() returns the smallest of its arguments
# xrange() iterates over a sequence of integers (here, starting with 1 and
# stopping at min(integer1, integer2))
for i in xrange(1, min(integer1, integer2) + 1):
# magic goes here!
Documentation links:
int()
min()
raw_input() and input()
xrange()
Your problem is with your if statements.
Rather than saying: while i <= integer1 and integer2, you need to say while i <= integer1 and i <= integer2
The same applies for your other if statement. if integer1 or integer2 < 1 : should be if integer1 < 1 or integer2 < 1 :