var1,var2 = input("Enter two digits a and b (0-9):").split(' ')
while True:
if (0 <= var1 <= 9) and (0 <= var2 <= 9):
result = var1+var2
print("The result is: %r." %result)
I use Spyder Python 3.5 to write this code and try to run it. However, this code does not work.
It reveals that " (1) var1,var2 = input("Enter two digits a and b (0-9):").split(''); (2) TypeError: 'str' object is not callable"
a,b = map(int, input().split())
while True:
if (0 <= a <= 9) and (0 <= b <= 9):
c = a + b
break
print('%r' %c)
Related
I want to take two input. The program must accept only valid scores (a score must fit in the range [0 to 10]). Each score must be validated separately. If the input is not valid, I want to print "Wrong input".
After taking two valid input, I want to print sum of the values.
count = 0
count2 = 0
while True:
a = float(input())
if 0 <= a <= 10:
count2 += a
count2 += 1
b = float(input())
if 0 <= b <= 10:
count2 += b
count += 1
else:
print('Wrong input')
if count == 2:
break
print('Sum = {}'.format(count2))
Sample input:
-3.5
3.5
11.0
10.0
Output:
Wrong input
Wrong input
sum = 13.5
By taking two while loops you can easily verify each input individually till you get the expected value.
while True:
a = float(input())
if 0<=a<=10:
break
else:
print('Wrong Input')
while True:
b = float(input())
if 0<=b<=10:
break
else:
print('Wrong Input')
print("sum =", a+b)
I'm new to python and want to make a program that generates Pi with the given decimal numbers. Problem is that I don't know how to check if the user has inputted a positive number.
This is the function that generates Pi (I don't know for sure how it works)
def PiBerekening(limiet):
q = 1
r = 0
t = 1
k = 1
n = 3
l = 3
decimaal = limiet
teller = 0
while teller != decimaal + 1:
if 4 * q + r - t < n * t:
# yield digit
yield n
# insert period after first digit
if teller == 0:
yield '.'
# end
if decimaal == teller:
print('')
break
teller += 1
nr = 10 * (r - n * t)
n = ((10 * (3 * q + r)) // t) - 10 * n
q *= 10
r = nr
else:
nr = (2 * q + r) * l
nn = (q * (7 * k) + 2 + (r * l)) // (t * l)
q *= k
t *= l
l += 2
k += 1
n = nn
r = nr
And this is how I ask the user how many decimals he wants to see
while not verlaatloop:
try:
pi_cijfers = PiBerekening(int(input("With how many decimals would you like to calculate Pi?")))
assert pi_cijfer > 0 # This is one of the things I've tried but I get the "NameError: name 'pi_cijfer' is not defined" error and I don't know what to do to check if the inputted number is negative
except ValueError:
print("This isn't a valid number, try again")
except AssertionError:
print("This number is negative, try again")
else:
verlaatloop = True
This is how I show the calculated Pi
for pi_cijfer in pi_cijfers:
print(pi_cijfer, end='')
You can first validate the input and then pass it to the PiBerekening function. Something like this:
while not verlaatloop:
try:
no_decimals = int(input("With how many decimals would you like to calculate Pi?"))
if no_decimals > 0:
pi_cijfers = PiBerekening(no_decimals)
#assert pi_cijfer > 0 # This is one of the things I've tried but I get the "NameError: name 'pi_cijfer' is not defined" error and I don't know what to do to check if the inputted number is negative
except ValueError:
print("This isn't a valid number, try again")
except AssertionError:
print("This number is negative, try again")
else:
verlaatloop = True
I try to find out the index of a certain Fibonacci number. However my program returned to me this result "Your program took too long to execute. Check your code for infinite loops, or extra input requests" after typing in 1134903171.
num = 1
num_prev = 1
n = int(input())
i = 1
if n < 2:
print(1, 2)
else:
while i <= n + 2:
num_prev, num = num, num + num_prev
i += 1
if n == num:
print(i + 1)
break
elif i == n + 3:
print(-1)
#break`
Thank you guys. The problem of last code is that: if the number isn't a Fibonacci number and meanwhile it is too large, it will took to many loops for the calculation. As I used a web compiler to calculate, they do not allow such "infinity" loop to operate. Then I used a math methode to limite the loop.
import math
N=int(input())
root1=math.sqrt(5*N*N+4)
root2=math.sqrt(5*N*N-4)
i=1
num, num_prev = 1, 1
if root1%1==0 or root2%1==0:
while i <= N+2:
num_prev,num = num,(num+num_prev)
i+=1
if N==num:
print(i+1)
break
else:
print(-1)
But the best answer could be:
prev, next = 1, 1
index = 2
possible_fib = int(input())
while possible_fib > next:
prev, next = next, prev + next
index += 1
if possible_fib == next:
print(index)
else:
print(-1)
I have this program:
a = []
num = input('Enter numbers *Separate by using commas:')
num = num.split(",")
for i in num:
a.append(i)
num = list(map(int,a))
print('~~Output~~')
for x in num:
if x >= 10:
print('Values >= 10 :',x,end = '~')
and it came out like this:
Enter numbers *Separate by using commas:12,1,10,5
~~Output~~
Values >= 10 : 12~Values >= 10 : 10~
>>>
how do I make it so that it print like this:
Enter numbers *Separate by using commas:12,1,10,5
~~Output~~
Values >= 10 : ~12~10~
>>>
thanks.
is it like this:
a = []
num = input('Enter numbers *Separate by using commas:')
for i in num:
if i >= 10:
a.append(i)
print('~' + '~'.join(a) + '~')
it will print:
if i >= 10:
TypeError: '>=' not supported between instances of 'str' and 'int'
>>>
I don't really understand....sorry...is there a simpler one using this for loop?
I assume you meant to print the label before the values? Not part of every value?
print('Values >= 10 :', end ='')
for x in num:
if x >= 10:
print(x,end = '~')
Your second error is that you are iterating over a string... You forgot to split the commas, and map the strings to integers
Add the numbers into a list and then print them.
numbersHigher = []
for x in num:
if x >= 10:
numbersHigher.append(x)
Zach King suggested list comprehension(Google it if you want to know more)
numbersHigher = [x for x in num if x >= 10]
Then you print it once after the loop.
It happens because there might be 2 numbers and you print twice because x is higher than 1- 2 times.
EDIT:
To make the last print like you want you can do:
import string
print('~' + '~'.join(numbersHigher) + '~')
I am failed to print only the nth fibonacci number.
In my code, when the user said to print nth trem it print the series upto nth term but i want to get the output only the nth term
e.g
if I say num=4
out put should be 2
please guide
here is the code:
N= int(input("How many terms? "))
N1 = 0
N2 = 1
sum = 2
if N <= 0:
print("Plese enter a positive integer")
elif N == 1:
print("Fibonacci sequence:")
print(N1)
else:
print("Fibonacci sequence:")
print(N1,",",N2,end=' , ')
while sum < N:
Nth = N1 + N2
print(Nth,end=' , ')
N1 = N2
N2 = Nth
sum += 1
The print stmt should be outside the loop
N= int(input("How many terms? "))
N1 = 0
N2 = 1
sum = 2
if N <= 0:
print("Plese enter a positive integer")
elif N == 1:
print("Fibonacci sequence:")
print(N1)
else:
print("Fibonacci sequence:")
print(N1,",",N2,end=' , ')
while sum < N:
Nth = N1 + N2
N1 = N2
N2 = Nth
sum += 1
print(Nth,end=' , ')
Simpler code, from the "How to Think Like a Comptuer Scientist: Python" book,
def fibonacci (n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)
Just call fibonacci passing your nth term as the argument.
to achieve that output you can simply decrease the value of n by 1 and then carry on all the computation.
For example:
def fib(n):
n = n-1
a, b = 0, 1
count = 1
while count <= abs(n):
next = a + b
a = b
b = next
count += 1
return a