This question already has answers here:
Are infinite for loops possible in Python? [duplicate]
(16 answers)
Closed 2 years ago.
I am working through some exercises on python and my task is to create a program that can take a number, divide it by 2 if it is an even number. Or it will take the number, multiply it by 3, then add 1. It should ask for an input and afterwards it should wait for another input.
My code looks like this, mind you I am new to all this.
print('Please enter a number:')
def numberCheck(c):
if c % 2 == 0:
print(c // 2)
elif c % 2 == 1:
print(3 * c + 1)
c = int(input())
numberCheck(c)
I want it to print "Please enter a number" only once. but after running I want it to wait for another number. How would I do this?
I tried a for loop but that uses a range and I don't want to set a range unless there is a way to do it to infinity.
If you want to run an infinite loop, that can be done with a while loop.
print('Please enter a number:')
def numberCheck(c):
if c % 2 == 0:
print(c // 2)
elif c % 2 == 1:
print(3 * c + 1)
while True:
c = int(input())
numberCheck(c)
So my understanding is you want the function to run indefinitely. this is my approach, through the use of a while loop
print("Enter a number")
while True:
c = int(input(""))
numberCheck(c)
You could use a while loop with True:
while True:
c = int(input())
numberCheck(c)
Related
So after finishing the code, I would like to have an option where the user would like to try again by typing Y/n or N/n. How do I make it?
a=int(input('enter value of n: '))
i = 1
sum=0
while a < 1 or a > 300:
print(a, 'is not in the range 1-300')
exit()
for a in range(1,a+1):
print (a, end = ' ')
while i<=a:
if i%3==0 or i%5==0:
sum=sum+i
i=i+1
print('\nsum of all multiples of 3 and 5 is:',sum)
repeat=str(input('Would you like to try again? Y/N?'))
Here's a simple way to do it (keeping your code structure) without any functions or jargon (for beginners :]):
from sys import exit # Just something to exit your code
repeat = 'y' # So it starts the first time
while repeat.lower() == 'y': # repeat.lower() -> convert the string 'repeat' to lowercase, incase user inputs 'Y'. you could also use the or keyword here though
n = int(input("Enter value of n:\n>>> "))
if n < 1 or n > 300:
print("'n' must be between 1 - 300, not " + n) # You could use f-strings, check them out!
exit()
sum_of_multiples = 0
# I'm combining your for and while loop as shown below
for i in range(1, n + 1): # Don't name your 'i' and 'n' variables the same -> you did so with 'a'
print(i, end=', ') # There are cleaner ways to do this but I'm assuming this is what you want
if i % 3 == 0 or i % 5 == 0:
sum_of_multiples += i
# Printing output
print(f"\nSum of all multiples of 3 and 5 is: {sum_of_multiples}") # This is called an f-string
repeat = input("\nDo you want to go again?\n>>> ") # If you don't input Y/y, the outer while loop will break and terminate
print("Thank you for running me!") # Prints after the program finishes running
Note that you don't need the exit() when checking if n is within 1 - 300, you could also just use break.
EDIT (WITH BREAK)
Program without from sys import exit below:
repeat = 'y' # So it starts the first time
while repeat.lower() == 'y': # repeat.lower() -> convert the string 'repeat' to lowercase, incase user inputs 'Y'. you could also use the or keyword here though
n = int(input("Enter value of n:\n>>> "))
if n < 1 or n > 300:
print("'n' must be between 1 - 300, not " + n) # You could use f-strings, check them out!
break # This will mean that "Thank you for running me!" gets printed even if your input is wrong
sum_of_multiples = 0
# I'm combining your for and while loop as shown below
for i in range(1, n + 1): # Don't name your 'i' and 'n' variables the same -> you did so with 'a'
print(i, end=', ') # There are cleaner ways to do this but I'm assuming this is what you want
if i % 3 == 0 or i % 5 == 0:
sum_of_multiples += i
# Printing output
print(f"\nSum of all multiples of 3 and 5 is: {sum_of_multiples}") # This is called an f-string
repeat = input("\nDo you want to go again?\n>>> ") # If you don't input Y/y, the outer while loop will break and terminate
print("Thank you for running me!") # Prints after the program finishes running
Hope this helped!
I'd like to create a function that add 2 to an integer as much as we want. It would look like that:
>>> n = 3
>>> add_two(n)
Would you like to add a two to n ? Yes
The new n is 5
Would you like to add a two to n ? Yes
the new n is 7
Would you like to add a two to n ? No
Can anyone help me please ? I don't how I can print the sentence without recalling the function.
The idea is to use a while loop within your function that continues to add two each time you tell it to. Otherwise, it exits.
Given that knowledge, I'd suggest trying it yourself first but I'll provide a solution below that you can compare yours against.
That solution could be as simple as:
while input("Would you like to add a two to n ?") == "Yes":
n += 2
print(f"the new n is {n}")
But, since I rarely miss an opportunity to improve on code, I'll provide a more sophisticated solution as well, with the following differences:
It prints the starting number before anything else;
It allows an arbitrary number to be added, defaulting to two if none provided;
The output text is slightly more human-friendly;
It requires a yes or no answer (actually anything starting with upper or lower-case y or n will do, everything else is ignored and the question is re-asked).
def add_two(number, delta = 2):
print(f"The initial number is {number}")
# Loop forever, relying on break to finish adding.
while True:
# Ensure responses are yes or no only (first letter, any case).
response = ""
while response not in ["y", "n"]:
response = input(f"Would you like to add {delta} to the number? ")[:1].lower()
# Finish up if 'no' selected.
if response == "n":
break
# Otherwise, add value, print it, and continue.
number += delta
print(f"The new number is {number}")
# Incredibly basic/deficient test harness :-)
add_two(2)
You can use looping in your add_two() function. So, your function can print the sentence without recalling the function.
The above answer describes in detail what to do and why, if you're looking for very simple beginner-type code that covers your requirements, try this:
n = 3
while True:
inp = input("Would you like to add 2 to n? Enter 'yes'/'no'. To exit, type 'end' ")
if inp == "yes":
n = n + 2
elif inp == "no":
None
elif inp == "end": # if the user wants to exit the loop
break
else:
print("Error in input") # simple input error handling
print("The new n is: ", n)
You can wrap it in a function. The function breaks once the yes condition is not met
def addd(n):
while n:
inp = input('would like to add 2 to n:' )
if inp.lower() == 'yes':
n = n + 2
print(f'The new n is {n}')
else:
return
addd(10)
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
At line 13, in < module > a = int(input()) EOF error: End of file error when reading a line.
Line 13 is a = int(input()) for the statement elif n == 3:
Write a program that performs the tasks of a simple calculator. The program should first take an integer as input and then based on that integer perform the task as given below.
If the input is 1, 2 integers are taken from the user and their sum is printed.
If the input is 2, 2 integers are taken from the user and their difference(1st number - 2nd number) is printed.
If the input is 3, 2 integers are taken from the user and their product is printed.
If the input is 4, 2 integers are taken from the user and the quotient obtained (on dividing 1st number by 2nd number) is printed.
If the input is 5, 2 integers are taken from the user and their remainder(1st number mod 2nd number) is printed.
If the input is 6, the program exits.
For any other input, print "Invalid Operation".
n = int(input())
while n != 6:
if n == 1:
a = int(input())
b = int(input())
print(a + b)
elif n == 2:
a = int(input())
b = int(input())
print(a - b)
elif n == 3:
a = int(input())
b = int(input())
print(a * b)
elif n == 4:
a = int(input())
b = int(input())
print(a // b)
elif n == 5:
a = int(input())
b = int(input())
print(a % b)
else:
print("Invalid Operation")
The EOFError will occur if you call input() when you have already reached the end of your input. The problem is that your loop condition is always True (if you don't type 6 at the start) because n is assigned to some value outside the loop, and never changed. So it will always keep calling input(), and at some point this can fail if you have reached the end of your input (e.g. you press ctrl-D (Linux) or ctrl-Z (Windows) or it reaches the end of input file that is redirected into standard input).
You probably meant:
while True
n = int(input())
if n == 6:
break
# carry on with rest of code ...
although if you are using Python >= 3.8, you could use the "walrus operator" in order to avoid needing a while True loop that you have to break out of:
while (n := int(input()) != 6:
# carry on with rest of code ...
This question already has answers here:
Why is "None" printed after my function's output?
(7 answers)
Closed 3 years ago.
Learning from "Automate The Boring Stuff" by Al Sweigart. At the end of Chapter 3, the Collatz Sequence is given as practice. The output seems correct, but the last row has a 'None' in it. In the code below, I am guessing that when p = 1, it gets out of the while loop, and then there is nothing to print, so it gives a None (?). Can someone point me in the right direction of why the None is added, and how to fix it?
See code right below and example results further down:
def collatz (p):
while p != 1:
if p % 2 ==0:
p = (p//2)
print(p)
else:
p = ((3*p) + 1)
print(p)
print ('Select a number between 1 and 10')
entry = float(input())
number = round(entry)
if number >10 or number <1:
print('Your selection must between 1 and 10. Please try again')
else:
Program = collatz(number)
print (Program)
**
Example results:
If I input number as 3, I get:
3
10
5
16
8
4
2
1
None
As was already pointed out in the comments, your function returns None. I thought I'd take your function and make it a generator which you can iterate over and print the values that way. This has several advantages like making your code much more flexible and reusable:
def collatz (p):
while p != 1:
if p % 2 == 0:
p = p / 2 # You don't need the double slash here because of the if before it
else:
p = (3*p) + 1
yield p
print('Select a number between 1 and 10')
number = int(input()) # You really want int here I think and leave out the rounding
if 1 <= number <= 10: # Slightly more pythonic
for sequence_item in collatz(number):
print(sequence_item)
else:
print('Your selection must between 1 and 10. Please try again')
Feel free to ask anything or correct me on possibly wrong assumptions! :)
This question already has answers here:
Implementing the collatz function using Python
(8 answers)
Closed 5 years ago.
Note: I was trying to figure out why my while statement did not evaluate to False when the integer was, so I don't believe this is a duplicate
Doing an automating the boring stuff exercise in python where the program receives an input and reduces it to 1 using the following algorithm.
#even / 2
#odd * 3 + 1
def collatz():
print("Enter number:")
number = input()
try:
data = int(number) # Input Validation
while int(data) != 1:
if data % 2 == 0: #Number is even
data = int(data/2)
print(data)
if data % 2 == 1: # Number is odd
data = int(3*data+1)
print(data)
except:
print("Please input a valid value")
collatz()
collatz()
Instead of the while loop breaking, when the number is reduced to 1. The loop continues and it multiplies 1 by 3 and adds 1(Just as normal odd number). Btw many int conversions were done as I thought it may have returned a floating point.
So please tell me where are the unncessary int conversions and how to break it using a while statement. Any cleanup to code is appreciated
There are a few things that you should neaten up to make your code work properly and just generally better:
Rename data to n, this isn't going to make much of a difference, but I would say it just makes more sense.
There is no need to do endless conversions to int, n only needs to be converted from a string to an integer once.
Don't put your entire code in a function then call it once, instead have the main algorithm in a smaller function which you then can call from the main body of your code or even create another function to call the algorithm which handles the inputting side of things.
Use the integer division operator (//) instead of the floating point divider (/), since the number will be even, you can be sure that the decimal place will be 0.
You don't need to check if n % 2 is 0 and then on the next line check if it n % 2 is 1, you can just use an if ... else clause.
And that's about it! Here's what it looks like:
#even / 2
#odd * 3 + 1
def collatz(n):
while n != 1:
if n % 2 == 0: #Number is even
n = n // 2
else:
n = n * 3 + 1
print(n)
number = input("Enter number:")
try:
number = int(number)
collatz(number)
except ValueError:
print("Please input a valid value")
And a test shows it works (input of 24):
12
6
3
10
5
16
8
4
2
1