I am working on a python exercise asking for
Write Python programs that read a sequence of integer inputs and print
The smallest and largest of the inputs.
My code so far
def smallAndLarge():
num1 = int(input("Enter a number: "))
num2 = int(input("Enter a number: "))
if num1 > num2:
print(num1,"is the largest number, while",num2,"is the smallest number.")
else:
print(num2,"is the largest number, while",num1,"is the smallest number.")
smallAndLarge()
I am using def smallAndlarge(): since my instructor wants us to use a def function for all of our programs in the future.
My question is how do I ask for multiple inputs from a user until they decided they dont want to add anymore inputs. Thanks for your time.
You could let the user flag when they are finished. (live example)
numbers = [];
in_num = None
while (in_num != ""):
in_num = input("Please enter a number (leave blank to finish): ")
try:
numbers.append(int(in_num))
except:
if in_num != "":
print(in_num + " is not a number. Try again.")
# Calculate largest and smallest here.
You can choose any string you want for the "stop", as long as it's not the same as the initial value of in_num.
As an aside, you should add logic to handle bad input (i.e. not an integer) to avoid runtime exceptions.
In this specific example, you'd also probably want to create smallest and largest variables, and calculate their values after each input. Doesn't matter so much for a small calculation, but as you move to bigger projects, you'll want to keep the efficiency of the code in mind.
Related
I'm a teacher, not a student, I promise :)
Exercise: Declare an array. Use manual input to add integers to array. If the user enters -1, stop accepting input and do not add -1 to the array.
Other requirements: this must be as simple as possible, as it is a very early exercise for students who are just starting to program, and must be compatible with iGCSE PseudoCode, which does not allow for breaks/interrupts.
The three versions we are debating at the moment are:
1. Break
elements = []
while True:
user_input = int(input("Please enter a whole number. When you want to stop type -1 "))
if user_input == -1: break
elements.append(user_input)
Argument against: break is not compatible with pseudocode
2. Repeat Input
elements = []
user_input = int(input("Please enter a whole number. When you want to stop type -1 "))
while user_input != -1:
elements.append(user_input)
user_input = int(input("Please enter a whole number. When you want to stop type -1 "))
Argument against: repeating the input line is inelegant, and a source of errors when you take this approach on larger programs.
3. Repeat Condition
elements = []
user_input = 0
while user_input != -1:
user_input = int(input("Please enter a whole number. When you want to stop type -1 "))
if user_input != -1:
elements.append(user_input)
Argument against: repeating the condition is inelegant, and this is the longest of the three options
Are there any more elegant solutions that still preserve simplicity?
My opinion is that using builtin functions is more pythonic:
list(iter(lambda: int(input("Please enter a whole number. When you want to stop type -1 ")), -1))
Explanation of iter(callable, sentinel): Returns an iterator which calls callable until it returns sentinel (In our case -1).
list() is used to cycle through the iterator and save the elements in a list.
You can also use a function instead of a lambda if you want to do some validation:
def input_number():
value = input("Please enter a whole number. When you want to stop type -1 ")
try:
return int(value)
except ValueError:
return -1
x = list(iter(input_number, -1))
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 3 years ago.
I'm currently a few weeks into my first programming course. The language is Python and the assignment was to write a program that will take two numbers from user input and provide the sum. If the sum is >100, print a message saying it's a big number and don't print the value. If the sum is <100, add the two numbers the input provides and print the sum value.
Here's my code for that which seems to fit what the assignment asked for:
print("Please enter a number between 1 and 100: ")
num1 = int(input())
if num1 > 99:
print("That number is greater than 100. Please try again.")
elif num1 < 1:
print("That number is less than 1. Please try again.")
print("Again, please type any number between 1-100")
num2 = int(input())
if num2 > 99:
print("That number is greater than 100. Please try again.")
elif num2 < 1:
print("That number is less than 1. Please try again.")
sum = num1 + num2
if sum > 100:
print("They add up to a big number")
elif sum < 100:
print("Sum of ", num1, " and ", num2, " is = ", sum)
With this code however, if I for example input '0' as a value for example, it'll print to try again but of course proceed to the next instruction of num2.
In every programming assignment, the instructor gives bonus points for going the extra mile and learning on your own how to somehow better the code, which I always try and achieve. In this example, I'm trying to make it so that if I for example as stated above input the value '0', it'll print to try again and then loop back to the first input instruction rather than proceeding to num2.
I'm not looking for someone to do my homework, but rather a step in the right direction. I've done some research and am not sure what works best here, but it seems like a while loop might work? I'm unsure how to start implementing it with my code already existing.
In such cases it's better to use boolean flags.
bool lock = true;
while(lock):
print("Please enter a number between 1 and 100: ")
num1 = int(input())
if num1 > 99:
print("That number is greater than 100. Please try again.")
elif num1 < 1:
print("That number is less than 1. Please try again.")
else:
lock = false
It'll make sure that till the time a valid input is not entered the loop iterates and asks the user to input the same number again and again.
You could repeat it for the second number too.
I am working on a program that requires the user to enter a number and will continue to loop until a positive number is given. When a positive number is given, it will alert the user and present them with the sum of the digits of their number. However, I thought I had written my code correctly, but it is giving me an incorrect answer. What have I done wrong and how can I fix this?
user_input = float(int(input("Please Enter Your Number:")))
s = 0
while user_input < 0:
float(int(input("Please Enter Another Number: ")))
if user_input > 0:
s += user_input%10
user_input //= 10
print("You've entered a positive number! The sum of the digits is: ", s)
Four things:
Not sure why you storing the input as float, int should suffice.
If you give a negative input, it will enter the while loop. However, in the while loop, you are not actually assigning the new input to user_input. Fix this by adding user_input =
The while loop guarantees user_input is >= 0, so if user_input > 0: is unnecessary.
Probably the most important, to calculate the sum of digits, you need to repeatedly divide and sum, not just do it once. So, add a while loop.
Final code:
user_input = int(input("Please Enter Your Number: "))
s = 0
while user_input < 0:
user_input = int(input("Please Enter Another Number: "))
while user_input:
s += user_input % 10
user_input //= 10
print("You've entered a positive number! The sum of the digits is: ", s)
The if statement is generally used to decide if something should be done once.
If you want to keep going until user_input becomes zero, you'll need a while.
Also, I'm not entirely certain why you're storing the number as a float, especially when you make that from an int anyway. It may as well just be an int.
Additionally, you're loop to re-enter the value if it was negative doesn't actually assign the new value to the variable.
And you probably also want to outdent the print statement lest it be done on every iteration of the loop you're about to add.
Of course, some may suggest a more Pythonic way of summing the digits of a positive number is a simple:
sum([int(ch) for ch in str(x)])
That works just as well, without having to worry about explicit loops.
Another way to solve this is using assert and a function:
def sum_num():
# try get user input
try:
user_in = input('Enter Number: ')
assert int(user_in) > 0
except AssertionError:
# we got invalid input
sum_num()
else:
s_d = sum([int(i) for i in user_in])
print('You\'ve entered a positive number! The sum of the digits is: ', s_d)
#run the function
sum_num()
So this will asked user input, if it is not greater than zero it will throw assertion error, which we catch and return the user to inputting the number by calling the function again. If all is well, we split the input into character and add them up. as list('12') gives ['1','2']. We convert to int and add them. :)
The awesome thing about this is you can add more too the asset to capture other issue as floats, character as invalid inputs. E.g.
Assuming literal_eval is important( from ast import literal_eval)
assert isinstance(literal_eval(user_in),int) and int(user_in)>0
Check if user_in is integer and it is greater than 0. So you won’t get issues when user inputs floats or characters.
I am trying to create a basic calculator that takes the first number, takes the operation(+,-,*,/), and second number. If a person puts in a zero for the first number and/or the second number my program is supposed to go back to the number it was at and ask again for a number other than 0. So if a person puts in 0 for number 2 then my program will take the person back to number two. I am also supposed to do the same concept for the operation but have the person start over if they do not put in the operation available to use which includes the ones previously shown in parentheses. Below is the code I have so far. Any help would be appreciated. My class is currently on while loops and breaks among other things, but I am wondering if those two would be beneficial in my code.
#Programming Fundamentals Assignment Unit 5
#Create a basic calculator function
while True:
#Num1 will require user input
num1 = input ("Enter the first number\n")
#Operation will require user input
operation = raw_input("Enter the operation(+,-,*,/)\n")
#Num2 will require user input
num2 = input("Enter the second number\n")
#Now to define how the operation will be used
if operation == "+":
print num1+num2
elif operation == "-":
print num1-num2
elif operation == "*":
print num1*num2
elif operation == "/":
print num1/num2
else:
print "Please enter an operation"
#Exit will end the calculation from going into a loop
exit()
Put loops around your various inputs to ensure proper checking. So for the first number, you could have:
num1 = 0
while num1 == 0:
num1 = input ("Enter the first number\n")
This'll keep asking till they input something that isn't a 0.
For the second issue (starting over if they enter an invalid operation), you want to immediately check if the operation is valid and if it isn't, then you need to re-loop (which is just by skipping the remaining parts of the current loop).
So to easily check if it's valid:
operation not in ["+","-","*","/"]
which will return false if they enter invalid, and then the second part (skipping the rest of the loop) can easily be accomplished with the "continue" keyword.
if operation not in ["+","-","*","/"]:
continue
This will take you back to the beginning of the loop, asking for new number first number.
When you want to stop execution, you'll need to implement "break" which will break out of the inner most loop that it's a part of.
I was wondering how I would sum up the numbers they input for n even though it's an input and not int. I am trying to average out all the numbers they input.
n=print("Enter as many numbers you want, one at the time, enter stop to quit. ")
a=0
while n!="stop":
n=input("Start now ")
a+=1
In Python 2.x input() evaluates the input as python code, so in one sense it will return something that you can accept as an integer to start with, but may also cause an error if the user entered something invalid. raw_input() will take the input and return it as a string -> evaluate this as an int and add them together.
http://en.wikibooks.org/wiki/Python_Programming/Input_and_Output
You would be better off using a list to store the numbers. The below code is intended for Python v3.x so if you want to use it in Python v2.x, just replace input with raw_input.
print("Enter as many numbers you want, one at the time, enter stop to quit. ")
num = input("Enter number ").lower()
all_nums = list()
while num != "stop":
try:
all_nums.append(int(num))
except:
if num != "stop":
print("Please enter stop to quit")
num = input("Enter number ").lower()
print("Sum of all entered numbers is", sum(all_nums))
print("Avg of all entered numbers is", sum(all_nums)/len(all_nums))
sum & len are built-in methods on lists & do exactly as their name says. The str.lower() method converts a string to lower-case completely.
Here is one possibility. The point of the try-except block is to make this less breakable. The point of if n != "stop" is to not display the error message if the user entered "stop" (which cannot be cast as an int)
n=print("Enter as many numbers you want, one at the time, enter stop to quit. ")
a=0
while n!="stop":
n=input("Enter a number: ")
try:
a+=int(n)
except:
if n != "stop":
print("I can't make that an integer!")
print("Your sum is", a)