Why do I appear to have an infinite loop? - python

This is part of a tutorial. My goal was to take an input from user and then increment it while a condition is true.
inputNum = raw_input("What is max number?")
def incrementF(greatest):
i = 0
numbers = []
while i < greatest:
print "At the top of the list numbers 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
incrementF(inputNum)
When I run the script and type anything in for inputNum, rather than a few lines of output, I appear to run into an infinite loop.
For example, is the raw input prompt gave 10, I'd have expected to see something like:
At the top of the list numbers is 0,
Numbers now: 0,
0
At the top of the list numbers is 1,
Numbers now: 1,
1
I've read over my script several times and cannot see. I suspect it could have something to do with indenting? But I'm not sure.

As quoted in the docs for raw_input:
The function then reads a line from input, converts it to a string
(stripping a trailing newline), and returns that.
So, greatest will be a string because you used raw_input to get it.
Furthermore, in Python 2.x, strings are always evaluated as being greater than integers*:
>>> 1 < 'a'
True
>>> 100000000000 < 'a'
True
>>>
This means that the condition of your while-loop will always evaluate to True because greatest will always be evaluated as being greater than i. Thus, you get an infinite loop.
You can fix this problem simply by making greatest an integer like i:
inputNum = int(raw_input("What is max number?"))
*Note: If you would like some more information on this, see How does Python compare string and int?

Related

How to say if this number is equal or less than X the change it to X

I am trying to make code that can round numbers i am starting off small and don't know why but getting errors and am trying to state "if this number is less or equal to 4 change the value to zero and print it, otherwise if it is greater than or eqaul to 5 the change it to a 10"
import math
import random
def help(num):
if num <= 4 num = "0"
else:
if num >= 5 num = "10"
result = help(5)
print(result)
If you aren't already, try using an IDE (I use PyCharm). These will highlight errors in your code and give suggestions as to how you may fix or handle them.
First of all, python requires proper formatting of whitespace to run correctly. Here's a useful StackOverflow link to give you an idea of what I mean.
Secondly, when you want to refer to a real number value, (i.e The mathematical number 0 as opposed to the letter representing 0), don't use quotes. When you use quotes you tell python "this is a word made of letters" instead of a number made of digits.
Third, you are missing the colon : at the end of your if and else statements. These are just necessary syntax.
Fourth, you need a return statement in your help() function if you want it to return a value.
Lastly, ensure that the last two lines are not within the method help() if you want them to run when the .py file is run.
Here's your modified code:
import math
import random
def help(num):
if num <= 4 :
num = 0
elif num >= 5:
num = "10"
return num
result = help(5)
print(result)
You don't need to be checking for greater or equal to 5 in this case if you've got just two outcomes.
def help(num):
return 0 if num <=4 else 10
result = help(5)
print(result)

how do i print a string with a variable that contains a float

I'm very new to python and I want to print the average variable as a float after the string but I keep getting an error. How can I fix this. Edit: I've added the start of my code in case it helps
numbers = input ("Enter a list of numbers with a comma \",\" in between ")
total_num = 0
for num in numbers:
total_num += 1
average = float(sum(numbers)/total_num)
print ("The average is " , average)
This is the error I get
TypeError: unsupported operand type(s) for +: 'int' and 'str'
When I try this with python 2.6 it worked perfectly but I'm using python 3.7.1 and it has stopped working
The error comes from the sum(numbers). input() function returns a string, and sum() function tries to iterates and sum the characters of the string...
(It worked in python 2 as Python 2's input() function evaluates the string, and in this case returned a list of numbers ...)
You need to separate the numbers (using split(',')) and convert the list of strings to float.
This will work:
numbers = input ("Enter a list of numbers with a comma \",\" in between ")
numbers = [float(x) for x in numbers.split(',')]
total_num = 0
for num in numbers:
total_num += 1
average = float(sum(numbers)/total_num)
print ("The average is " , average)
(The code can be improved in many ways, I focused on the problem described ...)
In Python 2, input() magically applied the built-in eval() function to the string the user enters.
But that was thought to be a "security risk", so in Python 3 input() returns the string the user entered, unevaluated.
So, e.g., if the user typed
1, 2, 3
under Python 2, input() returned the tuple (1, 2, 3). but under Python 3 it returns the string "1, 2, 3". Under Python 3, you'll have to apply eval() to that string yourself (understanding that it's "a security risk", since eval() can end up doing anything at all, depending on what the user typed).
Edit 2:
Python2's input was an unsafe method as it applied eval on your input value.
Python3's input uses what was known in Python2 as raw_input.
Therefore, in order to parse your numbers the way you receive them now:
numbers = input ("Enter a list of numbers with a comma \",\" in between ")
numbers = [int(n) for n in numbers.split(',')]
or even better, to work with input that has whitespaces and commas and just easily ignore them:
import re
numbers = input ("Enter a list of numbers with a comma \",\" in between ")
numbers = [int(n) for n in re.findall("\d+", numbers)]
Edit:
Seems like the origin of your problem has to do something with your `numbers` list.
If it's a list of numbers represented in strings, you will have to cast them to ints (or floats) first:
sum(int(n) for n in numbers)
sum(float(n) for n in numbers)
so it will be:
average = sum(float(n) for n in numbers)/len(numbers) # Python3 division result by default are float
---
Other printing ways:
You can simply use f-string on Python3.6+:
average = float(sum(numbers)/total_num)
print(f"The average is {average}")
On older Python versions, you can either:
print("The average is {}".format(average))
print("The average is %f" % average) # Float formatted
print("The average is %d" % average) # Int formatted
print("The average is " + str(average))
And finally, your print should have worked as well:
print("The average is", str(average))
Your error is because numbers is a single string.
You need to split the string and then cast the entries to an int. That will give you this for the first two lines:
numbers = input("Enter a list of numbers with a comma \",\" in between ").split(',')
numbers = [int(i) for i in numbers]
You can then just delete the entire for loop and instead just use len(numbers)
Final Code
numbers = input("Enter a list of numbers with a comma \",\" in between ").split(',')
numbers = [int(i) for i in numbers]
total_num = 0
average = float(sum(numbers) / len(numbers))
print("\n The average is ", average)

How do you convert a string to an integer in Python

"""
A trimorphic number is a number whose cube ends in the number itself.
For example:
Input: 4
Output: true (4^3 is 64, which ends in 4)
Input: 24
Output: true (24^3 = 13824)
Input: 249
Output: true (249^3 = 15438249)
Write a program to check if the user input is a trimorphic number or not.
"""
num = int(input("Enter a number:"))
print(num)
num_cube = pow(num, 3)
str(num_cube)
print(num_cube[len(num_cube) - 1:] == num)
I tried running the code and I got a TypeError at line 22 (the last line) even though I converted the variable num_cube to a string in order to slice it. Why does it not work?
You should use the endswith function to check whether the last "n" characters in the cube are equal to the string representation of the number you are passed.
You could thus do:
print(str(num_cube).endswith(num))
The way you have currently implemented it, you are "hard coding" the expected length of the number read from the stdin and are thus assuming it to always be of length 1.
To correct your code, you would do the following:
>>> num = "24"
>>> num_cube = str(pow(int(num), 3))
>>> num_cube[len(num_cube) - len(num):] == num
True
>>> num_cube[-len(num):] == num # negative indexing
True
str(num_cube) is not assigned, so you are converting it but still using num_cube which is an int, hence the TypeError. Also, you need to compare it to another string, not to to num which is another integer:
print(str(num_cube)[-3:] == str(num))

Can anyone figure out this code for me?

import random
print "Welcome to the number guesser program. We will pick a number between 1 and 100 and then ask you to pick a number between 1 and 100. If your number is 10 integers away from the number, you win!"
rand_num = random.randint(1, 100)
user_input = raw_input('Put in your guess:').isdigit()
number = int(user_input)
print number
if abs(rand_num - number) <= 10:
print "Winner"
else:
print "Loser"
Whenever I try to run this code, the computer always generates the number 1. And if I put in a number that is 10 (or less) integers away from one it will still display the else statement. I will have my gratitude to whoever can solve my predicament. I am new to python try to keep your answers simple please.
raw_input returns a string you entered as input. isdigit() checks whether a string is a digit or not and returns True or False.
In your code you're assigning the return value of isdigit to user_input So, you get either True or False. Then you convert it to a number, thus getting either one or zero. This is not what you want.
Let user_input be just a result of raw_input. Then check whether it is a valid number with user_input.isdigit(). If it's not a number, print an error message and exit (or re-ask for input), else convert user_input to an integer and go on.
The problem is product by this sentenc:
user_input = raw_input('Put in your guess:').isdigit().
The return value of isdigit() is True or False. When you enter 1 or any digit number, it will return True(True=1,False=0), so you will always get 1, if you enter digit. You can change like this:
import random
print "Welcome to the number guesser program.
We will pick a number between
1 and 100 and then ask you to pick a number
between 1 and 100. If your number is 10 integers
away from the number, you win!"
rand_num = random.randint(1, 100)
user_input= raw_input('Put in your guess:')
is_digit = user_input.isdigit()
if is_digit==True:
number = int(user_input)
print number
if abs(rand_num - number) &lt= 10:
print "Winner"
else:
print "Loser"
else:
print 'Your input is not a digit.'
Look at this line:
user_input = raw_input('Put in your guess:').isdigit()
The function raw_input gives you user input, but then you call isdigit and as consequence in your variable user_input you get result of isdigit. So, it has boolean value.
Then in
number = int(user_input) you cast it to integer type. In python true is 1 and false is 0. That's why you always get 1.

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.

Categories