While loop over numbers doesn't seem to be working [duplicate] - python

This question already has answers here:
Reading in integer from stdin in Python
(4 answers)
Closed 4 years ago.
I am new to python and I am trying run this piece of code, however, the while loop doesn't seem to be working. Any ideas?
def whilelooper(loop):
i = 0
numbers = []
while i < loop:
print "At the top i is %d" %i
numbers.append(i)
i += 1
print "numbers now:",numbers
print "At the bottom i is %d" %i
print "the numbers:",
for num in numbers:
print num
print "Enter a number for loop"
b = raw_input(">")
whilelooper(b)

Your input is inputted as a string type, but the comparator
while i < loop:
is expecting both i and loop to be of type int (for integer), in order to be able to compare them.
You can fix this by casting loop to an int:
def whilelooper(loop):
i = 0
numbers = []
loop = int(loop)
...

Related

How to take exact number of inputs from the user using Python? [duplicate]

This question already has answers here:
for or while loop to do something n times [duplicate]
(4 answers)
Closed 3 years ago.
I am relatively new to programming and especially to Python. I am asked to create a for loop which prints 10 numbers given by the user. I know how to take input and how to create a for loop. What bothers me, is the fact that with my program I rely on the user to insert 10 numbers. How can I make the program control how many numbers are inserted? Here is what I tried:
x = input('Enter 10 numbers: ')
for i in x:
print(i)
You need to
ask 10 times : make a loop of size 10
ask user input : use the input function
for i in range(10):
choice = input(f'Please enter the {i+1}th value :')
If you want to keep them after, use a list
choices = []
for i in range(10):
choices.append(input(f'Please enter the {i + 1}th value :'))
# Or with list comprehension
choices = [input(f'Please enter the {i + 1}th value :') for i in range(10)]
What if input is row that contains word (numbers) separated by spaces? I offer you to check if there are 10 words and that they are numbers for sure.
import re
def isnumber(text):
# returns if text is number ()
return re.match(re.compile("^[\-]?[1-9][0-9]*\.?[0-9]+$"), text)
your_text = input() #your input
splitted_text = your_text.split(' ') #text splitted into items
# raising exception if there are not 10 numbers:
if len(splitted_text) != 10:
raise ValueError('you inputted {0} numbers; 10 is expected'.format(len(splitted_text)))
# raising exception if there are any words that are not numbers
for word in splitted_text:
if not(isnumber(word)):
raise ValueError(word + 'is not a number')
# finally, printing all the numbers
for word in splitted_text:
print(word)
I borrowed number checking from this answer

User input requires int but accepts variable name [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
How can I check if a string represents an int, without using try/except?
(23 answers)
Closed 4 years ago.
I've written a number guessing game in Python 2.7.14 and encountered something odd:
I ask for an integer as input and check for that, but the name of the variable (here "a") is always accepted, although no other strings or characters are accepted. Isn't this an issue when the user can enter variable names even though they are not allowed?
My code is:
from random import randint
a = randint(0,10)
b = input("enter a number between 0 and 10 ")
print "you entered :", b
if type(b) != int:
print "please enter only integers"
else:
if b < a:
print "b is smaller than a"
elif b == a:
print "b is equal to a"
else:
print "b is NOT smaller than a"
print "number was", a

why while loops does not stop? [duplicate]

This question already has answers here:
Python: Problem with raw_input reading a number [duplicate]
(6 answers)
Closed 5 years ago.
I am trying to print "count" , when count is smaller than my input value , but when I give the input value for X, it loos forever.
Can anybody tell me why ?
count = 0
x= raw_input()
while count <x :
print (count )
count +=1
By looking at the behaviour of the comparison operators (<, >, ==, !=), you can check that they treat integers as being smaller than non-empty strings. raw_input() returns a string (rather than an integer as you expected), hence your while loops indefinitely. Just switch to input():
count = 0
x = input()
while count < x:
print(count)
count += 1
Alternatively, you can use int(raw_input()), but I always use (and prefer) the former. All this is assuming you use Python 2.
Cast the input as an int so that the loop can increment it:
count = 0
x = int(raw_input())
while count <x :
print (count )
count +=1

Infinite loop in python from user input

I am writing Python code counting up to the number the user provides, but I get into an infinite loop when running the code. Please note I tried commenting out lines 3 and 4 and replaced "userChoice" with a number, let's say for example 5, and it works fine.
import time
print "So what number do you want me to count up to?"
userChoice = raw_input("> ")
i = 0
numbers = []
while i < userChoice:
print "At the top i is %d" % i
numbers.append(i)
i = i + 1
print "Numbers now: ", numbers
print "At the bottom i is %d" % i
time.sleep(1)
print "The numbers: "
for num in numbers:
print num
time.sleep(1)
raw_input returns a string, not int. You can fix the issue by converting user response to int:
userChoice = int(raw_input("> "))
In Python 2.x objects of different types are compared by the type name so that explains the original behavior since 'int' < 'string':
CPython implementation detail: Objects of different types except numbers are ordered by their type names; objects of the same types that don’t support proper comparison are ordered by their address.
You are comparing a number with a string in:
while i < userChoice:
The string will always be greater than the number. At least in Python 2 where these are comparable.
You need to turn userChoice into a number:
userChoice = int(raw_input("> "))

Python passing arguments from console [duplicate]

This question already has answers here:
python: while loop not checking the condition [closed]
(3 answers)
Closed 8 years ago.
In the following code:
def foo(n):
print "n value before if:",n #displays given num
if n <= 2:
print "n value:",n #not displayed even n is less than 2
num = raw_input()
print foo(num)
The if statement does not execute on giving inputs less than 2 for num.
So, why is if statement not executing?
raw_input returns a string, you are then comparing it to an integer.
Try converting it to an int:
num = int(raw_input())

Categories