python string and integer comparison - python

I want to print all the numbers until the given user input using while loop. Example:Enter:5 ==> 1 2 3 4 5 But the below program loops for ever.
user = str(input("Enter : "))
i = 1
while i < user:
print(i)
i = i + 1

ummm while i < int(user):?

Try this instead:
try:
user = int(raw_input('Enter: ')) # Cannot compare a string with an integer.
except ValueError:
print('Input should be an integer!')
i = 1
while True:
i += 1
if i > user:
break
print(i)
Note: In your code, even if we were to explicitly declare the input as an integer it would still not quite work the way you want it to. This is because in your code the while loop stops once i is equal to user (as the condition is while less than... and will thus not print out the final value, user. I therefore modified it so it breaks at the point where i is greater than user, meaning that the last printed value will be equal to user.
Example previous output where user = 5:
1
2
3
4
And with the new code:
1
2
3
4
5
It is however better to use a for loop here, if you are not set on using a while loop:
for i in range(1, user+1):
print(i)

input in Python 2.x will try to evaluate what the user enters, it is equivalent to
user = eval(raw_input(...))
In this case, you are explicitly converting whatever is supplied to a string (with str()). In Python 2.x, strings always compare larger than numbers, so i < user is always True.
It is wiser to use raw_input and convert to int. You can also simplify your code with a for loop:
user = int(raw_input("Enter : "))
for i in range(user):
print(i)

You are comparing an int to a str and that is why you are getting an infinite loop. You should compare the same type of variables
user = int(input("Enter: "))
should work

Related

Write a simple looping program

I want to write a program with this logic.
A value is presented of the user.
Commence a loop
Wait for user input
If the user enters the displayed value less 13 then
Display the value entered by the user and go to top of loop.
Otherwise exit the loop
You just need two while loops. One that keeps the main program going forever, and another that breaks and resets the value of a once an answer is wrong.
while True:
a = 2363
not_wrong = True
while not_wrong:
their_response = int(raw_input("What is the value of {} - 13?".format(a)))
if their_response == (a - 13):
a = a -13
else:
not_wrong = False
Although you're supposed to show your attempt at coding towards a solution and posting when you encounter a problem, you could do something like the following:
a = 2363
b = 13
while True:
try:
c = int(input('Subtract {0} from {1}: '.format(b, a))
except ValueError:
print('Please enter an integer.')
continue
if a-b == c:
a = a-b
else:
print('Incorrect. Restarting...')
a = 2363
# break
(use raw_input instead of input if you're using Python2)
This creates an infinite loop that will try to convert the input into an integer (or print a statement pleading for the correct input type), and then use logic to check if a-b == c. If so, we set the value of a to this new value a-b. Otherwise, we restart the loop. You can uncomment the break command if you don't want an infinite loop.
Your logic is correct, might want to look into while loop, and input. While loops keeps going until a condition is met:
while (condition):
# will keep doing something here until condition is met
Example of while loop:
x = 10
while x >= 0:
x -= 1
print(x)
This will print x until it hits 0 so the output would be 9 8 7 6 5 4 3 2 1 0 in new lines on console.
input allows the user to enter stuff from console:
x = input("Enter your answer: ")
This will prompt the user to "Enter your answer: " and store what ever value user enter into the variable x. (Variable meaning like a container or a box)
Put it all together and you get something like:
a = 2363 #change to what you want to start with
b = 13 #change to minus from a
while a-b > 0: #keeps going until if a-b is a negative number
print("%d - %d = ?" %(a, b)) #asks the question
user_input = int(input("Enter your answer: ")) #gets a user input and change it from string type to int type so we can compare it
if (a-b) == user_input: #compares the answer to our answer
print("Correct answer!")
a -= b #changes a to be new value
else:
print("Wrong answer")
print("All done!")
Now this program stops at a = 7 because I don't know if you wanted to keep going with negative number. If you do just edited the condition of the while loop. I'm sure you can manage that.

While loop adding two numbers

I want to write a very basic code.
Add two numbers,next add another number given by user,print result,ask for another,add to previous result,print new result.
I've started with that:
a=int(raw_input('give a number'))
b=int(raw_input('give second number'))
y=True
n=False
while input('Continue? (y/n)') != 'n':
c = a + b
print c
b = int(raw_input('give another number'))
Ok I've correct code by your tips.I am appreciate but it stil doesn't work.It add two numbers,print result then ask for another add to result(right now its ok) But when you enter another it add to a and then print.
Maybe you see what is wrong?
And when I enter "n" it didn't end the program
I'd avoid using input() in lieu of raw_input() (safer, and input() was removed in Python 3). With it, you can then turn the input into a number yourself by wrapping it with int() or float(). Then you have a couple possibilities:
Loop forever, and end the loop if you get an error in conversion:
...
while True:
try:
b = int(raw_input('give another number ("x" to exit)'))
except ValueError:
break
...
Or, break if you see some sentinel value, for instance 0 (which conveniently evaluates as false).
a = 1
b = 2
while b:
a = a + b
print a
b = int(raw_input('give another number'))
In most programming languages, including Python, conditions must evaluate to true or false. In this case, the string "condition" will always evaluate to true, because only empty strings evaluate to false. In order to leave the while loop, you must first determine what condition is necessary to discontinue looping. With
while condition: pass
condition can be an if statement, or an object reducible to True or False. Most objects, such as lists, tuples, and strings, evaluate to True when not empty, and False when empty. The other common condition is a comparison between two values; such as
1 < 2
or
a is b
The simplest condition you could check for is EOF (end of file). That would be when the user does not type a number but instead just types a carriage return.
It is up to you to tell the user how to end the program. So you also have to write an instruction to them e.g.
b=input('give another number or type <enter> to end')
I'm a beginner too. I know this solution is simplistic, but it works.
a=int(raw_input('Give a number'))
while True:
print a
userIn = (raw_input('Give another number or <cr> to end)'))
if not userIn:
break
b = int(userIn)
a = a + b

Why does my Fibonacci series genetares an infinte loop? [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 7 months ago.
unfortunately raw_input is not doing what I need it to do. What I am trying to do is get totPrimes = whatever I type in at the prompt. If i replace while count < totPrimes with while count < 50 this script works. If I type 50 into the prompt, this script doesnt work, I'm afraid raw_input isn't the function im looking to use? Here is a snippet of my code:
testNum = 3
div = 2
count = 1
totPrimes = raw_input("Please enter the primes: ")
while count < totPrimes :
while div <= testNum :
Do
totPrimes = int(totPrimes)
while count < totPrimes:
# code
raw_input gives you a string you must convert to an integer or float before making any numeric comparison.
You need to cast totPrimes into an int like this:
integer = int(totPrimes)
You just need to convert your raw input in a integer. For your code just change your code as:
testNum = 3
div = 2
count = 1
totPrimes = raw_input("Please enter the primes: ")
totPrimes=int(totPrimes)
while count < totPrimes :
while div <= testNum :
The raw_input function always returns a 'string' type raw_input docs, so we must in this case convert the totPrimes 'string' type to an 'int' or 'float' type like this:
totPrimes = raw_input("Please enter the primes: ")
totPrimes = float(totPrimes)
You can combine them like this:
totPrimes = float(raw_input("Please enter the primes: "))
In order to compare things in python count < totPrimes, the comparison needs to make sense (numbers to numbers, strings to strings) or the program will crash and the while count < totPrimes : while loop won't run.
You can use try/except to protect your program. managing exceptions
For people taking the course "Programming for Everybody" you can take in hours and rate this way. the if/else statement you should try to figure out.
You have to change every number to "hrs" or "rate".
For example: 40*10.50+(h-40)*10.50*1.5 is wrong, 40*r+(h-40)*r*1.5 is right.
Use input then.
Raw input returns string.
input returns int.

Extract element from a shuffled list (based off of user's input)

I have something like this:
s=[7777,5454,75000,4545,787,16000,1000,9888,7854,12223]
random.shuffle(s)
ans=input('Press a number from 0 to 9')
I want to associate the input number ans with the s[ans] element. I can do it with 10 if loops, is this the only chance? //SOLVED this
Done that, I want to repeat the random extraction until user digits something like "stop" (here I am) and then sum all the value extracted until "stop" string. How can I do this last point?
Thanks all!
from random import choice
elem = choice (some_list)
If you are only trying to select a random number (and asking for input is only a means to achieve that goal), then you should really look into random.choice. It does exactly what you need, and you won't have to spend time shuffling your list
You can directly access values of an array like so:
s[ans]
But first you may have to convert ans to an integer (and handle cases where a user sends something that's not a number!)
try:
i = int(s)
except ValueError:
i = 0
You've edited your question to declare the original version "solved" and then added a second one. In the future, don't do that; accept the answer that solved the problem for you, then create a new question. (And you should still accept the answer that solved your original problem!) But this time only, here's a second answer:
Done that, I want to repeat the random extraction until user digits something like "stop" (here I am) and then sum all the value extracted until "stop" string. How can I do this last point?
I'm assuming you're on Python 2, and using the input function so the user can just type 2 and you get the number 2 instead of the string "2". (If you're using Python 3, input works like Python 2's raw_input, so see the second version.)
So:
s=[7777,5454,75000,4545,787,16000,1000,9888,7854,12223]
random.shuffle(s)
values = []
while True:
ans=input('Press a number from 0 to 9')
if ans == 'stop':
break
values.append(s[ans])
print sum(values)
Note that the user will have to type "stop" with the quotes this way. If the user instead types stop (or 10, for that matter), the program will quit with an exception. It would be much better to use raw_input instead, and do something like this:
s=[7777,5454,75000,4545,787,16000,1000,9888,7854,12223]
random.shuffle(s)
values = []
while True:
ans=raw_input('Press a number from 0 to 9, or stop when done')
if ans == 'stop':
break
try:
index = int(ans)
values.append(s[ans])
except ValueError:
print '{} is not a number or the word stop'.format(ans)
except IndexError:
print '{} is not between 0 and 9.'.format(ans)
print sum(values)
You may recognize that this values = [], while, values.append pattern is exactly what list comprehensions and iterators are for. And you can easily factor out all the user input into a generator function that just yields each s[ans], and then just print sum(userChoices()), without having to build up a list at all. But I'll leave that as an exercise for the reader.
ans = 0
s = [7777,5454,75000,4545,787,16000,1000,9888,7854,12223]
ans_sums = []
while ans != 'stop': # while the input is not 'stop'
random.shuffle(s)
ans = raw_input('Press a number from 0 to 9: ') # this returns the input as a string
if ans == 'stop':
break
else:
ans_sums.append(int(s[ans])) # adds s[ans] to ans_sums.
# it must be converted to an integer first because raw_input returns it as a string
return sum(s[ans])
Alternatively, you can do something like:
ans = 0
s = [7777,5454,75000,4545,787,16000,1000,9888,7854,12223]
ans_sums = 0
while ans != 'stop': # while the input is not 'stop'
random.shuffle(s)
ans = input('Press a number from 0 to 9: ')
if ans == 'stop':
break
else:
ans_sums += s[ans] # adds s[ans] to ans_sums
return ans_sums
This avoids creating a list and accomplishes the same job: finds the sum of all the input.

python while loop unexpected behavior

I'm relatively new to Python, and I don't understand the following code produces the subsequently unexpected output:
x = input("6 divided by 2 is")
while x != 3:
print("Incorrect. Please try again.")
x = input("6 divided by 2 is")
print(x)
the output of which is:
6 divided by 2 is 3
Incorrect. Please try again.
6 divided by 2 is 3
3
Incorrect. Please try again.
6 divided by 2 is
Why is the while loop still being executed even though x is equal to 3?
input() returns a string, which you are comparing to an integer. This will always return false.
You'll have to wrap input() in a call to int() for a valid comparison.
x = int(input("6 divided by 2 is"))
while x != 3:
print("Incorrect. Please try again.")
x = int(input("6 divided by 2 is"))
print(x)
Read more on int() here.
You are getting this error is because you are not parsing the input like so:
x = int(input("6 divided by 2 is"))
If you replace your inputer statement with that, it'll work.
input method gives the string. So you need to typecast to int as:
x = int(input("6 divided by 2 is"))
Here is my answer to your question
Guesses = 0
while(Guesses < 101):
try:
x = int(input("6 divided by 2 is: "))
if(x == 3):
print("Correct! 6 divide by 2 is", x)
break
else:
print("Incorrect. try again")
Guesses += 1
except ValueError:
print("That is not a number. Try again.")
Guesses += 1
else:
print("Out of guesses.")
I am assuming you wanted the user to input a number so i put your code into a while\else loop containing a try\except loop. The try\except loop ensures that if the users inputs a number, a ValueError will appear and it will inform them that what they inputted was not a number. The while\else loop ensures that the user will be inputted the question if the Guesses limit is no higher than 100. This code will ensure that if the user guesses the answer which is 3, the user will be prompted that they got the answer right and the loop will end; if the users guesses anything besides 3 (Number wise) the answer will be incorrect and the user will be prompted the question again; if the user guesses a string it will be classified as a ValueError and they will be notified that their answer wasn't a number and that the user has to try again.
Considering this was asked a long time ago, I'm assuming your probably forgot about this or you figured out the answer but if not try this and tell me if you like this answer. Thank :)
I actually tried this myself now with python 2.6, and did get an int without converting to int. For example, when I try the following:
x = input("6 divided by 2 is")
print "Your input is %s, %s" % (x, type(x))
I get the following:
6 divided by 2 is 2
Your input is 2, <type 'int'>
So is this a version issue? Or maybe an environment issue (I'm using OS X)?
What I do conclude is that it should be a good practice using previous recommendations using int().

Categories