Python coding help for a newbie - python

I am new to coding and I'm trying to figure a simple code. The user will input a number, that must be an integer greater than 0, then asked to enter a second integer, greater than the previous one. once the second value is entered the two inputs should be displayed as well as the even and odd numbers in-between the two inputs. Currently, the code I have doesn't distinguish the value of the second input, allowing it to be lesser than the previous one.
number = input('please enter a number:')
val = int(number)
if val > 0:
integer = raw_input('please pick a second integer:')
if raw_input < val:
print 'please pick an integer greater than the previos input'
if raw_input > val:
print
if val < 0:
print 'please pick a positive integer greater than zero'

You could ask for the inputs before the while loop check and then ask again, but I like the cleaner appearance of only having the input prompt appear once in the code, so we can set up some conditions that will trigger the loop and the prompt.
We can initialize num1 = -1 and then our while loop condition will be triggered and repeat until we receive and int larger is larger than 0.
Then we can do the same with num2 by initializing it as num1 - 1, this will trigger our while loop that will continue to prompt until num2 is greater than num1.
Finally we can print a list of the range from num1 to num2 + 1 since the end is not inclusive we should extend the range by 1
num1 = -1
while num1 <= 0:
num1 = int(input('Enter a number greater than 0: '))
num2 = num1 - 1
while num2 <= num1:
num2 = int(input('Enter a number greater than {}: '.format(num1)))
print(list(range(num1, num2+1)))
Enter a number greater than 0: 1
Enter a number greater than 1: 5
[1, 2, 3, 4, 5]

Related

Why does my program to calculate the average of numbers entered into a while loop not work as expected?

I am new to coding. I would like to attend a course but there are assessments first in order to be chosen.
The question I am stuck on is:
Write a program that always asks the user to enter a number. When the user enters the negative number -1, the program should stop requesting the user to enter a number. The program must then calculate the average of the numbers entered excluding the -1.
num = 0
inputs = []
while True:
num = int(input("Please enter a number between -1 and 5: "))
if num > -1:
break
else:
inputs.append(int(num))
print (sum(inputs) / len(inputs))
so lets break this down together.
This is fine.
num = 0
inputs = []
You will want to modify this while true statement to be while True (if using python) like below
while True:
Next, it doesn't explicitly say integers, and technically there are different number types, but for simplicity sake we check to see if the number entered is an integer to avoid trying convert a letter to an integer. (This will cause a ValueError). We make a decision to ignore this type of bad input and continue.
input_value = input("Please enter a number between -1 and 5: ")
try:
num = int(input_value)
except ValueError:
continue
The condition for stopping the loop is entering -1 (if I understood the question properly). So, first check to see if the number entered matches the condition to stop: if num == -1: break.
if num == -1:
break
otherwise, you will want to check to be sure the number is in range before it is added to your inputs array, otherwise ignore it and wait for the next input. The question asks for any number, but since you're prompting for specific input, we're making a decision here not to accept numbers out of bounds of what was prompted for.
elif num < -1 or num > 5:
continue
Finally, if input is not -1, and the input is a number between 0-5 inclusive, add it to the array and await the next input.
else:
inputs.append(num)
Finally at the end of the return after -1 was received, it is possible the first number entered was -1, or all values entered were invalid. Both of these scenarios would result in division by 0, and an error being thrown. So you would want to set the minimum number that can be set as the divisor to 1 to ensure you don't crash trying to calculate your answer:
print(sum(inputs) / max(len(inputs), 1))
And now putting it all together:
num = 0
inputs = []
while True:
input_value = input("Please enter a number between -1 and 5: ")
try:
num = int(input_value)
except ValueError:
continue
if num == -1:
break
elif num < -1 or num > 5:
continue
else:
inputs.append(num)
return sum(inputs) / max(len(inputs), 1)
Maybe this is the code you are looking for just changing if num > -1 to if num == -1 to agree with the question you posted:
num = 0
inputs = []
while True:
num = int(input("Please enter a number between -1 and 5: "))
if num == -1:
break
else:
inputs.append(num)
print(sum(inputs) / len(inputs))
and it works just fine having as a result:
Please enter a number between -1 and 5: 5
Please enter a number between -1 and 5: 4
Please enter a number between -1 and 5: 3
Please enter a number between -1 and 5: 2
Please enter a number between -1 and 5: 1
Please enter a number between -1 and 5: -1
3.0

Syntax issue with my for loop and while loop keeps repeating infinitely (python)

I was working on a for loop and while loop for 2 separate programs asking for the same thing. My for loop is giving me syntax issues and won't come out as expected…
Expectations: A python program that takes a positive integer as input, adds up all of the integers from zero to the inputted number, and then prints the sum. If your user enters a negative number, it shows them a message reminding them to input only a positive number.
reality:
i1 = int(input("Please input a positive integer: "))
if i1 >= 0:
value = 0 # a default, starting value
for step in range(0, i1): # step just being the number we're currently at
value1 = value + step
print(value1)
else:
print(i1, "is negative")
And my While loop is printing "insert a number" infinitly…
Here is what my while loop looks like:
while True:
try:
print("Insert a number :")
n=int(input())
if(n<0):
print("Only positive numbers allowed")
else:
print ((n*(n+1))//2)
except ValueError:
print("Please insert an integer")
`Same expections as my for loop but as a while loop
Anyone know anyway I could fix this issue?
You have some indentation issues. This way works:
while True:
try:
print("Insert a number: ")
user_input = input()
if user_input == 'q':
exit()
n = int(user_input)
if n <= 0:
print("Only positive numbers allowed")
else:
print(n * (n+1) // 2)
except ValueError:
print("Please enter an integer")
Output sample:
Enter a number:
>>> 10
55
Enter a number:
>>> 1
1
Enter a number:
>>> -1
Only positive numbers allowed
Enter a number:
>>> asd
Please enter an integer
Enter a number:
See more about indentation in the docs.

How to break out of continue statement after certain amount of tries?

Apologies if the question to this is worded a bit poorly, but I can't seem to find help on this exercise anywhere. I am writing a basic Python script which sums two numbers together, but if both numbers inputted are the same the sum will not be calculated.
while True:
print('Please enter a number ')
num1 = input()
print('Please enter a second number ')
num2 = input()
if num1 == num2:
print('Bingo equal numbers!')
continue
elif num1 == num2:
print('It was fun calculating for you!')
break
print('The sum of both numbers is = ' + str(int(num1) + int(num2)))
break
If both numbers are equal I want the script to loop back once more and if the numbers inputted are equal again I want the program to end. With the code I have provided the issue I am having is that when I enter two equal numbers it keeps constantly looping until I enter two different numbers.
You would likely want to have a variable keeping track of the number of times that the numbers were matching. Then do something if that counter (keeping track of the matching) is over a certain threshold. Try something like
matches = 0
while True:
num1 = input('Please enter a number: ')
num2 = input('Please enter a second number: ')
if num1 == num2 and matches < 1:
matches += 1
print('Bingo equal numbers!')
continue
elif num1 == num2:
print('It was fun calculating for you!')
break
print('The sum of both numbers is = ' + str(int(num1) + int(num2)))
break
You can add give input code again inside first if statement or use some other dummy variable for loop so that you can break the loop, for e.g. use while j == 0 and increase it j += 1when you are inside the first if statement
continue skips the execution of everything else in the loop. I don't see it much useful in your example. If you want to print the sum then just remove it.
How continue works can be demonstrated by this sample (taken from python docs)
for num in range(2, 10):
if num % 2 == 0:
print("Found an even number", num)
continue
print("Found a number", num)
Result
Found an even number 2
Found a number 3
Found an even number 4
Found a number 5
Found an even number 6
Found a number 7
Found an even number 8
Found a number 9

If-Else Statement-Positive and Negative Integers

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')

Continually prompting user for input in Python

Objective: * Write a python program that repeatedly prompts for input of a positive number until the sum of the numbers is greater than 179. Use at least three modules/functions in your solution.
* The largest number entered cannot exceed 42.
* When the sum of the numbers exceeds 179, print the sum of the numbers, the largest number entered and smallest number entered.
I just need some guidance, specifically for the "input_numbers" module. There must be an easier way to do this than to make a variable for each number. The code is not complete. I haven't even started on the two other modules yet. Thanks in advance.
def input_numbers():
while True:
num1 = raw_input("Enter a positive integer no greater than 42 ")
if num1 <= 0:
print "That is not a positive integer. Try again "
elif num1 > 42:
print "The number cannot exceed 42. Try again "
num2 = raw_input("Enter another positive integer ")
if num2 <= 0:
print "That is not a positive integer. Try again "
elif num2 > 42:
print "The number cannot exceed 42. Try again "
num3 = raw_input("Enter another positive integer ")
if num3 <= 0:
print "That is not a positive integer. Try again "
elif num3 > 42:
print "The number cannot exceed 42. Try again "
num4 = raw_input("Enter another positive integer ")
if num4 <= 0:
print "That is not a positive integer. Try again "
elif num4 > 42:
print "The number cannot exceed 42. Try again "
num5 = raw_input("Enter another positive integer ")
if num5 <= 0:
print "That is not a positive integer. Try again "
elif num5 > 42:
print "The number cannot exceed 42. Try again "
elif sum(num1, num2, num3, num4, num5) > 179:
print_numbers()
add_numbers()
def add_numbers():
print_numbers()
def print_numbers():
input_numbers()
You can knock out all three function requirements by encapsulating each step of your program. Rather than having your loop inside of a function, we'll let main control the loop, and we'll control the flow by passing data into and out of function calls.
Let's rework your input_numbers() function a bit.
def get_input_number():
num = int(raw_input("Enter a positive integer no greater than 42 "))
if num <= 0 or num > 42:
print "Invalid input. Try again "
get_input_number()
else:
return num
So, instead of having input_numbers control the loop as well as the input handling and validation, we have it do just what its name implies: It asks for input, validates it, and then, if it's good, it returns the value to the caller, but if it's bad, it writes a message, and calls itself again to the user can enter good input.
The next function we'll set up is straight from your list of requirements. From all of the numbers that the user enters, we need to find the biggest one. From the language alone, we can determine that we're looking through a set of numbers, and thus, this is a good place to break out a list. Assuming we store all of the users input in a list, we can then pass that list to a function and perform operations on it, like so.
def get_greatest_number(input_list):
highest = input_list[0]
for i in input_list:
if i > highest:
highest = i
return highest
We set the first element of the list to a variable highest and then check all other elements in the list against that initial value. If we find one that's bigger, we then reassign the highest variable to the element that was bigger. Once we do this for each element in the list, the number inside of highest will now be, just that, the highest number, and so, we'll return it to the main program.
Similarly, we can do the same for finding the smallest.
def get_smallest_number(input_list):
smallest = input_list[0]
for i in input_list:
if i < smallest:
smallest = i
return smallest
Finally, we get to our main loop. Here we declare an empty list, number_list to store all the numbers in. And we use the sum of that as our loop condition.
if __name__ == '__main__':
number_list = []
while sum(number_list) < 179:
number_list.append(get_input_number())
In the body of the loop, we call our get_input_number() and append its result to the list we made. Once the sum of the numbers in the list exceed 179, the while loop will exit and we can finally show the user the results.
print
print '-------------------------'
print 'total of numbers entered: %d' % sum(number_list)
print 'greatest number entered: %d' % get_greatest_number(number_list)
print 'smallest number entered: %d' % get_smallest_number(number_list)
Here we can the get_greatest_number and get_smallest_number we made, and we give them the list of numbers as an argument. They'll loop though the lists, and then return the appropriate values to the print statements.
Yes, of course there's a better way than making a variable for each number. Store them in a list. Storing them in a list also makes finding their sum and the highest and lowest value easy (there are built-in functions for this).
As a further hint, you'll want to use two loops, one inside the other. The outer loop keeps the user entering numbers until their sum exceeds 179. The inner loop keeps the user entering a single number until it's between 1 and 42 inclusive.
def get_int(prompt=''):
while True:
try:
return int(raw_input(prompt))
except ValueError:
pass
def get_values():
values = []
total = 0
while total <= 179:
val = get_int('Enter a positive integer <= 42: ')
if 0 <= val <= 42:
values.append(val)
total += val
return values
def print_info(values):
print 'Sum is {}'.format(sum(values))
print 'Largest value is {}'.format(max(values))
print 'Smallest value is {}'.format(min(values))
def main():
values = get_values()
print_info(values)
if __name__=="__main__":
main()
You can repeatedly poll the number in a loop, and add the inputs into a list, e.g.
def input_numbers():
user_inputs = [] # a list of all user's inputs
while True:
num = raw_input("Enter a positive integer no greater than 42 ")
try:
num = int(num) # convert input string to integer
if num <= 0:
print "That is not a positive integer. Try again "
elif num > 42:
print "The number cannot exceed 42. Try again "
user_inputs.append(num)
except ValueError: # conversion to integer may fail (e.g. int('string') ?)
print 'Not a Number:', num
if some_condition_regarding(user_inputs):
break # eventually break out of infinite while loop
here some well-known tricks:
def min_and_max(your_num_list)
min=your_num_list[0]
max=your_num_list[0]
for num in your_num_list:
if num < min:
min=num
if max > num
max=num
return min,max
When you're writing a standalone Python program, it’s a good practice to use a main function. it allows you to easily add some unit tests, use your functions or classes from other modules (if you import them), etc.
And as others already said, it is a good idea to create a list and append a new element to it each time the user enters a valid number (until the sum of the numbers axceeds 179). If user entered an incorrect value, then just don’t append anything to the list and skip to the next iteration (so the user will be asked to enter a number again).
So basically it could look like this:
def validate_entered_number(num):
"""
Checks if the number is positive and is less or equal to 42.
Returns True if the number matches these conditions,
otherwise it returns False.
"""
if num < 0:
print "That is not a positive integer."
return False
if num > 42:
print "The number cannot exceed 42."
return False
return True
def main():
entered_numbers = []
while True:
try:
num = int(raw_input("Enter a positive integer less or equal to 42: "))
except ValueError:
print "You should enter a number"
continue
if validate_entered_number(num):
entered_numbers.append(num)
if sum(entered_numbers) > 179:
print "The sum of the numbers is %s" % sum(entered_numbers)
print "The smallest number entered is %s" % min(entered_numbers)
print "The largest number entered is %s" % max(entered_numbers)
return
if __name__ == "__main__":
main()
In fact, I can imagine a situation where you would want to just store the sum of the numbers, the smallest number and the largest number in three variables and update these variables in each iteration (add current number to the sum and compare it to the currently known smallest and larger numbers and update the corresponding variables when necessary), but in this case the longest list you can possibly have is only 180 elements (if all numbers are 1 and the user doesn’t enter 0 or you have modified the program to deny entering 0), which is very small amount of elements for a list in Python. But if you had to deal with really big amounts of numbers, I’d recommend to switch to a solution like this.
Thanks to everyone who answered. I've written the following code and it works nearly perfectly except the last module. If you exit the program after the first run (by pressing 0) it will exit, but if you run it a second time pressing 0 won't make it exit. It'll just go back to the beginning of the program. I don't know why.
Note: The assignment has various requirements that I had to incorporate in my code. Hence the unnecessary modules, global variables, and comments.
maxNum = 42 # declares global variable maxNum
target = 179 # declares global variable target
def user_input(): # prompts user to input a number 42 or less until all add up to 179
x = 0
nums = []
while sum(nums) <= target:
nums.append(int(raw_input("Enter a number: ")))
if int(nums[x]) > int(maxNum):
print "Number cannot exceed 42."
user_input()
else:
x += 1
print_nums(nums,x)
def print_nums(nums,x): # prints the sum of the numbers, the smallest, and the largest
print "Sum of all numbers is", sum(nums)
nums.sort()
x -= 1
print "Largest number entered is", nums[x]
print "Smallest number entered is", nums[0]
decide()
def decide(): # allows user to continue the program or exit
exit = raw_input("<9 to enter a new set of number. 0 to exit.> ")
while True:
if int(exit) == 0:
return
elif int(exit) == 9:
user_input()
user_input()

Categories

Resources