I'm trying to print the largest number from the inputs that the user gives, but it's printing the wrong number - python

Basically, I'm trying to build a code to get the largest number from the user's inputs. This is my 1st time using a for loop and I'm pretty new to python. This is my code:
session_live = True
numbers = []
a = 0
def largest_num(arr, n):
#Create a variable to hold the max number
max = arr[0]
#Using for loop for 1st time to check for largest number
for i in range(1, n):
if arr[i] > max:
max = arr[i]
#Returning max's value using return
return max
while session_live:
print("Tell us a number")
num = int(input())
numbers.insert(a, num)
a += 1
print("Continue? (Y/N)")
confirm = input()
if confirm == "Y":
pass
elif confirm == "N":
session_live = False
#Now I'm running the function
arr = numbers
n = len(arr)
ans = largest_num(arr, n)
print("Largest number is", ans)
else:
print(":/")
session_live = False
When I try running my code this is what happens:
Tell us a number
9
Continue? (Y/N)
Y
Tell us a number
8
Continue? (Y/N)
Y
Tell us a number
10
Continue? (Y/N)
N
Largest number is 9
Any fixes?

The error in your largest_num function is that it returns in the first iteration -- hence it will only return the larger of the first two numbers.
Using the builtin max() function makes life quite a bit easier; any time you reimplement a function that already exists, you're creating work for yourself and (as you've just discovered) it's another place for bugs to creep into your program.
Here's the same program using max() instead of largest_num(), and removing a few unnecessary variables:
numbers = []
while True:
print("Tell us a number")
numbers.append(int(input()))
print("Continue? (Y/N)")
confirm = input()
if confirm == "Y":
continue
if confirm == "N":
print(f"Largest number is {max(numbers)}")
else:
print(":/")
break

So, first things first,
the use of max can be avoided, as it is a reserved keyword in python
And coming to your fix, you are comparing it with the value only once in the loop, and you are returning the number, the indentation is the key here. You will have to wait for the loop to complete its job then return the value.
There are many inbuilt methods to do the job, Here is your implementation (a bit modified)
session_live = True
numbers = []
a = 0
def largest_num(arr, n):
#Create a variable to hold the max number
max_number = arr[0]
#Using for loop for 1st time to check for largest number
for i in range(1, n):
if arr[i] > max_number:
max_number = arr[i]
# --- The indentation matters
#Returning max's value using return
return max_number
while session_live:
print("Tell us a number")
num = int(input())
numbers.insert(a, num)
a += 1
print("Continue? (Y/N)")
confirm = input()
if confirm == "Y":
pass
elif confirm == "N":
session_live = False
#Now I'm running the function
arr = numbers
n = len(arr)
ans = largest_num(arr, n)
print("Largest number is", ans)
else:
print(":/")
session_live = False

I made it without using the built-in function 'max'.
It is a way to update the 'maxNum' variable with the largest number by comparing through the for statement.
numbers = []
while True:
print("Tell us a number")
numbers.append(int(input()))
print("Continue? (Y/N)")
confirm = input()
if confirm == "Y":
continue
if confirm == "N":
maxNum = numbers[0]
for i in numbers:
if i > maxNum:
maxNum = i
print("Largest number is", maxNum)
else:
print(":/")
break

Related

How do I write a for loop in Python to repeatedly ask the user to enter a number until they enter in a whole number (0, 1, 2, etc)?

I know how to do this with a while loop and know how to use a for-loop in other languages like Java and C++. I want to use a for-loop in place of where I have written the while loop asking for the user input.
# You are required to use for-loop to solve this and round your answer to 2 decimal places. Write
# a program that takes n ∈ N (i.e., any positive integer including zero) from the user and use the
# input value to compute the sum of the following series:
n = -1
while n < 0:
n = int(input("Enter a value to compute: "))
# keep asking for user input until a whole number (0, 1, 2, 3, etc...) has been entered
k = 0
sum = 0
# To hold the sum of the fraction to be displayed
lastTerm = 0
# This variable represents the last term to be added to the fraction sum before the while loop below terminates
if n == 0:
sum = 0
elif n == 1:
sum = 1
else:
while lastTerm != 1 / n:
lastTerm = (n - k) / (k + 1)
sum = sum + (n - k) / (k + 1)
k += 1
print("{:.2f}".format(sum))
# Print the sum to two decimal places
One option is to catch the exception which is thrown when you cannot convert the input to an int, i.e.
while(True):
try:
# read input and try and covert to integer
n = int(input("Enter a value to compute: "))
# if we get here we got an int but it may be negative
if n < 0:
raise ValueError
# if we get here we have a non-negative integer so exit loop
break
# catch any error thrown by int()
except ValueError:
print("Entered value was not a postive whole number")
Alternative, slightly cleaner but I'm not 100% sure isdigit() will cover all cases
while(true):
n = input("Enter a value to compute: ")
if value.isdigit():
break
else:
print("Entered value was not a postive whole number")
How about this? It uses the for loop and sums all the values in the list.
x=[1,2,3,4] #== test list to keep the for loop going
sum_list=[]
for i in x:
j=float(input("Enter a number: "))
if not j.is_integer() or j<0:
sum_list.append(j)
x.append(1) #=== Add element in list to keep the cyclone going
else:
break
sums=sum(sum_list)
print("The Sum of all the numbers is: ",round(sums,2))
Use this to check for whole numbers -
if num < 0:
# Not a whole number
elif num >= 0:
# A whole number
for a for loop:
import itertools
for _ in itertools.repeat([]): # An infinite for loop
num = input('Enter number : ')
if num < 0:
# Not a whole number
pass # This will ask again
elif num >= 0:
# A whole number
break # break from for loop to continue the program
Easier Way -
mylist = [1]
for i in mylist : # infinite loop
num = int(input('Enter number : '))
if num < 0:
mylist.append(1)
pass # This will ask again
elif num >= 0:
# A whole number
break

writing a loop that ends with a negative number and prints the sum of the positive numbers

i have to write a program with a loop that asks the user to enter a series of positive numbers. the user should enter a negative number to signal the end of the series, and after all positive numbers have been entered, the program should display their sum.
i don't know what to do after this, or whether this is even right (probably isn't):
x = input("numbers: ")
lst = []
for i in x:
if i > 0:
i.insert(lst)
if i < 0:
break
you should use input in the loop to enter the intergers.
lst = []
while True:
x = int(input('numbers:'))
if x > 0:
lst.append(x)
if x < 0:
print(sum(lst))
break
def series():
sum1 = 0
while True:
number = int(input("Choose a number, -1 to quit:"))
if number>=0:
sum1+=number
else:
return sum1
series()
while True means that the algorithm has to keep entering the loop until something breaks it or a value is returned which ends the algorithm.
Therefore, while True keep asking for an integer input , if the given integer is positive or equal to zero, add them to a sum1 , else return this accumulated sum1
You can use a while loop and check this condition constantly.
i, total = 0, 0
while i>=0:
total+=i
i = int(input('enter number:'))
print(total)
Also, don't use:
for loop for tasks you don't know exactly how many times it is going to loop
while loop as while True unless absolutely necessary. It's more prone to errors.
variable names that have the same name as some built-in functions or are reserved in some other ways. The most common ones I see are id, sum & list.
do you want that type of code
sum_=0
while True:
x=int(input())
if x<0:
break
sum_+=x
print(sum_)
Output:
2
0
3
4
5
-1
14
if you want a negative number as a break of input loop
convert string to list; input().split()
convert type from string to int or folat; map(int, input().split())
if you want only sum, it is simple to calculate only sum
x = map(int, input("numbers: ").split())
ans = 0
for i in x:
if i >= 0:
ans += i
if i < 0:
break
print(ans)

AttributeError: 'str' object has no attribute 'list'

We have to find out the average of a list of numbers entered through keyboard
n=0
a=''
while n>=0:
a=input("Enter number: ")
n+=1
if int(a)==0:
break
print(sum(int(a.list()))/int(n))
You are not saving the numbers entered. Try :
n = []
while True:
a=input("Enter number: ")
try: #Checks if entered data is an int
a = int(a)
except:
print('Entered data not an int')
continue
if a == 0:
break
n.append(a)
print(sum(n)/len(n))
Where the list n saves the entered digits as a number
You need to have an actual list where you append the entered values:
lst = []
while True:
a = int(input("Enter number: "))
if a == 0:
break
else:
lst.append(a)
print(sum(lst) / len(lst))
This approach still has not (yet) any error management (a user enters float numbers or any nonsense or zero at the first run, etc.). You'd need to implement this as well.
a needs to be list of objects to use sum, in your case its not. That is why a.list doens't work. In your case you need to take inputs as int (Can be done like: a = int(input("Enter a number")); ) and then take the integer user inputs and append to a list (lets say its name is "ListName")(listName.append(a)), Then you can do this to calculate the average:
average = sum(listName) / len(listName);
def calc_avg():
count = 0
sum = 0
while True:
try:
new = int(input("Enter a number: "))
if new < 0:
print(f'average: {sum/count}')
return
sum += new
count += 1
print(f'sum: {sum}, numbers given: {count}')
except ValueError:
print("That was not a number")
calc_avg()
You can loop, listen to input and update both s (sum) and c (count) variables:
s, c = 0, 0
while c >= 0:
a = int(input("Enter number: "))
if a == 0:
break
else:
s += a
c += 1
avg = s/c
print(avg)

What is the flaw with my logic in a python function for checking primes?

I'm relatively new to Python and trying to build a function to check primes because I thought it would be a good starter project, but my code returns everything as a prime, so it's obviously gone wrong. I get this is an inefficient way to do it, but I want to understand how to do it the long way first. Here's my code so far:
def Prime(n):
if n == 1 or n == 2 or n == 3:
print("This number is prime.")
else:
i = n - 1
while i > 0:
if n % i == 0:
break
print("This number is not prime.")
else:
i = i - 1
print("This number is prime.")
def Main():
n = int(input("What is the number you'd like to check?"))
Prime(n)
answer2 = input("Thank you for using the prime program.")
Main()
Mathematically speaking you could check only all the int between 0 and sqrt(n) to judge a number is prime or not as for the logic, you are missing negative number handling plus other things please see my following code:
def prime(n):
n = abs(n)
if n<4: return True
i = int(sqrt(n))
while i > 1:
if n % i == 0: return False
i -= 1
return True
plus you should add this to your import
from math import sqrt
Here is your program with a couple changes:
def Prime(n):
if n == 1 or n == 2 or n == 3:
print("This number is prime.")
else:
i = n - 1
while i > 1:
if n % i == 0:
print("This number is not prime.")
return
i = i - 1
print("This number is prime.")
return
def Main():
n = int(input("What is the number you'd like to check? "))
Prime(n)
print "Thank you for using the prime program."
Main()
First, i is now compared until i > 1 rather than 0 as every number is divisible by 1 and hence all numbers would be prime if the original condition was used.
Secondly, the break statement is substituted with return. Although break would work, the program would need more modifications in that case because the message for a prime number would always be printed at the end (along with not a prime message). Also, the return statement was moved after the print to actually get a print. More importantly, the message that a number is a prime was moved outside the while - otherwise the message would be printed on every iteration.
I also removed the else and the i is decremented right in the while loop which is to me a more readable alternative.
Finally, your last statement was, I assume, supposed to be an output, which it is now. I also added a space to the user prompting message so that the number displays more nicely.
It's not easy to explain the logic flaw, but you can see the following code
def Prime(n):
if n == 1 or n == 2 or n == 3:
print("This number is prime.")
else:
i = n - 1
while i > 0:
if i == 1 or n == 2 or n == 3:
print("This number is prime.")
break
if n % i == 0:
print("This number is not prime.")
break
else:
i = i - 1
def Main():
n = int(input("What is the number you'd like to check? "))
Prime(n)
print("Thank you for using the prime program.")
Main()
Ok, first off, your code will never print "This number is not prime." because you've put a break statement right before it. You would want to reverse those two lines such that it becomes:
print("This number is not prime.")
break
Also, the line i = n - 1 should be changed to i = n so that you check the starting number as well, and not just the numbers lesser than it. So if you try the code now, you'll notice that you're printing whether every number that you check is prime or not, not just the input value. To remedy this using your code structure, use a flag. For example:
def Prime(n):
flag = true
if n == 1 or n == 2 or n == 3:
print("This number is prime.")
else:
i = n
while i > 0:
if n % i == 0:
print("This number is not prime.")
break
else:
i = i - 1
if flag == true:
print("This number is prime.")
The flag check should be outside the loop.

The Next Palindrome number

I am beginner in programming, So can you please tell me what's wrong with my code?
I want to print next palindrome number if the number entered by the user (n) is not palindrome
n = int(input("Enter any number :- "))
reverse = 0
temp = n
while (n!=0):
reverse = reverse * 10
reverse = reverse + n%10
n=n//10
if(temp==reverse):
print ("Already palindrome:: ")
if(temp != reverse):
new_temp = temp
new_reverse = 0
for i in range(new_temp,new_temp+10):
while(temp != 0):
new_reverse = new_reverse * 10
new_reverse = new_reverse + temp%10
temp = temp//10
if(new_temp==new_reverse):
print ("Next pallindrome is :- ",new_temp)
break
if(new_temp != new_reverse):
temp = new_temp+1
There are two problems with your code.
1) Your "for i in range" loop calculates the reverse of the temp variable, but you don't change the temp variable's value.
You do
new_temp = temp
for i in range(new_temp,new_temp+10):
[SNIP]
if(new_temp != new_reverse):
temp = new_temp+1 #this value never changes.
So you're making 10 iterations with one and the same value.
2) Ten iterations might not be enough to find a palindrome. Keep going until you find a palindrome.
Working code:
def reverse(num):
reverse= 0
while num:
reverse= reverse*10 + num%10
num= num//10
return reverse
num= int(input("Enter any number :- "))
if num==reverse(num):
print ("Already palindrome.")
else:
while True:
num+= 1
if num==reverse(num):
print ("Next palindrome is : %s"%num)
break
To check if a number is a palindrome, you don't need to convert it to a number. In fact, its a lot simpler if you just check the string equivalent of your number.
>>> i = '212'
>>> i == i[::-1]
True
>>> i = '210'
>>> i == i[::-1]
False
Use this to your advantage, and create a function:
def is_palindrome(foo):
return str(foo) == str(foo)[::-1]
Next, to find the next palindrome, simply increment the number till your palindrome check is true.
Combine all that, and you have:
def is_palindrome(n):
return str(n) == str(n)[::-1]
n = raw_input('Enter a number: ')
if is_palindrome(n):
print('Congratulations! {0} is a palindrome.'.format(n))
else:
n1 = n
while not is_palindrome(n1):
n1 = int(n1)+1
print('You entered {0}, but the next palindrome is {1}'.format(n, n1))
Here is how it works:
$ python t.py
Enter a number: 123
You entered 123, but the next palindrome is 131
$ python t.py
Enter a number: 121
Congratulations! 121 is a palindrome.
If it helps, I believe it's possible to solve this problem with n/2 iterations where n is the length of the input number. Here's my solution in Python:
def next_palin_number(number):
number+=1
# Convert the number to a list of its digits.
number = list(str(number))
# Initialize two indices for comparing symmetric digits.
i = 0
j = len(number) - 1
while i < j:
# If the digits are different:
if number[i] != number[j]:
# If the lower-power digit is greater than the higher-power digit:
if int(number[j]) > int(number[i]):
if number[j-1]!='9':
number[j - 1] = str(int(number[j - 1]) + 1)
number[j] = number[i]
else:
number = list(str(int(''.join(number[:j]))+1))+number[j:]
else:
number[j] = number[i]
i += 1
j -= 1
# Concatenate and return the result.
return "".join(number)
This problem has a wonderful number of ways to solve them.
One of them is
def nearest_palindrome(number):
#start writitng your code here
while True:
number+=1
if str(number) == str(number)[::-1]:
return number
number=12300
print(nearest_palindrome(number))
Thanks for your time to read my answer : )
I have written this for finding next pallindrome number given a pallindrome number.
def palindrome(num):
bol=False
#x=len(str(num))
num=num+1
while(bol==False):
if(check_palindrome(num)):
bol=True
else:
num=num+1
return num
def check_palindrome(n):
temp=n
rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
if(temp==rev):
return True
b=palindrome(8)
print(b)
def next_palin_drome(n):
while True:
n+=1
if str(n) == str(n)[::-1]:
return n
n=12231
print(next_palin_drome(n))
output:12321
def nearest_palindrome(number):
for i in range(1,number):
number=number+1
tem=str(number)
tem1=tem[-1::-1]
if(tem==tem1):
return number
else:
continue
number=12997979797979797
print(nearest_palindrome(number))
def nearest_palindrome(number):
n = len(str(number))//2
if(len(str(number)) % 2 == 0):
#number like 1221
number_1 = int((str(number))[:n]) #12
number_2 = int((str(number))[n:]) #21
if(number_1 < number_2):
number_1 += 1
number_2 = int(str(number_1)[::-1])
else:
number_2 = int(str(number_1)[::-1])
# if last half part is zero then just reverse the first number
if number_2 == 0:
number_2 = str(number_1)[::-1]
#combining the both parts
ans = int(str(number_1) + str(number_2))
return ans
else:
#numer like 12510 n=2
nu = int((str(number))[:n+1]) #add in this number
number_1 = int((str(number))[:n]) # 12
number_2 = int((str(number))[n+1:]) # 21
if (number_1 < number_2):
nu += 1
number_2 = int((str(nu))[::-1][1:])
else:
number_2 = int((str(nu))[::-1][1:])
#if last half part is zero then just reverse the first number
if number_2 == 0:
number_2 = str(nu)[::-1]
number_2 = number_2[1:]
#combinning both parts
ans = int(str(nu) + str(number_2))
return ans
number=12331
print(nearest_palindrome(number))
If a definite range is given:
# function to check if the number is a palindrome
def palin(x):
s=str(x)
if s==s[::-1]:
return True
else:
return False
n=int(input("Enter the number"))
# Putting up range from the next number till 15 digits
for i in range(n+1,int(10e14)):
if palin(i) is True:
print(i)
break
A brute force method:
def math(n):
while not var:
n += 1
if str(n) == str(n)[::-1] : f = 'but next is : '+str(n); return f
n = int(input()); t = math(n); print('Yes',t) if str(n) == str(n)[::-1] else print('No',t); global var; var = False
This is a good fast solution. I saw that the other solutions were iterating and checking through every +1 they did, but this is really slow for big numbers.
This solution has O(n) time if you look at the length of the number
beginNumber = 123456789101112131415161718 #insert number here for next palidrome
string = str(beginNumber + 1)
length = len(string)
number= [int(x) for x in list(string)]
for i in range(length//2):
if (number[i] != number[length-1-i]):
if (number[i]<number[length-1-i]):
number[length-2-i] += 1
number[length-1-i] = number[i]
print("".join([str(x) for x in number]))
I have written this for finding next pallindrome number given a pallindrome number..
#given a pallindrome number ..find next pallindrome number
input=999
inputstr=str(input)
inputstr=inputstr
#append 0 in beginning and end of string ..in case like 99 or 9999
inputstr='0'+inputstr+'0'
length=len(inputstr)
halflength=length/2;
#if even length
if(length%2==0):
#take left part and reverse it(which is equal as the right part )
temp=inputstr[:length/2]
temp=temp[::-1]
#take right part of the string ,move towards lsb from msb..If msb is 9 turn it to zero and move ahead
for j,i in enumerate(temp):
#if number is not 9 then increment it and end loop
if(i!="9"):
substi=int(i)+1
temp=temp[:j]+str(substi)+temp[j+1:]
break;
else:
temp=temp[:j]+"0"+temp[j+1:]
#now you have right hand side...mirror it and append left and right part
output=temp[::-1]+temp
#if the length is odd
if(length%2!=0 ):
#take the left part with the mid number(if length is 5 take 3 digits
temp=inputstr[:halflength+1]
#reverse it
temp=temp[::-1]
#apply same algoritm as in above
#if 9 then make it 0 and move on
#else increment number and break the loop
for j,i in enumerate(temp):
if(i!="9"):
substi=int(i)+1
temp=temp[:j]+str(substi)+temp[j+1:]
break;
else:
temp=temp[:j]+"0"+temp[j+1:]
#now the msb is the middle element so skip it and copy the rest
temp2=temp[1:]
#this is the right part mirror it to get left part then left+middle+right isoutput
temp2=temp2[::-1]
output=temp2+temp
print(output)
similarly for this problem take the left part of given number ...reverse it..store it in temp
inputstr=str(number)
if(inputstr==inputstr[::-1])
print("Pallindrome")
else:
temp=inputstr[:length/2]
temp=temp[::-1]
for j,i in enumerate(temp):
if(i!="9"):
substi=int(i)+1
temp=temp[:j]+str(substi)+temp[j+1:]
break;
else:
temp=temp[:j]+"0"+temp[j+1:]
now depending on length of your number odd or even generate the output..as in the code
if even then output=temp[::-1]+temp
if odd then temp2=temp1[1:]
output=temp2[::-1]+temp
I am not sure about this solution..but hope it helps

Categories