This question already has answers here:
How to print every nth index of a python list on a new line?
(4 answers)
Closed 1 year ago.
I'm having trouble with my code, and I can't figure it out. My code is supposed to print 0 to input number subtracted by 1. Here's my code:
num = int(input(''))
if num > 50:
print('Number must be below 50')
else:
for num in range(0, num):
if num >= 0:
print(num, end=" ")
The output must next line every 10 numbers, but my output only displays one line.
Input:
15
Output:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
Output must be
Input:
15
Output:
0•1•2•3•4•5•6•7•8•9
10•11•12•13•14
num = int(input(''))
if num > 50:
print('Number must be below 50')
else:
for i in range(0, num):
print(i, end=" ")
if i % 10 == 9:
print()
For clarity, don't reuse the variable name num inside and outside the loop. You can easily introduce bugs that way.
You are not printing a new line after printing every 10 numbers. As you are starting from 0, you have to print a new line whenever you get a multiple of 9. The code should look like this:
num = int(input(''))
if num > 50:
print('Number must be below 50')
else:
for i in range(0, num):
if i >= 0:
print(i, end=" ")
if i % 9 == 0:
print("")
Related
I have a piece of code here where I am creating a logic to be displaying all of the numbers from 2, to my int(input) to be converted to a list and then only display the prime numbers from 2 to my input.
Here is my code:
def display_prime_numbers(maximum):
lst = []
if maximum <= 2:
print('Enter Number Greater Than 2')
maximum = maximum + 1
rng = range(2,maximum)
for index in rng:
print(index, end=' ')
for i in rng:
if (index % i) == 0:
return False
else:
print(f'{index} is a prime number')
This is my output:
Enter Positive Integer Greater Than 2:10
2 3 4 5 6 7 8 9 10
Summary: I'm unable to display my range count loop as a list and am trying to only display my prime number pieces.
i.e. expected:
[2,3,4,5,6,7,8,9,10]
3 is a prime number
5 is a prime number
7 is a prime number
To clarify my comment, your return false statement will end the function. The first time the mod of the index is == 0, then the function will end and the rest of the list will not be evaluated for being prime.
def display_prime_numbers(maximum):
lst = []
if maximum <= 2:
print('Enter Number Greater Than 2')
maximum = maximum + 1
rng = range(2,maximum)
for index in rng:
print(index, end=' ')
for i in rng:
if (index % i) != 0: #Just print here!
print(f'{index} is a prime number')
display_prime_numbers(10)
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")
This question already has answers here:
How to print X items in a list per line
(3 answers)
Closed 2 years ago.
i am really beginner and just starting programming with python since 2 weeks.
here is my question i cant find anywhere or i cant figure out the solution.
i want to see my result in terminal with multiple line , for example i want to calculate long for loop and the result show up this loop on terminal with very long a single line.
is there any solution for this?
and sorry for my bad english isnt my native language.
Code:
list = list(range(1,100))
for x in list:
if x % 3 == 0 or x % 5 == 0:
print(x, end=' ')
Output:
3 5 6 9 10 12 15 18 20 21 24 25 etc...
But i want this one:
3 5 6 9 10
12 15 18 20 21
You could add an if statement before you print, to determine whether you want to have end be a blank or a newline character.
x_list = range(1,100)
n = 0
for x in x_list:
if x % 3 == 0 or x % 5 == 0:
if n == 4:
print(x, end='\n')
n = 0
else:
print(x, end=' ')
n = n + 1
You can change your print statement to:
print(x)
If you would print some results in the same line, you can do a logic to print some characters inline and after some iteration print in next line.
list1 = list(range(1,100))
for num, x in enumerate(list1):
if x % 3 == 0 or x % 5 == 0:
print(x, end=' ')
if num % 10 == 0:
print()
I'm doing this assignment:
Write a program that prints all even numbers less than the input
number using the while loop.
The input format:
The maximum number N that varies from 1 to 200.
The output format:
All even numbers less than N in ascending order. Each number must be
on a separate line.
N = int(input())
i = 0
while 200 >= N >= 1:
i += 1
if i % 2 == 0 and N > i:
print(i)
and its output like:
10 # this is my input
2
4
6
8
but there is an error about time exceed.
The simple code would be:
import math
N = int(input(""))
print("1. " + str(N))
num = 1
while num < math.ceil(N/2):
print (str(num) + ". " + str(num * 2))
num += 1
The problem is that the while loop never stops
while 200 >= N >= 1 In this case because you never change the value of N the condition will always be true. Maybe you can do something more like this:
N = int(input())
if N > 0 and N <= 200:
i = 0
while i < N:
i += 2
print(i)
else
print("The input can only be a number from 1 to 200")
This question already has answers here:
Sum the digits of a number
(11 answers)
Closed 2 years ago.
I am trying to find the magic number in this program but I got stuck on this part and am not sure where to go next. I have searched up many ways on the internet but they are all using more complex code that I have not learned yet.
Example
input 45637
4+5+6+3+7 = 25
2+5 = 7
7 = magic number
num = int(input("Enter a positive number : "))
ans = 0
while num > 0 or ans > 9:
digit = num % 10
num = num//10
print(digit)
Using statements and operators you have already learned as demonstrated in your code, you can use a nested while loop to aggregate the digits from the division remainders into a total as the number for the next iteration of the outer while loop:
num = 45637
while num > 9:
total = 0
while num > 0:
digit = num % 10
num = num // 10
total = total + digit
num = total
print(num)
This outputs:
7
One way:
while len(str(ans))>1:
ans = sum(map(int, str(ans)))
Full code:
num = int(input("Enter a positive number : "))
ans = num
while len(str(ans))>1:
ans = sum(map(int, str(ans)))
print(ans)
Output for input 45637:
7