How to check if this input is a negative number - python-3.x

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

Related

Why isn't chr() outputting the correct character?

I'm working on a Caesar Cypher with Python 3 where s is the string input and k is the amount that you shift the letter. I'm currently just trying to work through getting a letter like 'z' to wrap around to equal 'B'(I know the case is wrong, I'll fix it later). However when I run caesarCipher using the the following inputs: s = 'z' and k = 2, the line: s[n] = chr((122-ord(s[n]) + 64 + k)) causes s[n] to equal 'D'. If i adjust it down two(logically on the unicode scale this would equal 'B'), it makes s[n] = #. What am I doing wrong on that line that's causing 'B' not to be the output?
def caesarCipher(s, k):
# Write your code here
n = 0
s = list(s)
while n < len(s):
if s[n].isalpha() == True:
if (ord(s[n].lower())+k) < 123:
s[n] = (chr(ord(s[n])+k))
n += 1
else:
s[n] = chr((122-ord(s[n]) + 64 + k))
else:
n += 1
s = ''.join(s)
return s
You forgot to add 1 to n in the test of (ord(s[n].lower())+k) < 123 so that it would count s[n] twice or more.
Change it to
else:
s[n] = chr((122 - ord(s[n]) + 64 + k))
n += 1
and if you input "z" and 2, you'll get "B"
print(caesarCipher("z", 2))
# B
and if you adjust it down two, you'll get "#", which is the previous previous character of B in ASCII.
...
else:
s[n] = chr((122 - ord(s[n]) + 62 + k))
n += 1
...
print(caesarCipher("z", 2))
# #

other options for solving tasks with list

Task:
Write a program that reads from the standard input and will return the:
sum
difference
product
of all elements in the given list.
Input
An integer n (1 <= n <= 500) that denotes the number of elements in the list. The following n integers are the next elements of the list.
Output
Three integers:
sum
difference
product
of all the elements of the list.
And these are my ideas, but I still get a mistake
from sys import stdin
def Simple_list_arithmetic():
print("Enter a positive number: ")
n = int(stdin.readline())
l = []
if n >= 1 and n <= 500:
for i in range(1, n+1):
l.append(i)
#print(l)
suma = 0
for add in range(0, len(l)):
suma = suma + l[add]
print(suma)
#return suma
difference = 2
for substract in range(0, len(l)):
difference = difference - l[substract]
print(difference)
#return difference
product = 1
for increase in range(0, len(l)):
product = product * l[increase]
print(product)
return suma, difference, product
else:
print("Wrong number.")
still wrong
suma = 0
q = [suma + l[add] for add in range(0, len(l))]
print(sum(q))
difference = 2
w = [difference - l[substract] for substract in range(0, len(l))]
print(list(w))
product = 1
e = [product * l[increase] for increase in range(0, len(l))]
print(sum(e))
still wrong
if n >= 1 and n <= 500:
for x in range(1, n+1):
print(x)
print("\n")
suma = 0
for add in range(1, n+1):
suma = suma + add
print(suma)
difference = 2
for substract in range(1, n+1):
difference = difference - substract
print(difference)
product = 1
for increase in range(1, n+1):
product = product * increase
print(product)
with map() and lambda still wrong
t = list(map(lambda add: suma + l[add], range(0, len(l))))
#return sum(t)
y = list(map(lambda increase: increase * l[increase], range(0, len(l))))
#print(y[-1])
#print(y)
try this:
x = int(input("Enter a positive number: "))
if x >= 1 and x <= 500:
sum = 0
for i in range(x,501):
sum +=i
print(sum)
diff = 2
for i in range(x,501):
diff -= i
print(diff)
prod = 1
for i in range(x, 501):
prod *= i
print(prod)

Given a positive integer, determine if it's the nth Fibonacci number for some n

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)

Trouble with variables (Python)

I'm a newbie with programming and I'm in trouble with this code:
def supercalcx(a, b):
n = a
while a <= b:
n = n * a
a = a + 1
print(n)
The IDE give me the error: "TypeError: can't multiply sequence by non-int of type 'str'", but I'm sure the inputs are ints or floats, can anyone explain me the problem. Thanks !
This function works:
>>> def supercalcx(a, b):
... n = a
... while a <= b:
... n = n * a
... a = a + 1
... print(n)
...
>>> supercalcx(2, 4)
48
Your function does not convert between data types. A very crude method of this is to do the following below:
def supercalcx(a,b):
n = int(a)
a = int(a)
b = int(b)
while a <= b:
n = n * a
a = a + 1
print(n)
A couple of suggestions to improve your code:
A function should rarely have the print() function inside of it; instead, use the return keyword. You can change a = a + 1 to a += 1 and n = n * a to n *= a. You can also introduce try and except which will attempt to perform whatever is tabbed under try and if something throws an error specified by the except block, it will then perform whatever is tabbed under except. A somewhat improved version is below:
def supercalcx(a, b):
try:
n = int(a)
a = int(a)
b = int(b)
except ValueError:
return "Unable to convert to integers!"
while a <= b:
n *= a
a += 1
return n
print(supercalcx("1", 2))
print(supercalcx(1, 2))

The result is coming back correct but not in correct format

I am doing an assignment and the answers are coming back correctly but I would need them to say 5! = 120 instead of just = 120. How would I go about that?
def getInt():
getInt = int
done = False
while not done:
print("This program calcultes N!")
# get input for "N
N = int(input("Please enter a non-negative value for N: "))
if N < 0:
print("Non-Negative integers, please!")
else:
done = True
return N
def main():
n = getInt()
for i in range(n-1):
n = n * (i+1)
print("=" ,n)
main()
I hope this code will help.
print('Enter a positive integer')
a = int(input())
def factorial(n):
if n == 0:
return(1)
if n == 1:
return(1)
if n > 1:
return(n * factorial(n-1))
if a < 0:
print('Non-Negative integers, please!')
if a >= 0:
print(str(a) + '! = ' + str(factorial(a)))
In the for i in range(n-1)you could use another integer instead of n just to be sure things don't mess up and you can print like joel said print(i,"!=", n) but instead of n the integer you will use.
can you show me your homework instructions?
i'm not sure what the first value is in your example.. the current iteration or the original number entered?
# declare getInt()
def getInt():
getInt = int
done = False
while not done:
# write "this program calculates N!"
print("This program calcultes N!")
# get input for "N
N = int(input("Please enter a non-negative value for N: "))
# if N < 0 then
if N < 0:
print("Non-Negative integers, please!")
# else
else:
# done = true
done = True
# return N
return N
# main
def main():
n = entry = getInt()
for i in range(n-1):
n = n * (i+1)
print("{0}! = {1}".format(entry, n))
main()
results:
/*
This program calcultes N!
Please enter a non-negative value for N: 5
5! = 120
*/

Resources