I am trying to solve a simple problem. Enter three numbers and find the average of the largest two.
while True:
try:
n1 = int(input("Enter n1: "))
n2 = int(input("Enter n2: "))
n3 = int(input("Enter n3: "))
except ValueError:
print ("Enter an integer: ")
continue
else:
break
mylist = [n1,n2,n3]
mylist.remove(min(mylist))
print (float(sum(mylist))/2)
Why is this not working. If I remove the assignment n_avg and keep the last two lines of code as shown below it works. Can someone explain why?
mylist.remove(min(mylist))
print (float(sum(mylist))/2)
I wanted to share a slightly cleaner code.
mylist = []
while len(mylist) < 3:
try:
mylist.append(int(input("Enter a number:")))
except ValueError:
print ("Please enter an integer")
mylist.remove(min(mylist))
print (sum(mylist)/2.)
Works as expected.
Related
I want to make a code that allows me to check if the number I have entered is really a number and not a different character. Also, if it is a number, add its string to the list.
Something like this:
numbers = []
num1 = input("Enter the first number: ")
try:
check = int(num1)
numbers.append(num1)
print("The number {} has been added.".format(num1))
except ValueError:
print("Please, enter a number")
I have to do the same for several numbers, but the variables are different, like here:
num2 = input("Enter the next number: ")
try:
check = int(num2)
numbers.append(num2)
print("The number {} has been added.".format(num2))
except ValueError:
print("Please, enter a number")
Is there any way to create a code that does always the same process, but only changing the variable?
If you are trying to continue adding numbers without copying your code block over and over, try this:
#!/usr/bin/env python3
while len(numbers) < 5: #The five can be changed to any value for however many numbers you want in your list.
num2 = input("Enter the next number: ")
try:
check = int(num2)
numbers.append(num2)
print("The number {} has been added.".format(num2))
except ValueError:
print("Please, enter a number")
Hopefully this is helpful!
Create the list in a function (returning the list). Call the function with the number of integers required.
def get_ints(n):
result = []
while len(result) < n:
try:
v = int(input('Enter a number: '))
result.append(v)
print(f'Number {v} added')
except ValueError:
print('Integers only please')
return result
Thus, if you want a list of 5 numbers then:
list_of_numbers = get_ints(5)
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 3 years ago.
I am trying to write a function to get 2 int values from a user until their sum is 21, Simple!!
The aim is to keep prompting the user to pass 2 int values until the condition is met. I am not sure where the code breaks as it stops when either conditions is met, both if true or false.
def check_for_21(n1,n2):
result = 0
while True:
while result != 21:
try:
n1 = int(input("Enter first number >> "))
n2 = int(input("Enter second number >> "))
if n1+n2 != 21:
print("You did not get to 21! ")
else:
print("You got it! ")
except:
if n1+n2 == 21:
print("You got it! ")
else:
break
break
This is what you are looking for you had multiple logical errors! However, the idea was there but wrongly formatted. In this program, it runs continuously until you enter two numbers and their sum is 21
def check_for_21():
while True:
n1 = int(input("Enter first number >> "))
n2 = int(input("Enter second number >> "))
if n1+n2 != 21:
print("You did not get to 21! ")
else:
print("You got it! ")
break
check_for_21()
Try this. This will meet your requirment.
a = 5
while (a<6):
n1 = int(input("Enter first number >> "))
n2 = int(input("Enter second number >> "))
if n1+n2 == 21:
print("You got it ")
break
else:
print("You did not get to 21! ")
Take the input, check for result, if you get 21, break the loop.
def check_for_21(n1,n2):
result = 0
while True:
try:
n1 = int(input("Enter first number >> "))
n2 = int(input("Enter second number >> "))
if n1+n2 != 21:
print("You did not get to 21! ")
else:
print("You got it! ")
break
except:
pass
Below is the test result of the code that worked for me:
I have been asked to make a piece of code including a for loop and a while loop. I was asked to:
Get the user to input a number
Output the times table for that number
Starts again every time it finishes
I was able to do the for loop like so:
num= int(input ("Please enter a number."))
for x in range (1,13):
print (num,"x",x,"=",num*x)
But I cannot figure out how to make it repeat, any ideas?
Just put your code inside a while loop.
while True:
num = int(input("Please enter a number: "))
for x in range(1,13):
print("{} x {} = {}".format(num, x, num*x))
I think it would be nice for you to handle errors.
If a user decides to enter a non digit character it will throw an error.
while True:
num = input('please enter a number')
if num ==0:
break
elif not num.isdigit():
print('please enter a digit')
else:
for x in range(1, 13):
mult = int(num)
print('%d x %d = %d' %(mult, x, mult*x))
I am just starting my first computer science class and have a question! Here are the exact questions from my class:
"Write a complete python program that allows the user to input 3 integers and outputs yes if all three of the integers are positive and otherwise outputs no. For example inputs of 1,-1,5. Would output no."
"Write a complete python program that allows the user to input 3 integers and outputs yes if any of three of the integers is positive and otherwise outputs no. For example inputs of 1,-1,5. Would output yes."
I started using the if-else statement(hopefully I am on the right track with that), but I am having issues with my output.
num = int(input("Enter a number: "))
num = int(input("Enter a number: "))
num = int(input("Enter a number: "))
if num > 0:
print("YES")
else:
print("NO")
I have this, but I am not sure where to go with this to get the desired answers. I do not know if I need to add an elif or if I need to tweak something else.
You probably want to create three separate variables like this:
num1 = int(input("Enter number 1: "))
num2 = int(input("Enter number 2: "))
num3 = int(input("Enter number 3: "))
In your code you only keep the value of the last number, as you are always writing to the same variable name :)
From here using an if else statement is the correct idea! You should give it a try :) If you get stuck try looking up and and or keywords in python.
On the first 3 lines, you collect a number, but always into the same variable (num). Since you don't look at the value of num in between, the first two collected values are discarded.
You should look into using a loop, e.g. for n in range(3):
for n in range(3):
num = int(input("Enter a number: "))
if num > 0:
print("YES")
else:
print("NO")
Use the properties of the numbers...
num1 = int(input("Enter number 1: "))
num2 = int(input("Enter number 2: "))
num3 = int(input("Enter number 3: "))
Try Something like this
if num1< 0 or num2 <0 or num3 < 0:
print ('no')
elif num1 > 0 or num2 > 0 or num3 > 0:
print ('yes')
I have this simple code:
var = 1
while var == 1 :
try:
num = int(raw_input("Enter a number :"))
except ValueError:
print "Thats not a number!"
continue
try:
num2 = int(raw_input("Enter another number :"))
except ValueError:
print "Thats not a number!"
continue
print "Sum of previous 2 inputs:="+str(num+num2)
print "Good bye!"
Now first continue statement does the job, but the second one, not. Because it goes back at the top of loop, but I need it to go back where second exception was caught, so it would ask to enter second number again, not first number.
Any ideas?
You can factor out entering a number to a function – this spares you writing the same code twice:
def input_int(prompt):
while True:
try:
return int(raw_input(prompt))
except ValueError:
print "That's not a valid integer!"
...
num = input_int("Please enter a number: ")
num2 = input_int("Please enter another number: ")