Basic while loop program - python

I've been self-teaching Python for the last month. I have an interview for a coding course and need help on writing a program which uses a while loop.
The task is as follows:
Write a program that asks the user to type in 5 numbers, and that outputs the largest of these numbers and the smallest of these numbers. So, for example, if the user types in the numbers 2456 457 13 999 35, the output would be:
The largest number is 2456
The smallest number is 13
Thanks for your help.

Here you go
numbers = [] #this will be the list in which we will store the numbers
while len(numbers) < 5: #len return the length of your list, we want our while loop to repeat 5 times
numbers.append(double(input("enter number: "))) # adds the inputed number to the list
print("The largest number is",max(numbers),"The smallest number is",min(numbers))

Next time you ask questions, please include at least some of your progress so that everyone is willing to help you.
When you learn a language, a good coding style is also important.
Here is an answer for you. I hope you can learn something. You can also try using max() and min() with a list.
input_times = 5
max_num, min_num = -float('inf'), float('inf')
while input_times:
input_times -= 1
try:
num = int(input('Please enter a number:\n'))
if num < min_num:
min_num = num
if num > max_num:
max_num = num
except:
print("Please input an integer!")
input_times += 1
print('The largest number is {max_num} The smallest number is {min_num}'.format(
max_num = max_num, min_num = min_num))

def max_min():
my_list = []
for i in range(1, 6):
temp_val = input("Enter number {}: ".format(i))
my_list.append(int(temp_val))
max_val = max(my_list)
min_val = min(my_list)
return "max value is {} and min value is {}".format(max_val, min_val)
print(max_min())

Related

Function only returning first input of a list and not continuing in the input is outside a range

I'm really new to coding (as in about 3 weeks in), and I'm writing a code where the user is asked to input a number between 0 and 100 and then this number is added to a list. Once the list reaches a length of 10 numbers, it should print the list. I'm using a function to this.
I can get it so it prints a list, but it's only printing the first number that is input. For example if I enter 5, it'll still ask for the other numbers, but it prints the list as [5, 5, 5, 5, 5, 5, 5, 5, 5, 5]. Also if I enter a number outside the range of 0-100 it does ask you to input a different number, but then it stops and prints the list as 'None'.
Below is my code:
def getUser(n):
mylist = []
while 0 < n < 100:
mylist.append(n)
int(input("Please enter a number between 0 and 100: "))
if len(mylist) == 10:
return(mylist)
else:
int(input("This number is not in the range of 0-100, please input a different number: "))
n = int(input("Please enter a number between 0 and 100: "))
print("The numbers you have entered are: ", getUser(n))
I'm guessing its to do with the while/else loop but as I said I'm new to this and it all feels so overwhelming, and trying to google this just seems to bring about super complicated things that I don't understand!! Thanks
First : Why you get [5, 5, 5, 5, 5, 5, 5, 5, 5, 5] :
int(input("Please enter a number between 0 and 100: "))
You should give this to n first :
n=int(input("Please enter a number between 0 and 100: "))
Then, it gets out of the loops because you go in the else, and then you don't go back in the while. Then your function ended, without return, so none
To be honest, I don't understand why your code gets out of the while loop if you give a number out of the range, as the value is not given to n. If someone could explain in comment, that would be great !
I would do it like that :
def getUser():
mylist = []
while len(mylist) < 10:
n = int(input("Please enter a number between 0 and 100: "))
if (0 < n < 100):
mylist.append(n)
else:
print('This is not between 0 and 100 !')
return mylist
print("The numbers you have entered are: ", getUser())
Then you will be asked number from 0 to 100 (excluded) until you get a size of 10.
So here's what you were doing wrong
def getUser(n):
mylist = []
while 0 < n < 100:
mylist.append(n)
n = int(input("Please enter a number between 0 and 100: "))
if len(mylist) == 10:
return(mylist)
else:
int(input("This number is not in the range of 0-100, please input a different number: "))
n = int(input("Please enter a number between 0 and 100: "))
print("The numbers you have entered are: ", getUser(n))
You notice any difference in the edited code?
You were never re-assigning the value of the variable n
So you would just add whatever value you passed to getUser every time (and it would be the same value every time)
Don't be afraid to ask for help if you're stuck!
P.S.
You can also move a line somewhere to somewhere else to make it behave a bit better if you're up to the challenge ;)
def getUser(n):
mylist = []
t = True
while t:
n =int(input("Please enter a number between 0 and 100: "))
if n >0 and n<=100:
mylist.append(n)
if len(mylist) == 10:
return(mylist)
t = False
elif n < 0 or n >100:
print('This number is not in the range of 0-100, please input a different number:')
Ok, you are trying to use while instead of if.
Here is what I would do - I will explain it soon:
def get_user():
mylist = []
for i in range(5):
n = int(input("Please enter a number between 0 and 100: "))
if n <= 100 and 0 <= n:
mylist.append(n)
else:
print("This is not between 0 and 100 !")
i = i - 1
return mylist
Going through the code
for i in range(5)
Here we use the for to iterate through a range
of numbers (0 - 5). for will assign i to the smallest
number in the range and constantly add 1 to i every iteration until
i is out of the range. See this for more info on range
if n <= 100 and 0 <= n:
Here and checks if 2 expressions are true.
In this case, if n is less than or equal to hundred and more than or equal to 0.
You could use and any number of times you want like this:
if 1 < 100 and 100 > 200 and 20 < 40:
print("foo!")
Now look at the else :
else:
i = i - 1
Here, we subtract 1 from i and thus, decreasing our progress by one.
Also note that my function is called get_user() and not getUser().
In python, we use snake case and not camel case.
I hope this answer helps. I have given small hints in my answer.
You should google them! I also am not directly giving you the logic.
Try to figure it out! That way you would have a good understanding of what I did.

python for loop wont change value

So im new to python and this question should be fairly easy for anybody in here except me obvisouly haha so this is my code
for c in range(0,20):
print("number",c+1)
number = input ("Enter number:\n")
number = int(number)
if (number < 1 or number > 9):
print("try again by inputing a positive number < 10")
c -=1
so as you may think if the number someone inputs is bigger than 9 or smaller than 0 i just want my c to stay where it is so i get 20 positive numbers from 1-9 instead it doesnt do that and it keeps increasing even tho i have the c-=1 thingy down there
First, do not use range(0,20) but range(20) instead.
Second, range returns an iterator. This means, that when you do c-=1 you do not go back in the iterator, you decrease the number returned by the iterator. Meaning that if c=5 and the number you entered in input is 20, c will become 4, but when returning to the start of the loop, c be be 6.
You probably want something of this sort:
c = 0
while c < 20:
print("number",c+1)
number = input ("Enter number:\n")
number = int(number)
if (number < 1 or number > 9):
print("try again by inputing a positive number < 10")
continue
c += 1
an alternative and simple solution to this would be:
i=20
while(i!=0):
number = input("Enter number:\n")
number = int(number)
if (number <1 or number >9):
print("Invalid no try within 0-9 ")
else
print(number)
i-=1

Is it possible to have a user enter integers and add them using a while loop in python?

This is for one of my assignments.
Here is the question just for clarity on what I am trying to do. Please do not give me the answer, just if you could help me understand what I need to do.
Write a Python program that uses a WHILE loop. The program must prompt the user to enter an integer number. The value must be added to a total. The loop must continue until the total exceeds 45. After the loop, the average of the numbers must be calculated. The program must display each of the input values, as well as the sum of all values and the average value.
*** enhancement, replace the user prompt with a random number selector.
This is the current code I am using:
num = int(input('Enter as many integers as you want: '))
numList =num.split()
print('All entered numbers ', numList)
sum = 0
while num >= 45:
print('Sum of all numbers ', sum)
avg = sum / num
print('Average of all numbers ', avg)
This, of course, is not working, I have figured out how to do it with a for loop ( from the internet ) I just cannot seem to understand how to link the input function with the while loop.
You want to read numbers one at a time, until the sum exceeds 45.
total = 0
num_list = []
while total < 45:
num = int(input(...))
num_list.append(num)
total += num
# Now compute the average and report the sum and averages
To make sure the last number is not added to the list if that would put the total over 45,
total = 0
num_list = []
while True:
num = int(input(...))
new_total = total + num
if new_total > 45:
break
num_list.append(num)
total = new_total
The while loop should be used to get values from the user : While the total of the given values is lower than 45, ask the user for another value
numList = []
total = 0
while True:
num = int(input('Enter an integer: '))
if (total + num) > 45:
break
numList.append(num)
total = total + num
avg = total / len(numList)
print('Sum of all numbers ', total)
print('Average of all numbers ', avg)

Write a program in python to find the sum of the first 200 jumpy numbers

I just started learning python and I have a task to submit as homework.
I have to write a program that prints out the sum of the first 200 jumpy numbers.
Jumpy numbers are numbers whose digits are neither increasing nor decreasing. for example 101, 102, 103, 104.... unlike increasing numbers such as 2347, 378, 459 and decreasing numbers 975, 854, 741.
From the little I know, I have written this, but i cant figure out how to do the rest. Please help...
#python program to find the sum of first 200 jumpy numbers
minimum = int(input(" Please Enter the Minimum Value : "))
maximum = int(input(" Please Enter the Maximum Value : "))
total = 0
for number in range(minimum, maximum+1):
if(number[2] == 1):
print("{0}".format(number))
total = total + number
print("The Sum of Jumpy Numbers from {0} to {1} = {2}".format(minimum, number, total))
Gokul's answer is very nice, however if you aren't a professional coder (me too), then I wrote this simpler version, however much longer.
#python program to find the sum of first 200 jumpy numbers
minimum = int(input(" Please Enter the Minimum Value : "))
maximum = int(input(" Please Enter the Maximum Value : "))
total = 0
def isJumpy(x):
increasing, decreasing = True,True
x = [int(x) for x in str(x)]
x = list(map(int,x))
for n in range(len(x)-1):
if int(x[n]) > int(x[n+1]):
pass
else:
increasing = False
if int(x[n]) < int(x[n+1]):
pass
else:
decreasing = False
if increasing == False or decreasing == False:
return True
else:
return False
for i in range(minimum,maximum+1):
if isJumpy(i):
total += i
print("The Sum of Jumpy Numbers from {0} to {1} = {2}".format(minimum, maximum, total))
If you have any questions, or the code is wrong please let me know. Btw this was a fun little challenge :)
min = 1
max = 100
f=lambda n,i=1:n and-~f(n-g(i),i+1)
g=lambda i:i<10or i%100%11%9==g(i/10)>0
values = [i for i in range(min,max) if g(i)]
print values
print sum(values)
g(i) checks for jumping number or not
Use your custom min and max. lambda functions are used for smaller expressions.
lambda arguments : expression
sum() is inbuilt function of python.
Took help from answer
def is_jumpy (n):
num_list = [int (x) for x in str (n)]
goes_up = goes_down = False
for index in range (1, len (num_list)):
if (num_list[index-1] < num_list[index]):
goes_up = True
elif (num_list[index-1] > num_list[index]):
goes_down = True
if (goes_up and goes_down):
return True
return False
sum=0
for i in range (min,max):
if (is_bouncy (i)):
sum += i
print(f'the sum of the jumpy numbers between{min} and {max} is {sum}')

"'int' object is not iterable" when asking for a Number input (beginner)

I am planning to create a program which basically lists the Fibbonacci sequnce up to 10,000
My problem is that in a sample script that I wrote I keep getting the error 'int' object is not iterable
My aim is that you enter a number to start the function's loop.
If anyone would help out that would be great
P.S I am a coding noob so if you do answer please do so as if you are talking to a five year old.
Here is my code:
def exp(numbers):
total = 0
for n in numbers:
if n < 10000:
total = total + 1
return total
x = int(input("Enter a number: "), 10)
exp(x)
print(exp)
numbers is an int. When you enter the number 10, for example, the following happens in exp():
for n in 10:
...
for loops through each element in a sequence, but 10 is not a sequence.
range generates a sequence of numbers, so you should use range(numbers) in the for loop, like the following:
for n in range(numbers):
...
This will iterate over the numbers from 0 to number.
As already mentioned in comments, you need to define a range -- at least this is the way Python do this:
def exp(numbers):
total = 0
for n in range(0, numbers):
if n < 10000:
total = total + 1
return total
You can adjust behavior of range a little e.g. interval is using. But this is another topic.
Your code is correct you just need to change :
for n in numbers:
should be
for n in range(0, numbers)
Since you can iterate over a sequence not an int value.
Good going, Only some small corrections and you will be good to go.
def exp(numbers):
total = 0
for n in xrange(numbers):
if n < 10000:
total += 1
return total
x = int(input("Enter a number: "))
print exp(x)

Categories