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

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.

Related

why this python code dosent work even its correct? [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 1 year ago.
I wrote a little programm in python which has to give the biggest nummber of 2 inputs. The code is following:
a = input("insert a")
b = input("insert b")
if a < b:
print(b)
else:
print(a)
the problem is, this Code works with some numbers but not with all. Foe example if i insert a=5 and b=10 or b=5 and a=10 it would always give me 5 back, even 10 is bigger than 5.
I dont know if the problem is from my Code or its a bug in Pycharm beacaue i tried it in Pycharm in visual Studi Code and it gave me the same result and i dont understand why. If somone can explain this to me, i would be very grateful
the issue is cause by input() returning a string not a number, this causes the evaluation to compare alphabetically not numerically. you can cast the variables to int like so
a = int(input("insert a"))
b = int(input("insert b"))
if a < b:
print(b)
else:
print(a)
Since Python 3, input() returns a string which you have to explicitly convert to ints, with int, like this
x = int(input("Enter a number: "))
y = int(input("Enter a number: "))
For values that can have a fractional component, the type would be float rather than int:
x = float(input("Enter a number:"))

Getting " 'NoneType' Object has no attribute 'isdigit' " error on my code

with the code I'm trying to accomplish is that I'm asking the user to for a number between 1 and 12 and then display the times table for that number.
The while loop checks if it's not a number or if its less than 1 or more than 12 then it will loop until it input is correct. However I get the error (written on the title)
Any ideas how to fix this?
user_input = print('Input number between 1-12: ')
#While loop to keep checking the following conditions
while (not user_input.isdigit()) or (int(user_input < 1) or int(user_input > 12)):
print("Please input a number between 1-12")
user_input = print("Input selection >> ")
#Now convert user_input into an int
user_input = int(user_input)
print('------------------------------------------')
print()
print(f'This is the {user_input} times table')
print()
for i in range(1,13):
print(f'{i} x {user_input} = {i*user_input}')
user_input = input('Input number between 1-12: ')
#While loop to keep checking the following conditions
while (not user_input.isdigit()) or (int(user_input)< 1 or int(user_input) > 12):
list of issues:
you printed instead of input to receive input from the user
you attempted to use < on instances of str and int, instead you should check this outside the int conversion to make sure that you trying to use < which both operands are int
user_input = print('Input number between 1-12:')
The above line only print out Input number between 1-12: to the console, it does not ask for the user to input anything. Since the print() function displays the string inside it and returns None, you get the error that you're getting.
If you want to take user input, then use the input() function like,
user_input = input("Input number between 1-12: ")
The above line will prompt the user to input something while also displaying the text

How do I get the user to input an int rather than a float?

I'm writing a program that takes in a value from the user, in the console, and I'm casting it to an int like so:
num = int(input("Enter a number: "))
I need my program to work with ints only. This works to convert an actual int entered into the console to an int I can use in the program, but if the user enters a float, like 3.1, then it doesn't cast to an int by truncating or rounding up for example.
How do I get the user to input an int rather than a float? Or how do I convert a floating point input to an int?
You can use a try catch block to ensure they only give you an int:
while True:
try:
num = int(input("Enter a number: "))
#do something with num and then break out of the while loop with break
except ValueError:
print("That was not a number, please do not use decimals!")
When ValueError (when it fails to convert to int) is excepted it goes back to asking for a number which once you get your number you can do things with said number or break out of the loop then and use num elsewhere.
You can use a try except to test if a user input is a whole number. Example code:
while True:
try:
value=int(input("Type a number:"))
break
except ValueError:
print("This is not a whole number.")
This code will loop back to the start if a user inputs something that is not an int.
So int() of a string like "3.1" doesnt work of course. But you can cast the input to a float and then to int:
num = int(float(input("Enter a number: ")))
It will always round down. If you want it to round up if >= .5:
num = float(input("Enter a number: "))
num = round(num, 0)
num = int(num)
You can simply use eval python built-in function. num = int(eval(input("Enter a number: "))).
For converting string into python code and evaluating mathimatical expressions, eval function is mostly used. For example, eval("2 + 3") will give you 5. However, if you write "2 + 3", then u will get only '2 + 3' as string value.
Try:
num = int(float(input("Enter number: ")))
and the float will be rounded to int.
You can also add a try...except method to give error to user if the number cannot be converted for any reason:
while True:
try:
num = int(float(input("Enter number: ")))
print(num)
break
except ValueError:
print("This is not a whole number")
use abs() it returns the absolute value of the given number

iPython crashes on printing Fibonacci Series

While attempting to print a fibonacci series using tuples, iPython tends to crash.
Here is the code I am trying to execute.
n = raw_input("Please enter a number: ")
a = 0
b = 1
while b < n:
(b,a) = (a,b+a)
print b
However, if I replace n with a number (eg. 20, 100, 1000), it runs smoothly. I also tried to run this code in Pycharm, with similar results. Pycharm ran the code, with a huge stream on numbers being generated, and a warning which read:
Too much output to process
What causes this crash?
You forgot to turn the string n you get from raw_input into an integer.
Since the comparison is done by type name in this case b < n will always be True.
Use n = int(raw_input("Please enter a number: "))
Because the return value of raw_input is str, you should try
n = int(raw_input("Please enter a number: ")) instead.

python string and integer comparison

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

Categories