Infinite loop in python from user input - python

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("> "))

Related

Finding Even Numbers In Python

I have a Python assignment that is as following: "Write a complete python program that asks a user to input two integers. The program then outputs Both Even if both of the integers are even. Otherwise the program outputs Not Both Even."
I planned on using an if and else statement, but since I'm working with two numbers that have to be even instead of one, how would I do that?
Here is how I would do it if it was one number. Now how do I add the second_int that a user inputs???
if first_int % 2 == 0:
print ("Both even")
else: print("Not Both Even")
You can still use an if else and check for multiple conditions with the if block
if first_int % 2 == 0 and second_int % 2 == 0:
print ("Both even")
else:
print("Not Both Even")
An even number is an integer which is "evenly divisible" by two. This means that if the integer is divided by 2, it yields no remainder. Zero is an even number because zero divided by two equals zero. Even numbers can be either positive or negative.
Use raw_input to get values from User.
Use type casting to convert user enter value from string to integer.
Use try excpet to handle valueError.
Use % to get remainder by dividing 2
Use if loop to check remainder is 0 i.e. number is even and use and operator to check remainder of tow numbers.
code:
while 1:
try:
no1 = int(raw_input("Enter first number:"))
break
except ValueError:
print "Invalid input, enter only digit. try again"
while 1:
try:
no2 = int(raw_input("Enter second number:"))
break
except ValueError:
print "Invalid input, enter only digit. try again"
print "Firts number is:", no1
print "Second number is:", no2
tmp1 = no1%2
tmp2 = no2%2
if tmp1==0 and tmp2==0:
print "Both number %d, %d are even."%(no1, no2)
elif tmp1==0:
print "Number %d is even."%(no1)
elif tmp2==0:
print "Number %d is even."%(no2)
else:
print "Both number %d, %d are NOT even."%(no1, no2)
Output:
vivek#vivek:~/Desktop/stackoverflow$ python 7.py
Enter first number:w
Invalid input, enter only digit. try again
Enter first number:4
Enter second number:9
Firts number is: 4
Second number is: 9
Number 4 is even.

How to compare inputted numbers without storing them in list

Note: This is not my homework. Python is not taught in my college so i am doing it my myself from MITOCW.
So far i have covered while loop, input & print
Q) Write a program that asks the to input 10 integers, and then prints the largest odd number that was entered. If no odd number was entered it should print a message to the effect
How can i compare those 10 number without storing them in some list or something else? Coz i haven't covered that as if yet.
print "Enter 10 numbers: "
countingnumber=10
while countingnumber<=10:
number=raw_input():
if number % 2 == 0:
print "This is odd"
countingnumber=countingnumber+1
else:
print "This is even. Enter the odd number again"
i think the program will look something like this. But this has some unknown error & How can i compare all the numbers to get the largest odd number without storing those 10 numbers in the list.
print "Enter 10 numbers: "
countingNumber = 1
maxNumber = 0
while countingNumber<=10:
number=int(raw_input())
if (number % 2 == 0):
countingNumber = countingNumber+1
if (maxNumber < number):
maxNumber = number
else:
print "This is even. Enter the odd number again"
print "The max odd number is:", maxNumber
you can just define a maxnum variable and save the max in it! also you must use int(raw_input()) instead raw_input()
print "Enter 10 numbers: "
maxnum=0
for i in range(10):
number=int(raw_input())
if number%2 == 0:
print "This is odd"
if number>maxnum:
maxnum=number
else:
print "This is even. Enter the odd number again"
print "max odd is :{0}".format(maxnum)
DEMO:
Enter 10 numbers:
2
This is odd
4
This is odd
6
This is odd
8
This is odd
12
This is odd
14
This is odd
16
This is odd
100
This is odd
2
This is odd
4
This is odd
max odd is :100
Whenever I do input, I like to make sure I don't leave room for human error giving me bugs.
Because I put in extra checks I break code into a lot of separate function. This also gives code the quality of being non-coupled. ie) You can reuse it in other programs!!
def input_number():
while true:
input = raw_input("Enter Value: ")
if not input.isdigit():
print("Please enter numbers only!")
else:
return int(input)
Designing the input function in this fashion gives the code no opportunity to crash. We can now use it in a function to get odd numbers!
def input_odd_number():
while true:
input = input_number()
if input % 2 == 0:
print("Please enter odd numbers only!")
else:
return input
Now we can finally move onto the main code. We know we need ten numbers so lets make a for loop. We also now we need to hold onto the largest odd number, so lets make a variable to hold that value
def largest_odd(count = 10): // its always nice to make variables dynamic. The default is 10, but you can change it when calling!
max_odd = input_odd_number() // get the first odd number
for i in range(count - 1): // we already found the first one, so we need 1 less
new_odd = input_odd_number()
if new_odd > max_odd:
max_odd = new_odd
print("The largest odd value in '{}' inputs was: {}".format(count, max_odd)
In your solution are multiple flaws.
A syntax error: The colon in number=raw_input():.
raw_input returns a string and you have to cast it to an int.
Your while loop just runs one time, because you start with 10 and compare 10 <= 10. On the next iteration it will be 11 <= 10 and finishes.
Also you have mixed odd an even. even_number % 2 gives 0 and odd_number % 2 gives 1.
To get the biggest value you only need a additional variable to store it (See biggest_number in my solution). Just test if this variable is smaller then the entered.
You ask again if the number is odd, but you should take every number and test only against odd numbers.
A working solution is:
print "Enter 10 numbers"
count = 0
max_numbers = 10
biggest_number = None
while count < max_numbers:
number=int(raw_input("Enter number {0}/{1}: ".format(count + 1, max_numbers)))
if number % 2 == 1:
if biggest_number is None or number > biggest_number:
biggest_number = number
count += 1
if biggest_number is None:
print "You don't entered a odd number"
else:
print "The biggest odd number is {0}".format(biggest_number)
If you wonder what the format is doing after the string take a look in the docs. In short: It replaces {0} with the first statement in format, {1} with the second and so on.
here is the correct code for that:
print "Enter 10 numbers: "
countingnumber=1
MAX=-1
while countingnumber<=10:
number=int(raw_input())
if number%2==1:
if number>MAX:
MAX=number
if MAX==-1:
print "There Weren't Any Odd Numbers"
else:
print MAX
here are some notes about your errors:
1- you should cast the raw input into integer using int() function and the column after calling a function is not needed and therefor a syntax error
2- your while loop only iterates once because you initial counting number is 10 and after one iteration it would be bigger than 10 and the while body will be skipped.
3-an even number is a number that has no reminder when divided by 2 but you wrote it exactly opposite.
4- you don't need to print anything in the while loop, you should either print the biggest odd number or print "There Weren't Any Odd Numbers".
5- an additional variable is needed for saving the maximum odd number which is MAX.
Last note: in the code provided above you can combine the two ifs in the while loop in to one loop using 'and' but since you said you are a beginner I wrote it that way.

How do i order the numbers a user inputs?

I am basically wondering how i can store the users inputs and put them in order from least to greatest to help them find median mode or range.
from __future__ import division
amtnum = 0
sumofnums = 0
print "Hello, This program will help find the mean of as many numbers as you want."
useramtnum = input("How many numbers will you need to enter: ")#asks user to say how many numbers there are
while amtnum < useramtnum: #Tells program that while the amount of numbers is less than the users input amt of numbers to run.
amtnum = amtnum + 1 #Tells that each time program asks for number add one to amt of numbers
entnum = (int(raw_input("Enter a number:"))) #Asks user for number
sumofnums = entnum + sumofnums #Adds users number to all values
print "The amount of your numbers added up were:", sumofnums
print "The average/mean of your numbers were:", (sumofnums/useramtnum)
put 'em in a list and sort it
mylist = []
while ...
mylist.append(entnum)
mylist.sort()
print mylist
Utilize the basic data structure called a list!
Before your while loop, create a list (aka array)
user_input_list = []
After you get the individual number from the user in the while loop, add the input to the list (in the while loop)
user_input_list.append(entnum)
After the while loop, sort the list (it will sort in place)
user_input_list.sort()
Then the list has every input from the user in sorted order, least to greatest.
To access the last item in the list, use array accessors.
user_input_list[-1]
To access median, utilize the fact you can use the length of the list. Access the length(list)/2 item
user_input_list[int( len(user_input_list) / 2)] #int cast used to remove decimal points
I am by no means a Python expert (as in, this is like my third python program), but I think it's generally easier to call functions, be it in Python or in any other language. It makes code more readable.
These are all basic math functions, so I don't feel I deprived you of knowledge by just writing them. I did, however, leave the range function for you to write. (Since mylist is sorted, I'm sure you can figure it out.)
This allows the user to continually enter numbers and have the mean, median, and mode spit back at them. It doesn't handle non-integer input.
from collections import Counter
from decimal import *
def getMode(l):
data = Counter(l)
mode = data.most_common(1)
print "mode:", mode
def getMean(l):
length = len(l)
total = 0
for x in l:
total = total + x
mean = Decimal(total) / Decimal(length)
print "mean:", mean
def getMedian(l):
median = 0
length = len(l)
if (length % 2 == 0):
median = (l[length/2] + l[length/2 - 1])/2.0
else:
median = l[length/2]
print "median:", median
mylist = []
print "Enter numbers to continually find the mean, median, and mode"
while True:
number = int(raw_input("Enter a number:"))
mylist.append(number)
mylist.sort()
getMean(mylist)
getMedian(mylist)
getMode(mylist)
Solution to solve your problem :
Use a list : More on Lists
Example :
numbers = []
while amount < counter:
...
numbers.append(num)
print sorted(numbers)
You can take a look at modification of your code below.
numbers = []
print "Hello, This program will help find the \
mean of as many numbers as you want."
while True:
try:
counter = input("How many numbers will you need to enter: ")
except:
print "You haven't entered a number."
else:
break
amount = 0
while amount < counter:
try:
num = input("Enter a number: ")
except:
print "You haven't entered a number."
else:
amount += 1
numbers.append(num)
print "The amount of your numbers added up were:", (sum(numbers))
print "The average/mean of your numbers were:", ( (sum(numbers)) / counter)
print "My list not in order:", numbers
print "My list in order:", sorted(numbers)

Flowchart in Python

I need to write a prog in Python that accomplishes the following:
Prompt for and accept the input of a number, either positive or negative.
Using a single alternative "decision" structure print a message only if the number is positive.
It's extremely simply, but I'm new to Python so I have trouble with even the most simple things. The program asks for a user to input a number. If the number is positive it will display a message. If the number is negative it will display nothing.
num = raw_input ("Please enter a number.")
if num >= 0 print "The number you entered is " + num
else:
return num
I'm using Wing IDE
I get the error "if num >= 0 print "The number you entered is " + num"
How do I return to start if the number entered is negative?
What am I doing wrong?
Try this:
def getNumFromUser():
num = input("Please enter a number: ")
if num >= 0:
print "The number you entered is " + str(num)
else:
getNumFromUser()
getNumFromUser()
The reason you received an error is because you omitted a colon after the condition of your if-statement. To be able to return to the start of the process if the number if negative, I put the code inside a function which calls itself if the if condition is not satisfied. You could also easily use a while loop.
while True:
num = input("Please enter a number: ")
if num >= 0:
print "The number you entered is " + str(num)
break
Try this:
inputnum = raw_input ("Please enter a number.")
num = int(inputnum)
if num >= 0:
print("The number you entered is " + str(num))
you don't need the else part just because the code is not inside a method/function.
I agree with the other comment - as a beginner you may want to change your IDE to one that will be of more help to you (especially with such easy to fix syntax related errors)
(I was pretty sure, that print should be on a new line and intended, but... I was wrong.)

Python program not accepting decimal raw input

I am working on small python payroll project where you enter employee name, wage, and hours worked. When I enter decimals for the wage input, I am getting "invalid entry" because of my exception handling. Why are decimals being returned as invalid? Also, how can I loop this program so that it keeps the same 3 questions until the user types "Done"?
Any help will be greatly appreciated!
Thanks!
import cPickle
def getName():
strName="dummy"
lstNames=[]
strName=raw_input("Enter employee's Name: ")
lstNames.append(strName.title() + " \n")
def getWage():
lstWage=[]
strNum="0"
blnDone=False
while blnDone==False: #loop to stay in program until valid data is entered
try:
intWage=int(raw_input("Enter employee's wage: "))
if intWage >= 6.0 and intWage <=20.0:
lstWage.append(float(strNum)) #convert to float
blnDone=True
else:
print "Wage must be between $6.00 and $20.00"
except(ValueError): #if you have Value Error exception. Explicit on error type
print "Invalid entry"
def getHours():
lstHours=[]
blnDone=False
while blnDone==False: #loop to stay in program until valid data is entered
try:
intHrs=int(raw_input("Enter number of hours worked: "))
if intHrs >= 1.0 and intHrs <=60.0:
blnDone=True
else:
print "Hours worked must be 1 through 60."
except(ValueError): #if you have Value Error exception. Explicit on error type
print "Invalid entry"
def getDone():
strDone=""
blnDone=False
while blnDone==False:
try:
srtDone=raw_input("Type \"DONE\" if you are finished entering names, otherwise press enter: ")
if strDone.lower()=="done":
blnDone=True
else:
print "Type another empolyee name"
except(ValueError): #if you have Value Error exception. Explicit on error type
print "Invalid entry"
##### Mainline ########
strUserName=getName()
strWage=getWage()
strHours=getHours()
srtDone1=getDone()
Here's the core of it:
>>> int("4.3")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '4.3'
You can't convert a string to an integer if it's not an integer. So when you do intWage=int(raw_input("Enter employee's wage: ")) it throws the ValueError. Perhaps you should convert it directly to float.
Because you're converting the input to int:
intWage=int(raw_input("Enter employee's wage: "))
You are assuming that the wage is an integer, which by definition does not have a decimal place. Try this:
intWage=float(raw_input("Enter employee's wage: "))
Try using
intWage=int(float(raw_input("Enter employee's wage: ")))
This will accept a decimal number as input.
Error w/ Floats
As others said before, you are assuming the input will be a float. Either use float() or eval()instead of int():
intWage = float(raw_input("Enter employee's wage: "))
Or use input() instead of int(raw_input()):
intWage = input("Enter employee's wage:")
Both will accomplish the same thing. Oh, and change intWage to floatWage atleast, or even better, don't use Hungarian Notation.
The Code
As for your code, I did a couple of things:
Used break and/or return to terminate loops instead of keeping track of booleans (that's the whole purpose of the break and continue statements)
Changed intWage to floatWage
Rewrote number comparisons in a more concise way (x <= y and x >= z can be written as z >= x >= y)
Added return statements. I don't get why you didn't put them yourself, unless you wanted to assign None to strUserName, strWage and strHours)
Added a loop as you requested when asking for an employee's details.
Modified getDone() to work w/ the loop.
import cPickle
def getName():
strName = "dummy"
lstNames = []
strName = raw_input("Enter employee's Name: ")
lstNames.append(strName.title() + " \n")
return strName
def getWage():
lstWage = []
strNum = "0"
while True: #Loop to stay in program until valid data is entered
try:
floatWage = float(raw_input("Enter employee's wage: "))
if 6.0 <= floatWage <= 20.0:
lstWage.append(floatWage)
return floatWage
else:
print "Wage must be between $6.00 and $20.00"
except ValueError: #Catches ValueErrors from conversion to float
print "Invalid entry"
def getHours():
lstHours = []
while True: #loop to stay in program until valid data is entered
try:
intHrs=int(raw_input("Enter number of hours worked: "))
if 1.0 <= intHrs <= 60.0:
return intHrs
else:
print "Hours worked must be 1 through 60."
except ValueError: #Catches ValueErrors from conversion to int
print "Invalid entry"
def getDone():
strDone = ""
while True:
srtDone = raw_input('Type "DONE" if you are finished entering names, otherwise press enter: ')
if strDone.strip().lower() == "done":
return True
else:
print "Type another empolyee name"
while not getDone():
strUserName = getName()
strWage = getWage()
strHours = getHours()
An Example of break and continue
The break statements inside a loop (for and while) terminate the loop and skip all 'else' clauses (if there are any).
Thecontinue statements skips the rest of the code in the loop and the continues the loop as if nothing happened.
The else clause in a for...else construct, executes its code block when the loop exhausted all the items and exited normally, i.e., when it's not terminated by break or something.
for no in range(2, 10):
for factor in range(2, no):
if no % factor == 0:
if factor == 2:
print "%d is even" % no
continue
# we want to skip the rest of the code in this for loop for now
# as we've already done the printing
print "%d = %d * %d" % (no, factor, n/x)
break
# We've asserted that the no. isn't prime,
# we don't need to test the other factors
else:
# if 'break' wasn't called
# i.e., if the loop fell through w/o finding any factor
print no, 'is a prime number'

Categories