iPython crashes on printing Fibonacci Series - python

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.

Related

Fixing While Loops Python

We want to create a program that prompts the user to enter a number between 1 and 10. As long as the number is out of range the program reprompts the user for a valid number. Complete the following steps to write this code.
a.Write a line of code the prompts the user for number between 1 and 10.
number = float(input("Enter a number between 1 and 10: "))
b. Write a Boolean expression that tests the number the user entered by the code in step "a." to determine if it is not in range.
x = (number > 10 or number < 1)
c.Use the Boolean expression created in step b to write a while loopthat executes when the user input is out of range. The body of the loop should tell the user that they enteredan invalid number and prompt them for a valid number again.
while x == True:
print("you printed an invalid number")
number = float(input("please enter the number again, this time between 1 and 10"))
d.Write the code that prints a message telling the user that they entered a valid number.
if x == False:
print("wow, you printed a number between 1 and 10!")
I answered the stuff for the question, but my problem is that whenever the user enters a wrong number on their first try and a correct number on their second try, the program still considers it as an invalid input. How do I fix this???
Rewrite this line in the while loop:
x = (number > 10 or number < 1)
so it becomes
while x == True:
print("you printed an invalid number")
number = float(input("please enter the number again, this time between 1 and 10"))
x = (number > 10 or number < 1)
This changes the value of x so it doesn't stay at True
If you use a while True construct, you won't need to repeat any code. Something like this:
LO, HI = 1, 10
while True:
input_ = input(f'Enter a number between {LO} and {HI}: ')
try:
x = float(input_)
if LO <= x <= HI:
print(f'Wow! You entered a number between {LO} and {HI}')
break
print(f'{input_} is not in range. Try again')
except ValueError:
print(f'{input_} is not a valid number. Try again')
Note:
When asking for numeric input from the user, don't assume that their input can always be converted properly. Always check
The following code snippet should do all you need:
number = float(input("Please input a number: "))
while (number > 10 or number < 0):
number = float(input("Error. Please input a new number: "))
Use an infinite loop, so that you can prompt for the input only once.
Use break to terminate the loop after the number in the correct range is entered.
Use f-strings or formatted string literals to print the message.
while True:
num = float(input('Enter a number between 1 and 10: '))
if 1 <= num <= 10:
print('Wow, you printed a number between 1 and 10!')
break
else:
print(f'You printed an invalid number: {num}!')

Finding Sum of Variables in Python

I am working on a program that requires the user to enter a number and will continue to loop until a positive number is given. When a positive number is given, it will alert the user and present them with the sum of the digits of their number. However, I thought I had written my code correctly, but it is giving me an incorrect answer. What have I done wrong and how can I fix this?
user_input = float(int(input("Please Enter Your Number:")))
s = 0
while user_input < 0:
float(int(input("Please Enter Another Number: ")))
if user_input > 0:
s += user_input%10
user_input //= 10
print("You've entered a positive number! The sum of the digits is: ", s)
Four things:
Not sure why you storing the input as float, int should suffice.
If you give a negative input, it will enter the while loop. However, in the while loop, you are not actually assigning the new input to user_input. Fix this by adding user_input =
The while loop guarantees user_input is >= 0, so if user_input > 0: is unnecessary.
Probably the most important, to calculate the sum of digits, you need to repeatedly divide and sum, not just do it once. So, add a while loop.
Final code:
user_input = int(input("Please Enter Your Number: "))
s = 0
while user_input < 0:
user_input = int(input("Please Enter Another Number: "))
while user_input:
s += user_input % 10
user_input //= 10
print("You've entered a positive number! The sum of the digits is: ", s)
The if statement is generally used to decide if something should be done once.
If you want to keep going until user_input becomes zero, you'll need a while.
Also, I'm not entirely certain why you're storing the number as a float, especially when you make that from an int anyway. It may as well just be an int.
Additionally, you're loop to re-enter the value if it was negative doesn't actually assign the new value to the variable.
And you probably also want to outdent the print statement lest it be done on every iteration of the loop you're about to add.
Of course, some may suggest a more Pythonic way of summing the digits of a positive number is a simple:
sum([int(ch) for ch in str(x)])
That works just as well, without having to worry about explicit loops.
Another way to solve this is using assert and a function:
def sum_num():
# try get user input
try:
user_in = input('Enter Number: ')
assert int(user_in) > 0
except AssertionError:
# we got invalid input
sum_num()
else:
s_d = sum([int(i) for i in user_in])
print('You\'ve entered a positive number! The sum of the digits is: ', s_d)
#run the function
sum_num()
So this will asked user input, if it is not greater than zero it will throw assertion error, which we catch and return the user to inputting the number by calling the function again. If all is well, we split the input into character and add them up. as list('12') gives ['1','2']. We convert to int and add them. :)
The awesome thing about this is you can add more too the asset to capture other issue as floats, character as invalid inputs. E.g.
Assuming literal_eval is important( from ast import literal_eval)
assert isinstance(literal_eval(user_in),int) and int(user_in)>0
Check if user_in is integer and it is greater than 0. So you won’t get issues when user inputs floats or characters.

Python not running my program without any error

I need to create a program that will convert Base 10 numbers in Base 2.
Next is the code, it can not run as expected even if it has no error:
E = input('Please enter a number')
Eint= int(E)
for N in range(100,0):
while 2**N > Eint:
N = N-1
print(0)
if B**N <= Eint:
Eint = Eint - 2**N
print(1)
Print('finished')
When I'm running it it will ask me the number but that's all, thank you for your help guys.
From a quick inspection, range(100,0), B, and Print() are three culprits here! If you want to pass through numbers from 0 to 99, then range(100) is what you need. Now, what is B? Print should be written in lower case: print.
After we fix these syntax errors, let us try to revisit the program and understand what it is supposed to do. Have fun :-)
EDIT to fix the code in the question:
E = input('Please enter a number: ')
Eint = int(E)
for N in range(8,-1,-1):
if 2**N > Eint:
print(0, end='')
else:
Eint = Eint - 2**N
print(1, end='')
print()
print('finished')
Please note that Python is a language that uses indentations to denote code blocks. This code will convert a decimal to binary. Now, note that the range start of 8 gives you a hint about the upper bound of the number that the code can translate. Therefore, an if condition must be added after the second statement to ensure we are not attempting to convert a number that is too large. Enjoy!
If it helps check my solution too. Because I guess you don't want to see the result on separate lines, so I create a list for you to see the result in one line.
E = int(input('Please enter a number\n'))
Eint = E
base_two=[]
while E > 0:
a = int(float(E%2))
base_two.append(a)
E = (E-a)/2
base_two.append(0)
string = ""
for j in base_two[::-1]:
string = string+str(j)
print("Binary for", Eint, "is", string)
print('finished')
I was late a little bit :)

Struggling to get the Sum() function to output one value from a list

olst = []
elst = []
E = int(input("Please enter your first number: "))
O = int(input("Please enter your second number: "))
for OS in range(E,O+1):
if(OS%2!=0):
olst.append(OS)
for ES in range(E,O+1):
if(ES%2==0):
elst.append(ES)
print("Sum of all odd values is: ", sum(olst))
print("Sum of all even values is: ", sum(elst))
This programs intention is to print the sum of all odd numbers between my two integers as well as the even. This is my current code, I'm fairly new to python and tinkering around, open to any criticism and tips. The main issue I'm having is when I run my program both sum(olst) and sum(elst) output the answer multiple times until they reach the correct and final answer. Get the feeling my process is fundamentally flawed somewhere early on but hoping that's not the case!
The last two lines with the print statements should not be indented - otherwise, they are located within the for loop and executed multiple times:
olst = []
elst = []
E = int(input("Please enter your first number: "))
O = int(input("Please enter your second number: "))
for OS in range(E,O+1):
if(OS%2!=0):
olst.append(OS)
for ES in range(E,O+1):
if(ES%2==0):
elst.append(ES)
print("Sum of all odd values is: ", sum(olst))
print("Sum of all even values is: ", sum(elst))
There are also many ways how this code can be optimised (for example, you don't really need the lists elst and olst and can compute the sums in the loop or use comprehensions), but that's a different issue.
You already got your answer above but since you mentioned you are open to tips, this is to provide you just an alternate solution using list comprehensions:
E = int(input("Please enter your first number: "))
O = int(input("Please enter your second number: "))
olst = [i for i in range(E, O+1) if i%2 == 1]
elst = [i for i in range(E, O+1) if i%2 == 0]
print("Sum of all odd values is: ", sum(olst))
print("Sum of all even values is: ", sum(elst))
Additionally, you can replace the middle two lines of the code by
olst = [i for i in range(E, O+1) if i%2 ]
elst = [i for i in range(E, O+1) if not i%2]

'int' object is not iterable in python 3

got a error while compiling the code.
I tried to find smallest and largest value from user's input by storing the input in lists. After 'int' object not iterate problem, couldn't proceed further
largest=0
smallest=0
num=[]
while True:
num = int(input("Please enter a number: "))
for i in num:
if i>largest:
largest=i
for j in num:
if j<smallest:
smallest=j
if num==12:
break
print(largest)
print(smallest)
The moment you issue below code line num is no longer a list, instead its an int type of data.
num = int(input("Please enter a number: "))
As you can understand, there is nothing to iterate over in case of a single integer value.
The right solution is to read your input to a separate variable and append to your list.
input_num = int(input("Please enter a number: "))
num.append(input_num)
Further you will have to change value of your exit clause
if num==12:
break
If you desire to stop the loop after 12 inputs, then use len(num) == 12 in the if condition. In case you want to break loop if input number is 12 then change if condition to if input_num == 12
Note: Your algorithm has logical errors as well. You are assigning smallest to 0 . In case user enters all positive integers as input, your result will incorrect.
You are trying to iterate through a number which is wrong, you have overwritten your num list to an integer. Instead of the following:
num = int(input("Please enter a number: "))
You should save the number in some other variable and add to num list like:
x = int(input("Please enter a number: "))
num.append(x)

Categories