This question already has answers here:
Is it possible to implement a Python for range loop without an iterator variable?
(15 answers)
Closed 3 months ago.
So I have this assignment and I have a question about a part I don't know how to do, can you guys help me?
def main():
# Please see the comments
largest = 0
for index in range(3): # Enter the value(s) in the parenthesis to run the loop 3 times
number1 = int(input("Please enter the first number: "))
number2 = int(input("Please enter the second number: "))
number3 = int(input("Please enter the third number: "))
# insert call to function find_largest after this comment.
# find_largest will take in three parameters and will return the largest of the 3 numbers
result = find_largest(number1, number2, number3)
# insert the statement to print the three numbers entered and the largest number after this comment.
print("The numbers you entered were, \n", [number1, number2, number3])
print ("The largest of the numbers you entered is", result)
def find_largest(a, b, c):
# insert parameters in the parenthesis
# Write the code for this function here.
# find_largest will take in three parameters and will return the largest of the 3 numbers
# These three numbers are passed in as parameters from the main function
# Hint: if and elif - no loop needed here
if (a > b) and (a > c):
largest = a
elif (b > a) and (b > c):
largest = b
else:
largest = c
return largest
main() # this is the call to main() that will make the program run
So, my question is the part:
for index in range(3): # Enter the value(s) in the parenthesis to run the loop 3 times
I don't know what to add so the loop run 2 more times after it has found the largest number
The loop you have makes the first two iterations of the loop pointless, as each time you loop, you are reassigning new numbers to the three number variables. As a result, only the numbers entered in the last iteration of the loop are ever used for anything. I think this would make more sense:
numbers = []
for i in range(3):
input = int(input("Enter number: "))
numbers.append(input)
This will give you a list called numbers with 3 numbers in it entered by the user. Then you can do what you want with them. Having said that, you really don't need a for loop to do this. As Craig Burgler mentioned.
Alternatively(though this doesn't use range...):
number1 = 0
number2 = 0
number3 = 0
for i in (number1, number2, number3):
i = int(input("Enter number: "))
The code as written will ask for three numbers three times, overwriting the first and second set of numbers that the user enters. If the assignment is to get three numbers from the user and tell the user which is largest, then you do not need the for loop. The three input statements will do the trick.
Related
What I want to do, is to write a program that given a sequence of real numbers entered by the user, calculates the mean. Entering the sequence should be finished by inputting ’end’. To input more than 1 number I try:
num=input("Enter the number: ")
while num!="end":
num = input("Enter the number: ")
But I don't want the program to "forget" the first 'num', because I'll need to use it later to calculate the mean. What should I write to input and then use more than one value, but not a specific number of values? User should can enter the values until they enter 'end'. All of values need to be use later to calculate the mean. Any tip for me?
First, define an empty list.
numbers = []
Then, ask for your input in an infinite loop. If the input is "end", break out of the loop. If not, append the result of that input() to numbers. Remember to convert it to a float first!
while True:
num = input("Enter a number: ")
if num == "end":
break
numbers.append(float(num))
Finally, calculate the mean:
mean = sum(numbers) / len(numbers)
print("Mean: ", mean)
However, note that calculating the mean only requires that you know the sum of the numbers and the count. If you don't care about remembering all the numbers, you can just keep track of the sum.
total = 0
count = 0
while True:
num = input("Enter a number: ")
if num == "end":
break
total += float(num)
count += 1
print("Mean: ", total / count)
Mean is sum of all nos/total nos. Let's take input from user and add it to list, because we can easily use sum() function to find sum and len() function to find total nos. Your code:
obs=[]
while True:
num=input("Enter number: ")
if num=="end":
break
else:
obs.append(int(num))
print("Mean: ",(sum(obs)/len(obs)))
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 1 year ago.
num_length = int(input('Enter the length of the sequence:\n'))
nomlist=[]
count = 0
for i in range (num_length):
num = int(input('Enter number '+str(i+1)+ ':\n'))
nomlist.append(num)
this is a part of the solution for my homework, but now I need to rewrite it in a recursive form and I am not sure how I am supposed to change the above code in a recursive function. The above code basically asks the user to input a number and based on that number the program repeatedly asks the user for input and appends it into the list. Please help me.
num_length = int(input('Enter the length of the sequence:\n'))
nomlist=[]
def rec(l, count, num_length):
if count <= 0:
return
else:
num = int(input('Enter number '+str(num_length-count+1)+ ':\n'))
l.append(num)
rec(l, count-1, num_length)
rec(nomlist, num_length, num_length)
print(nomlist)
Here's a recursive function that makes use of default parameter values and conditional expressions to minimize the amount of code required:
def get_nums(length, numbers=None, entry=1):
numbers = [] if not numbers else numbers
numbers.append(input(f' Enter number {entry}: '))
return numbers if entry == length else get_nums(length, numbers, entry+1)
length = int(input('Enter the length of the sequence: '))
nomlist = get_nums(length)
print(nomlist)
I have an assignment as follows
Write a program that repeatedly asks the user to enter a number, either float or integer until a value -88 is entered. The program should then output the average of the numbers entered with two decimal places. Please note that -88 should not be counted as it is the value entered to terminate the loop
I have gotten the program to ask a number repeatedly and terminate the loop with -99 but I'm struggling to get it to accept integer numbers (1.1 etc) and calculate the average of the numbers entered.
the question is actually quite straightforward, i'm posting my solution. However, please show us your work as well so that we could help you better. Generally, fro beginners, you could use the Python built-in data types and functions to perform the task. And you should probably google more about list in python.
def ave_all_num():
conti = True
total = []
while conti:
n = input('Input value\n')
try:
n = float(n)
except:
raise ValueError('Enter values {} is not integer or float'.format(n))
if n == -88:
break
total.append(n)
return round(sum(total)/len(total),2)
rslt = ave_all_num()
Try the following python code. =)
flag = True
lst=[]
while(flag):
num = float(raw_input("Enter a number. "))
lst+=[num]
if(num==-88.0): flag = False
print "Average of numbers: ", round( (sum(lst[:-1])/len(lst[:-1])) , 2)
enter code hereThank you for the prompt replies. Apologies. This is the code i was working on:
`#Assignment2, Question 3
numbers=[]
while True:
num=int(input("Enter any number:"))
if num==float:
continue
if num==-88:
break
return print(" the average of the numbers entered are:",sum(numbers)/len(numbers)`
This question already has answers here:
Python: raw_input and unsupported operand type(s)
(3 answers)
Closed 7 years ago.
I am trying to ask the user to enter any number and then ask the user to enter any names, then store this input in a list.
However, when I enter any number, it asks to enter name only one time and shows the output in list:
def main():
# a = 4
a = input("Enter number of players: ")
tmplist = []
i = 1
for i in a:
pl = input("Enter name: " )
tmplist.append(pl)
print(tmplist)
if __name__== "__main__":
main()
output:
Enter number of players: 5
Enter name: Tess
['Tess']
The for loop should run 5 times and user entered 5 values get stored in a list.
You need to convert the number of players to integer and then loop for that much amount of times, you can use the range() function for this . Example -
def main():
num=int(input("Enter number of players: "))
tmplist=[]
for _ in range(num):
pl=input("Enter name: " )
tmplist.append(pl)
print(tmplist)
Since you are using Python3
a=input("Enter number of players: ")
means a is a string "5". Since this is only one character long - the loop will run just once
You need to use
a = int(input("Enter number of players: "))
You'll also need to change the loop
for i in range(a):
I recommend using more meaningful variable names - especially if this is homework
def main():
number_of_players = int(input("Enter number of players: "))
player_list = []
for i in range(number_of_players):
player = input("Enter name: " )
player_list.append(player)
print(player_listlist)
if __name__== "__main__":
main()
You got a string a which presumably contained something like '5'. Then you initialize a counter i. Then you loop through this string, which, since it's '5', resulted in one iteration, because there's only one character in '5'.
First you have to change it into a number, with a = int(a).
With a as a number, you still can't loop through that, because a number isn't an iterable.
So then you should create a range object to loop over, with for i in range(a):.
Then you will be able to carry out your operations as expected.
Since the input a is a string
you need to convert it to a number and then use a different for.
it should be
def main():
#a=4
a=int(input("Enter number of players: "))
tmplist=[]
i=0
while i < a:
pl=input("Enter name: ")
tmplist.append(pl)
i+=1
print(tmplist)
main()
How do I add numbers in between two numbers the user inputted in Python 2.7. So a person would input 75 and 80 and I want my program to add the numbers in between those two numbers. I am very new to programming and python so any help would be awesome!
This example excludes 75 and 80. If you need to include them replace with print sum(range(n1,n2+1))
n1=input('Enter first number ')
n2=input('Enter second number ')
print sum(range(min(n1,n2)+1,max(n1,n2)))
#DSM is right!
n1=input('Enter first number ')
n2=input('Enter second number ')
print (n2-n1+1)*(n2+n1)/2
to capture user input use number1 = raw_input('Input number'). From there I'm not exactly sure what you mean from adding numbers between the two? If you want 76+77+78+79 in that example
number1 = raw_input('Input number')
number2 = raw_input('Second number')
result = 0
for n in range(int(number1)+1, int(number2)):
result+=n
print result
Here's a quick sample that should handle a few different situations. Didn't go that in-depth since I don't know the scope of the situation. Realistically you should do some form of type-checking and loop until valid input is entered. However this should get you started:
def sumNums(a, b):
total = 0
if a < b:
total = sum(range(a+1, b))
elif b < a:
total = sum(range(b+1, a))
return total
num1 = int(raw_input("First Number: "))
num2 = int(raw_input("Second Number: "))
print sumNums(num1, num2)
However I'm sure there's a more comprehensive way using lists and sum() but it seems like you only need a basic working example.
easy you just go
def add(x,y):
if True:
return add(x, y)
else:
return None
add([1,2,3,4][0], [1,2,3,4][2])