This code is for asserting values into the list until the user inputs a negative number.
Is there a way better to implement it?
Below is my tried version.
i = -1
while i > -1:
x = raw_input("Enter array limit")
for i in limit(x):
listArr = list()
y = raw_input("Enter number")
y.append(listArr)
print (listArr)
Something like this should meet the requirements:
odds = [] # similiar to `listArr` but we only want odd numbers
limit = 5
for _ in range(limit): # Input 5 numbers into an array
y = int(input('Enter number: '))
if y > -1 and y % 2 !=0: # if odd number
odds.append(y) # add to array
else:
break # break after a negative number as input
if odds:
print(min(odds)) # and display minimum odd number
# and if no negative integer input then also display minimum odd number
else:
print(0) # and if no odd number display zero
If Python2 use raw_input() as used in question code, otherwise use input().
Related
The program should read a positive integer n from the user to decide how many number to generate.
The random numbers should be in the intervall [1, 100].
I should then print the average value, smallest value and largest value.
But WITHOUT using lists or any other data structure.
I managed to get the average value but I still need to get smallest and largest. any advise?
here is how my code look like so far
You can use the built in min() and max() functions. Here's a bit of code, should be pretty self explanatory:
import random
n = 20
# set up the values
smallest = 101
biggest = -1
for i in range(n):
x = random.randint(1,100)
# take the smallest of the new random number and the current smallest
smallest = min(x, smallest)
# take the biggest of the new random number and the current biggest
biggest = max(x, biggest)
print(smallest, biggest)
If I understand your question, you are trying to print the smallest and largest number of these five numbers without using a list.
You can easily create variables, and change them, if a higher/lower value is generated, then the highest/lowest value before. Hope it helps:
import random
n = int(input("Enter a number of integers to be generated: "))
if n < 0:
print("Please enter a positive integer!")
else:
highest_value = 0
smallest_value = 100
sum_of_random = 0
for x in range(n):
x = random.randint(1, 100)
sum_of_random += x
if x > highest_value:
highest_value = x
if x < smallest_value:
smallest_value = x
print(x, end = " ")
print("\n")
avg = round(sum_of_random / n, 2)
print(avg)
print(highest_value)
print(smallest_value)
If this answers your question, please mark it as a correct answer.
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
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)
This question already has answers here:
Choose largest odd number python
(28 answers)
Closed 4 months ago.
Hi I am new to programming and I made a program for a finger exercise in the book "Introduction to computation and programming using python"
here's the finger exercise : Write a program that examines three variables—x, y, and z—
and prints the largest odd number among them. If none of them are odd, it
should print a message to that effect.
I made this,
l = []
x = int(input("Enter a number for x: "))
y = int(input("Enter a number for y: "))
z = int(input("Enter a number for z: "))
l.append(x)
l.append(y)
l.append(z)
def testodd(n):
return n%2 != 0
def maxodd (l):
oddlist = []
for i in l:
if testodd(i):
oddlist.append(i)
else:
continue
return max(oddlist)
print(maxodd(l))
Program sometimes work properly and sometimes not for example I gave x=231 y=23 and z=678 it says "none of them are odd" what's the problem about this program ?
First we create a list that will contain all the numbers, then we sort that list in descending order (reverse=True) and then we look if there is any odd number. If we don't find any odd number in the list we print the message:
numbers = []
for _ in range(3): # Iterate 3 times
numbers.append(int(input("Enter a number:"))) # Append 1 number each time
numbers.sort(reverse=True) # Sort the numbers in descending order
for n in numbers: # Iterate over the numbers
if n % 2 != 0: # If the number is odd we have found the maximum odd value
print(n) # Print the value
break # Finish the loop
else: # An else block in a for loop will execute if no break was found
print("none of them are odd") # Print the message
A more advanced way to retrieve the numbers would be:
numbers = sorted((int(input("Enter a number:")) for _ in range(3)), reverse=True)
that would replace the first 4 lines.
This is simpler if you put only the odd numbers into a list.
x = int(input("Enter a number for x: "))
y = int(input("Enter a number for y: "))
z = int(input("Enter a number for z: "))
odd_numbers = [value for value in (x,y,z) if value%2]
if odd_numbers:
print("The greatest odd number is", max(odd_numbers))
else:
print("None of the numbers is odd.")
The program finds the maximal number and checks if it's odd.
To find the maximal odd number, you can use list comprehension:
Put the numbers to check at a list numbers = [x, y, z]
Loop over the numbers t for t in numbers, and filter in those who are odd if t % 2 != 0.
Find the maximal among them (#2): max([t for t in numbers if t % 2 != 0])
x = int(input("Enter a number for x: "))
y = int(input("Enter a number for y: "))
z = int(input("Enter a number for z: "))
# Put numbers in a list
numbers = [x, y, z]
# Filter the odd numbers, and find the max
print(max([t for t in numbers if t % 2 != 0]))
You may just append all numbers entered into a list, sort all odds into another list and get the maximum value:
numbs = []
x = int(input("Enter a number for x: "))
numbs.append(x)
y = int(input("Enter a number for y: "))
numbs.append(y)
z = int(input("Enter a number for z: "))
numbs.append(z)
odds = [x for x in numbs if x%2==1]
if odds == []:
print('No odd number was entered')
else:
print(max(odds))
I am new to Python and currently reading Python 3 for absolute beginner and face following problem.
I would like to calculate factorial with procedure.
request user to input an non negative number n
then use for loop to calculate factorial
and the code is like that:
N = input("Please input factorial you would like to calculate: ")
ans = 1
for i in range(1,N+1,1):
ans = ans*i
print(ans)
while i would like to add a feature to check whether input number N is non-negative number. like:
if N != int(N) and N < 0:
I want the user to input N again if it is NOT non-negative number.
Thanks for your gentle help.
The construct could look like this:
while True:
N = input("Please input factorial you would like to calculate: ")
try: # try to ...
N = int(N) # convert it to an integer.
except ValueError: # If that didn't succeed...
print("Invalid input: not an integer.")
continue # retry by restarting the while loop.
if N > 0: # valid input
break # then leave the while loop.
# If we are here, we are about to re-enter the while loop.
print("Invalid input: not positive.")
In Python 3, input() returns a string. You have to convert it to a number in all cases. Your N != int(N) thus makes no sense, as you cannot compare a string with an int.
Instead, try to convert it to an int directly, and if that doesn't work, let the user enter again. That rejects floating point numbers as well as everything else which is not valid as an integer.
In Python's math library, there is a factorial function. You can use it like so:
import math
...
ans = math.factorial(N)
Since you want to calculate using a loop however, have you considered the following?
ans = -1
while ans < 0:
N = input("Please enter a positive integer: ")
if N.isdigit() == True:
n = int(N)
if n >= 0:
ans = n
for x in range (n-1, 1, -1):
ans *= x
print (ans)
Note, the second solution doesn't work for N = 0, where ans = 1 is correct by definition of factorial.
Number = int(input("Enter the number to calculate the factorial: "))
factorial = 1
for i in range(1,Number+1):
factorial = i*factorial
print("Factorial of ",Number," is : ", factorial)
def factorial(a):
if a == 1:
return 1
else:
return a * factorial(a - 1)
print('factorial of number', factorial(5))
Start
Declare Integer n,i,n!
Display “Enter a nonnegative integer.”
Input n
For i=1 to n-1 Step1,
Display “n!=i*n”
End for
Stop
You can check math module for python.
# math.factorial(x)
Return x factorial.
Raises ValueError if x is not integral or is negative.