I tried this code with the Python IDE and worked fine. However, a NameError appeared after I compiled the code using pyinstaller or executed the code in Ninja IDE. Any suggestions?
Here is my code. I'm a beginner so please don't judge!
from math import sqrt
while True:
numbers = int(input('Input the total amount of numbers with uncertainties you wish to use: '))
answer = str(input('Type A/a for addition of uncertainties or M/m/D/d for division/multiplication of uncertainties:'))
count = 1
mylist = []
secondlist = []
listsqrnum = []
listsqrun = []
finallist= []
listnum = []
listuncertainty = []
listofanswer1 = ["A","a"]
listofanswer2 = ["d","D","M","m"]
if answer in listofanswer1:
while count <= numbers:
num = float(input('Input uncertainty ' + str(count) + ': '))
count += 1
mylist.append(num)
for i in mylist:
secondlist.append(i ** 2)
x = sqrt(sum(secondlist))
print (x)
elif answer in listofanswer2:
result = float(input("Input resulting value: "))
while count <= numbers:
number = float(input("Input number " + str(count) + ": "))
uncertainty = float(input("Input uncertainty number " +str(count)+ ": "))
listnum.append(number)
listuncertainty.append(uncertainty)
count +=1
for i in listnum:
listsqrnum.append(i ** 2)
for i in listuncertainty:
listsqrun.append(i**2)
for i in range(0,len(listsqrnum)):
finallist.append(listsqrun[i]/listsqrnum[i])
sumofsquare = sum(finallist)
squareroot = sqrt(sumofsquare)
final = result * squareroot
print (final)
else:
print("You have not typed anything or you entered a float")
The error traces back to line 4, saying NameError - 'a' is undefined.
It also indicates same error as other values within the answer list is inputted.
Thank you.
Related
I need help with this Python program.
With the input below:
Enter number: 1
Enter number: 2
Enter number: 3
Enter number: 4
Enter number: 5
the program must output:
Output: 54321
My code is:
n = 0
t = 1
rev = 0
while(t <= 5):
n = int(input("Enter a number:"))
t+=1
a = n % 10
rev = rev * 10 + a
n = n // 10
print(rev)
Its output is "12345" instead of "54321".
What should I change?
try this:
t = 1
rev = ""
while(t <= 5):
n = input("Enter a number:")
t+=1
rev = n + rev
print(rev)
Try:
x = [int(input("Enter a number")) for t in range(0,5)]
print(x[::-1])
There could be an easier way if you create a list and append all the values in it, then print it backwards like that:
my_list = []
while(t <= 5):
n = int(input("Enter a number:"))
t+=1
my_list.append(n)
my_list.reverse()
for i in range(len(my_list)):
print(my_list[i])
You can try this:
n = 0
t = 1
rev = []
while(t <= 5):
n = int(input("Enter a number:"))
t+=1
rev.append(n)
rev.reverse()
rev = ''.join(str(i) for i in rev)
print(rev)
Maintaining a numerical context: use "10 raised to t" (10^t)
This code is not very different from your solution because it continues to work on integer numbers and return rev as an integer:
t = 0
rev = 0
while (t < 5):
n = int(input("Enter a number:"))
# ** is the Python operator for 'mathematical raised to'
rev += n * (10 ** t)
t += 1
print(rev)
(10 ** t) is the Python form to do 10^t (10 raised to t); in this context it works as a positional shift to left.
Defect
With this program happens that: if you insert integer 0 as last value, this isn't present in the output.
Example: with input numeric 12340 the output is the number 4321.
How to solve the defect with zfill() method
If you want manage the result as a string and not as a integer we can add zeroes at the start of the string with the string method zfill().
In this context the zfill() method fills the string with zeros until it is 5 characters long.
The program with this modification is showed below:
NUM_OF_INTEGER = 5
t = 0
rev = 0
while (t < NUM_OF_INTEGER):
n = int(input("Enter a number: "))
rev += n * (10 ** t)
t += 1
# here I convert the number 'rev' to string and apply the method 'zfill'
print(str(rev).zfill(NUM_OF_INTEGER))
With previous code with input "12340" the output is the string "04321".
n = int(input("How many number do you want to get in order? "))
list1 = []
for i in range(n):
num = int(input("Enter the number: "))
thislist = [num]
list1.extend (thislist)
list1.sort()
print ("The ascending order of the entered numbers, is: " ,list1)
list1.sort (reverse = True)
print ("The descending order of the entered numbers, is: " ,list1)
I want to make a loop where I can input numbers, and then the loop will give me the average of the numbers that I inputted. But a problem that I am facing is that I do not know how to make the loop remember the previous numbers that I inputted. I want the loop to end if I put -1.
x = (input ("enter a number: "))
while x != "-1":
y = int(input("enter another number: " ))
total = 0 + y
if total <= 0:
totally = total
print (totally)
you may use a list to store all your numbers, when you finish the input you can compute the average:
nums = []
i = int(input("enter another number: " ))
while i != -1:
nums.append(i)
i = int(input("enter another number: " ))
avg = sum(nums) / len(nums)
print(avg)
if you like one-line solution:
from statistics import mean
from itertools import takewhile, count
print(mean(takewhile(lambda x : x !=-1, (int(input()) for _ in count() ))))
if you want to print intermediary average:
nums = []
i = int(input("enter another number: " ))
while i != -1:
nums.append(i)
print(sum(nums) / len(nums))
i = int(input("enter another number: " ))
also, you could use 2 variables to hold the current sum and the total count:
i = int(input("enter another number: " ))
s = 0
c = 0
while i != -1:
c += 1
s += i
print(s / c)
i = int(input("enter another number: " ))
Probably you should define your total var before, something like this:
x = int(input ("enter a number: "))
total = x
numLoops = 1
y = 0
while y != -1:
y = int(input("enter another number: " ))
total += y # This will store the summation of y's in total var
numLoops += 1
print(f"The average is: {total/numLoops}") # Prints the average of your nums
You can do the following:
values = []
while True:
x = int(input ("enter a number: "))
if x == -1:
break
else:
values.append(x)
print(sum(values)/len(values))
I have a problem with loops and declaring variables. currently I am making a program about Collatz Conjecture, the program should check what is the biggest steps to reach one from certain amount of Collatz Sequence. here's my code :
start_num = int(input("insert a starting Number > "))
how_many = int(input("how many times you want to check? >"))
def even_or_odd(number):
if number % 2 == 0:
return 'isEven'
else:
return 'notEven'
def collatz(n):
z = n
counter = 0
while True:
if n != 1:
if even_or_odd(n) == 'isEven':
n = n/2
counter += 1
continue
if even_or_odd(n) == 'notEven':
n = (n*3)+1
counter += 1
continue
else:
print('number ' + str(z) + ' reached 1 with : ' + str(counter) + ' steps')
return counter
break
def check_biggest_steps(steps_before, steps_after):
if steps_before > steps_after:
return steps_before
if steps_after > steps_before:
return steps_after
if steps_after == steps_before:
return steps_after
def compute_collatz(n_times, collatz_number):
for _ in range(n_times):
before = collatz(collatz_number)
collatz_number += 1
after = collatz(collatz_number)
collatz_number += 1
biggest_steps = check_biggest_steps(before, after)
print('Biggest Steps is :' + str(biggest_steps))
compute_collatz(how_many, start_num)
this biggest_steps variable always return the last 2 steps. I know what causing this problem is that biggest_step variable located inside the loop but I can't get it working anywhere don't know what to do. Thanks
Don't read my code until you have tried it yourself.
Try to make a list that appends every change to a list, then to get the number of moves at the end, just get the length of the list.
.
def collatz(x):
while x != 1:
if x % 2 > 0:
x =((3 * x) + 1)
list_.append(x)
else:
x = (x / 2)
list_.append(x)
return list_
print('Please enter a number: ', end='')
while True:
try:
x = int(input())
list_ = [x]
break
except ValueError:
print('Invaid selection, try again: ', end='')
l = collatz(x)
print('\nList:', l, sep=' ')
print('Number of steps required:', len(l) - 1)
you didn't save your biggest_steps and compared always the last 2 only.
I would suggest following change.
def compute_collatz(n_times, collatz_number):
biggest_steps = 0
for _ in range(n_times):
steps = collatz(collatz_number)
if steps > biggest_steps:
biggest_steps = steps
collatz_number += 1
print('Biggest Steps is :' + str(biggest_steps))
problem with sorting
a = raw_input("Do you know the number of inputs ?(y/n)")
if a == 'y':
n = int(input("Enter the number of inputs : "))
total = 0
i = 1
while i <= n:
s = input()
total = total + int(s)
i = i + 1
s.sort()
print s
print('The sum is ' + str(total))
Because you are trying to sort on input. sort only work on iterating like list and tuples.
I just rewrite your code,
a = raw_input("Do you know the number of inputs ?(y/n)")
if a == 'y':
n = int(input("Enter the number of inputs : "))
inputs = []
for i in range(n):
s = input()
inputs.append(int(s))
inputs.sort()
print inputs
print('The sum is ',sum(inputs))
Edit
Just change whole operation into a function and put yes/no question in a while loop, And for wrong entry exit from program.
def foo():
n = int(input("Enter the number of inputs : "))
inputs = []
for i in range(n):
s = input()
inputs.append(int(s))
inputs.sort()
print inputs
print('The sum is ',sum(inputs))
while True:
a = raw_input("Do you know the number of inputs ?(y/n)")
if a == 'y':
foo()
elif a == 'n':
print 'We are giving one more option.'
continue
else:
print 'Wrong entry'
break
n = int(input("Enter the number of inputs : "))
total = 0
i = 1
array = []
while i <= n:
s = int(input())
array.append(s)
total = total + int(s)
i = i + 1
array.sort()
print(array)
print('The sum is ' + str(total))
this will solve your problem, sort applies on list not on str object
Store the numbers in a list. Then use sum(list) to get the sum of elements in the list, and sorted(list) to get the list sorted in ascending order.
n = int(input("Enter the number of inputs: "))
l=[]
for i in range(n):
s = input()
l.append(int(s))
print('The sum is', sum(l))
print('Sorted values', sorted(l))
Were you looking for this?
I'm learning Python, and in trying to find out the min and max values of user number inputs, I can't seem to figure it out.
count = 0
x = []
while(True):
x = input('Enter a Number: ')
high = max(x)
low = min(x)
if(x.isdigit()):
count += 1
else:
print("Your Highest Number is: " + high)
print("Your Lowest Number is: " + low)
break
inp=input("enter values seperated by space")
x=[int(x) for x in inp.split(" ")]
print (min(x))
print (max(x))
output:
Python 3.5.2 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux
enter values seperated by space 20 1 55 90 44
1
90
break your program into small manageable chunks start with just a simple function to get the number
def input_number(prompt="Enter A Number:"):
while True:
try: return int(input(prompt))
except ValueError:
if not input: return None #user is done
else: print("That's not an integer!")
then write a function to continue getting numbers from the user until they are done entering numbers
def get_minmax_numbers(prompt="Enter A Number: "):
maxN = None
minN = None
tmp = input_number(prompt)
while tmp is not None: #keep asking until the user enters nothing
maxN = tmp if maxN is None else max(tmp,maxN)
minN = tmp if minN is None else min(tmp,minN)
tmp = input_number(prompt) # get next number
return minN, maxN
then just put them together
print("Enter Nothing when you are finished!")
min_and_max = get_numbers()
print("You entered Min of {0} and Max of {1}".format(*min_and_max)
x is a list, and to append an item to a list, you must call the append method on the list, rather than directly assigning an item to the list, which would override the list with that item.
Code:
count = 0
x = []
while(True):
num = input('Enter a Number: ')
if(num.isdigit()):
x.append(int(num))
count += 1
elif(x):
high = max(x)
low = min(x)
print("Your Highest Number is: " + str(high))
print("Your Lowest Number is: " + str(low))
break
else:
print("Please enter some numbers")
break