I'm currently trying to use simple while loops to count down from a given positive number to zero and then stop. If the number isn't a positive number then it should loop and ask again. I've gotten most of it down, but I can't make it count down to zero. Right now it just stops at 1.
For this problem, zero is not counted as a positive number. If zero is entered, it should loop back to the initial prompt.
This is the code I have so far:
# set loop variable
looking_for_positive_number = True
# get positive number
while (looking_for_positive_number == True):
reply = input("Enter positive number: ")
int_reply = int(reply)
# count down from given positive number to 0, loop back to reply if not
while int_reply > 0:
print(int_reply)
int_reply = int_reply - 1
looking_for_positive_number = False
This is what it returns (I used 5 as the positive number):
Enter positive number: 5
5
4
3
2
1
Ideally, it should return something like this (also used 5 here):
Enter positive number: 5
5
4
3
2
1
0
I don't know what I'm missing/what I'm doing wrong. Any help would be appreciated. Thanks in advance!
EDIT: I figured it out, I just had to include an if statement in the nested while loop. Final code looks like this:
# set loop variable
looking_for_positive_number = True
# get positive number
while (looking_for_positive_number == True):
reply = input("Enter positive number: ")
int_reply = int(reply)
# count down from given positive number to 0, loop back to reply if not
# ZERO DOES NOT COUNT AS POSITIVE NUMBER -- SHOULD LOOP BACK IF 0 IS ENTERED
while int_reply > 0:
print(int_reply)
int_reply = int_reply - 1
# want to print 0 after we get down to 1 (but not include 0 in our initial loop)
if int_reply == 0:
print(0)
# finish and exit loop
looking_for_positive_number = False
# get positive number
while (looking_for_positive_number == True):
reply = input("Enter positive number: ")
int_reply = int(reply)
if int_reply <= 0:
print( "Not a positive number." )
continue
# count down from given positive number to 0, loop back to reply if not
while int_reply > 0:
print(int_reply)
int_reply = int_reply - 1
looking_for_positive_number = False
The Python range function could simplify your logic (slightly). Using a negative step value it will count down instead of counting up.
Example:
while True:
number = int(input("Enter a postive integer value: "))
if number <= 0:
print("Not a positive number.")
continue
for i in range(number, -1, -1):
print(i)
break
Output:
Enter a postive number: 5
5
4
3
2
1
0
Related
experts.
I'm trying to define a function (collatz) that:
Asks for a number. If it is even it prints number // 2, if it odd it prints 3 * number + 1. (OK)
The result, whatever it is, must enter a loop until the result is 1. (NOK)
So, i´m not figure out because the result is not used and is in an infinite loop. Any suggestion?
def collatz():
number = int(input('Enter the number: '))
x = number % 2
while number != 1:
if x == 0:
print(f'{number // 2}')
else:
print(f'{3 * number + 1}')
number = number
print(f'{collatz()}')
You need to actually assign the result back to number.
As well:
The divisibility check needs to be in the loop.
The outer print() is not needed.
The f-strings are redundant. print() converts its arguments to string automatically.
def collatz():
number = int(input('Enter the number: '))
while number != 1:
if number % 2 == 0:
number //= 2 # Short for "number = number // 2"
else:
number = 3*number + 1
print(number)
collatz()
Example run:
Enter the number: 3
10
5
16
8
4
2
1
i have to write a hailstone program in python
you pick a number, if it's even then half it, and if it's odd then multiply it by 3 and add 1 to it. it says to continue this pattern until the number becomes 1.
the program will need methods for the following:
accepting user input
when printing the sequence, the program should loop until the number 1.
print a count for the number of times the loop had to run to make the sequence.
here's a sample run:
prompt (input)
Enter a positive integer (1-1000). To quit, enter -1: 20
20 10 5 16 8 4 2 1
The loop executed 8 times.
Enter a positive integer (1-1000). To quit, enter -1: 30
30 15 46 23 70 35 106 53 160 80 40 20 10 5 16 8 4 2 1
The loop executed 19 times.
Enter a positive integer (1-1000). To quit, enter -1: -1
Thank you for playing Hailstone.
right now i have this:
count = 0
def hailstone(n):
if n > 0
print(n)
if n > 1:
if n % 2 == 0:
hailstone(n / 2)
else:
hailstone((n * 3) + 1)
count = count + 1
i don't know what to do after this
Try to think in a modular way, make two functions: check_number() and user_call(). Check_number will verify if the current number in the loop is odd or even and the user_call() just wraps it to count how many times the loop did iterate.
I found the exercise in a great book called Automate Boring Stuff with Python, you have to check it out, if you don't know it already.
Here's my code. Try to use what serves you the best.
from sys import exit
def check_number(number):
if number % 2 ==0:
print(number // 2)
return(number // 2)
else:
print(number*3+1)
return number*3+1
def user_call(number):
count = 0
while number != 1:
count += 1
number = check_number(number)
return count
if __name__ == "__main__":
try:
number = int(input('Give a number \n'))
count = user_call(number)
print('count ',count)
except Exception as e:
exit()
you can use global
visit https://www.programiz.com/python-programming/global-keyword to learn more
import sys
res = []
def hailstone(number):
global res
if number > 1:
if number % 2 == 0:
res.append( number // 2 )
hailstone(res[len(res)-1])
else:
res.append(number * 3 + 1)
hailstone(res[len(res)-1])
return res
number = int(input('Enter a positive integer. To quit, enter -1: '))
if number <= 0 or number == 0:
print('Thank you for playing Hailstone.')
sys.exit()
else:
answers = hailstone(number)
for answer in answers:
print(answer)
print('The loop executed {} times.'.format(len(answers) + 1))
I used recursion to solve the problem.
Heres my code:
Edit: All criteria met
count = 0
list_num = []
def input_check():
number = int(input("Enter a positive integer (1-1000). To quit, enter -1: "))
if number >= 1 and number <= 1000:
hailstone_game(number)
elif number == -1:
return
else:
print("Please type in a number between 1-1000")
input_check()
def hailstone_game(number):
global count
while number != 1:
count += 1
list_num.append(number)
if number % 2 == 0:
return hailstone_game(int(number/2))
else:
return hailstone_game(int(number*3+1))
list_num.append(1) # cheap uncreative way to add the one
print(*list_num, sep=" ")
print(f"The loop executed {count} times.")
return
input_check()
Additional stuff that could be done:
- Catching non-integer inputs using try / except
Keep in mind when programming it is a good habit to keep different functions of your code separate, by defining functions for each set of 'commands'. This leads to more readable and easier to maintain code. Of course in this situation it doesn't matter as the code is short.
Your recursive function is missing a base/terminating condition so it goes into an infinite loop.
resultArray = [] #list
def hailstone(n):
if n <= 0: # Base Condition
return
if n > 0:
resultArray.append(n)
if n > 1:
if n % 2 == 0:
hailstone(int(n/2))
else:
hailstone((n * 3) + 1)
# function call
hailstone(20)
print(len(resultArray), resultArray)
Output
8 [20, 10, 5, 16, 8, 4, 2, 1]
Here's a recursive approach for the problem.
count=0
def hailstone(n):
global count
count+=1
if n==1:
print(n)
else:
if n%2==0:
print(n)
hailstone(int(n/2))
else:
print(n)
hailstone(3*n+1)
hailstone(21)
print(f"Loop executed {count} times")
What this is supposed to do is:
To ask the user for numbers using while loop until they enter 0
when 0 is pressed we need to print the average of the numbers entered so far.
(Kindly help)
import statistics as st
provided_numbers = []
while True:
number = int(input('Write a number'))
if number == 0:
break
else:
provided_numbers.append(number)
print(f'Typed numbers: {provided_numbers}')
print(f'The average of the provided numbers is {st.mean(provided_numbers)}')
Take each number and print the average so far and stop it when input is zero, right?
s = 0
count = 0
while True:
num = int(input('Write a number: '))
if num == 0:
break
s += num
count += 1
print("Average so far:",(s/count))
Could you add a piece of code you have tried or sample input and output too?
A program that reads a sequence of numbers
and counts how many numbers are even and how many are odd. When numbers of even output maybe 4, then the list is show even numbers and odd number. i got error in my code, this is my code:
odd_numbers = 0
even_numbers = 0
lst_odd =[]
lst_even =[]
# read the first number
number = int(input("Enter a number or type 0 to stop: "))
# 0 terminates execution
while number != 0:
# check if the number is odd
if number % 2 == 1:
# increase the odd_numbers counter
odd_numbers += 1
return lst_odd
else:
# increase the even_numbers counter
even_numbers += 1
return lst_even
# read the next number
number = int(input("Enter a number or type 0 to stop: "))
# print results
print("Odd numbers count:", odd_numbers, '\n','list odd numbers is', lst_odd)
print("Even numbers count:", even_numbers, '\n','list odd numbers is',lst_even)
i want to make the out like that:
Enter a number or type 0 to stop: 3
Enter a number or type 0 to stop: 3
Enter a number or type 0 to stop: 4
Enter a number or type 0 to stop: 5
Enter a number or type 0 to stop: 6
Enter a number or type 0 to stop: 7
Enter a number or type 0 to stop: 8
Enter a number or type 0 to stop: 2
Enter a number or type 0 to stop: 4
Enter a number or type 0 to stop: 0
Odd numbers count: 4
list odd number is [3,3,5,7]
Even numbers count: 5
list even number is [4,6,8,2,4]
When using return, you need code within a function. To add to a list, you append to it
For example
def main():
lst_odd = []
lst_even = []
while True:
number = input('Enter a number or "stop": ')
if number.lower() == 'stop':
return lst_odd, lst_even # end the loop, return both lists
n = int(number)
if n % 2 == 1:
lst_odd.append(n)
else:
lst_even.append(n)
odds, evens = main()
print('Odd numbers count: {}\nList odd numbers is {}'.format(len(odds), odds))
print('Even numbers count: {}\nList even numbers is {}'.format(len(evens), evens))
My task is to:
"Write a program that will keep asking the user for some numbers.
If the user hits enter/return without typing anything, the program stops and prints the average of all the numbers that were given. The average should be given to 2 decimal places.
If at any point a 0 is entered, that should not be included in the calculation of the average"
I've been trying for a while, but I can't figure out how to make the programs act on anything I instruct when the user hits 'enter' or for it to ignore the 0.
This is my current code:
count = 0
sum = 0
number = 1
while number >= 0:
number = int(input())
if number == '\n':
print ('hey')
break
if number > 0:
sum = sum + number
count= count + 1
elif number == 0:
count= count + 1
number += 1
avg = str((sum/count))
print('Average is {:.2f}'.format(avg))
You're very close! Almost all of it is perfect!
Here is some more pythonic code, that works.
I've put comments explaining changes:
count = 0
sum = 0
# no longer need to say number = 1
while True: # no need to check for input number >= 0 here
number = input()
if number = '': # user just hit enter key, input left blank
print('hey')
break
if number != 0:
sum += int(number) # same as sum = sum + number
count += 1 # same as count = count + 1
# if number is 0, we don't do anything!
print(f'Average is {count/sum:.2f}') # same as '... {:.2f} ...'.format(count/sum)
Why your code didn't work:
When a user just presses enter instead of typing a number, the input() function doesn't return '\n', rather it returns ''.
I really hope this helps you learn!
Try this:
amount = 0 # Number of non-zero numbers input
nums = 0 # Sum of numbers input
while True:
number = input()
if not number: # Breaks out if nothing is entered
break
if int(number) != 0: # Only add to the variables if the number input is not 0
nums+=int(number)
amount += 1
print(round(nums/amount,2)) # Print out the average rounded to 2 digits
Input:
1
2
3
4
Output:
2.5
Or you can use numpy:
import numpy as np
n = []
while True:
number = input()
if not number: # Breaks out if nothing is entered
break
if int(number) != 0: # Only add to the variables if the number input is not 0
n.append(int(number))
print(round(np.average(n),2)) # Print out the average rounded to 2 digits
A list can store information of the values, number of values and the order of the values.
Try this:
numbers = []
while True:
num = input('Enter number:')
if num == '':
print('Average is', round(sum(numbers)/len(numbers), 2)) # print
numbers = [] # reset
if num != '0' and num != '': numbers.append(int(num)) # add to list
Benefit of this code, it does not break out and runs continuously.