python - printing else statement rather then if and not repeating while statement - python

I'm writing a program that finds the multiple of a number between 1 and 10. The code currently skips over the if statement and immediately performs the else statement which is an error message even if an "accepted" value is entered. I also need it to repeat the multiples until it gets to 100 or above then it should stop. I tried changing around the ands and ors with no success and swapped the if and while statements around again to no success. The program looks like this:
check3 = False
num = int(input("Enter a number between 1 and 10: "))
if num <= 10 or num >= 1:
while not num <= 100:
num += num
print(num)
else:
print("Not in range. Try again.")

Like multiple people commented, there are a couple of problems.
I will walk you through them and then provide a commented working example.
Code walkthrough
check3 = False
num = int(input("Enter a number between 1 and 10: "))
# This condition can be rewritten without or/and to make it simpler to understand
# Check example below.
# (Also, if you were to write it like this,
# then the if would execute if either condition is true.
# Meaning it would execute if num is -50 because -50 <= 10.)
if num <= 10 or num >= 1:
# This while will run when NOT (number less than 100)
# So the while will only run when number is greater than 100
# You want the opposite of this actually
while not num <= 100:
# If you keep adding num to itself you will not get the multiples
# Example: num = 10
# round 1: num = 10+10 (num is now 20)
# round 2: num = 20+20 (num is now 40)
# etc
num += num
print(num)
# This else is indented at the same level as the while...
# So it will actually trigger when the condition is false.
else:
print("Not in range. Try again.")
So basically what's happening when you run your code is that since num is less than 100, the while will not run and execution will jump to the else.
Working example
num = int(input("Enter a number between 1 and 10: "))
if 1 <= num <= 10:
# it's better to set another variable because if you keep doing num+=num
# for num = 10 you will get num = 10+10 on the first loop (so num is 20 now)
# num = 20 + 20 on the second loop, etc...
multiples = 0
while not multiples >= 100:
multiples += num
print(multiples)
# the else needs to be indented at the same level as the if
else:
print("Not in range. Try again.")
End notes on boolean logic:
A OR B is true if either are true or if both are true.
A AND B is only true if both are true.

Related

Ask a user for 10 integers one at a time and store in list- python

score = int(input("Please enter a bowling score between 0 and 300: "))
while score >= 1 and score <= 300:
scores.append(score)
score = int(input("Please enter a bowling score between 0 and 300: "))
print(scores)
I want the user to enter 10 integers one at a time in a loop and store all ten in a list called scores.
You could do something like this, if you do not need the number entered to be restricted within an interval:
scores = []
for i in range(10):
scores.append(int(input())
This will repeatedly wait for a user input, and store each value in the scores list.
If you want the number to be between 1 and 300, simply place the code you already have in a for loop, or create a counter. You could end up with something like this:
scores = []
for i in range(10):
score = 0
while score >= 1 and score <= 300:
score = int(input("Please enter a bowling score between 0 and 300: "))
scores.append(score)
print(scores)
If you're okay assuming that all of the input will be valid, you can simply do:
scores = [int(input("Please enter a bowling score between 0 and 300: ")) for _ in range(10)]
This will raise a ValueError if the input isn't convertable to an int, though, and it also won't check for it being in the range. If you want to re-prompt them on invalid inputs until you have 10 valid inputs, you could make "get a valid score" its own function and then build the list with 10 calls to that:
def get_score() -> int:
while True:
try:
score = int(input("Please enter a bowling score between 0 and 300: "))
if not (0 <= score <= 300):
raise ValueError(f"{score} isn't between 0 and 300")
return score
except ValueError as e:
print(f"Error: {e}. Please try again.")
scores = [get_score() for _ in range(10)]
If you want for the user to input in different lines then this should work:
inputList = []
for i in range(10):
inputList.append(input("Enter: "))
But if you want the user to input all values in same line then use:
inputList = map(int, input("Enter: ").split())
Let's do a different approach than "try this" as it looks like you're a beginner.
To ask a user for an input you can use the input() function. It'll give you a string. To convert a string to a number you can utilize int(), float() or other functions depending on the properties the number should have (decimal numbers, precision, etc).
To repeat a certain action you need to use a loop. You know while as seen in your code. The loop keyword can be nested i.e. you can have a loop within a loop and you can arrange it so that it's checking for the amount of numbers outside of the number limit condition e.g.:
mylist = []
while len(mylist) < 10:
num = int(input("some text"))
while <your number condition>:
mylist.append(num)
...
...
or you can utilize for loop that will execute the block of code only N-times e.g. with range(10):
mylist = []
for _ in range(10):
num = int(input("some text"))
while <your number condition>:
mylist.append(num)
...
...
With a while loop you need to watch out for cases when it might just infinitely loop because the condition is always true - like in your case:
scores = []
score = < a number between 1 and 300, for example 1>
while score >= 1 and score <= 300: # 1 >= 1 and 1 <= 300 <=> True and True
scores.append(score)
score = int(input("Please enter a bowling score between 0 and 300: "))
print(scores)
which will exit in case you enter a number out of the interval but does not guarantee the N-times (10-times) you want. For that to happen you might want to adjust the loop a bit with break to stop the execution after 10 values are present:
scores = []
score = < a number between 1 and 300, for example 1>
while score >= 1 and score <= 300: # 1 >= 1 and 1 <= 300 <=> True and True
scores.append(score)
score = int(input("Please enter a bowling score between 0 and 300: "))
if len(scores) >= 10:
break # stop the while loop and continue to "print(scores)"
print(scores)
However that doesn't handle cases such as inputting 0 or 1000 let's say as once you choose the number out of the interval, it'll stop the while loop even if the amount of scores is less than 10.
And then there's the obvious ValueError when you simply press Enter / Return without entering a number or supply a non-numeric value such as two which is still a number, but will only crash instead converting to 2 with int().
For the first you'd need to encapsulate the number check in other loop or refactor it into something like this:
mylist = []
while len(mylist) < 10:
num = int(input("some text"))
if num >= 1 and num <= 300:
mylist.append(num)
which handles even wrong numeric input e.g. 1000 and will ask for another number.
To handle non-numeric input there are at least two ways - you either let it fail or you check the value first:
With fail first you pass the invalid value to int() automatically and Python interpreter will generate and raise an Exception.
mylist = []
while len(mylist) < 10:
try:
num = int(input("some text"))
except ValueError as error:
# do something with the error e.g. print(error)
# or let it silently skip to the next attempt with "continue"
continue
if num >= 1 and num <= 300:
mylist.append(num)
With value validating you can use isnumeric() method which is present on any string instance (which for your case is the return value of input() function):
mylist = []
while len(mylist) < 10:
num = input("some text")
if not num.isnumeric():
continue
if num >= 1 and num <= 300:
mylist.append(num)
And to make it more compact, you can chain the comparison, though with one unnecessary int() call when the value is correct assuming most of the values are incorrect. In that case num.isnumeric() evaluates to False first and prevents all int() calls while if the input is numberic you end up calling isnumeric() and 2x int():
mylist = []
while len(mylist) < 10:
num = input("some text")
if num.isnumeric() and 1 <= int(num) <= 300:
mylist.append(int(num))
or the other way around, assuming most of the values are correct you can go for the edge-case of incorrect value with try which would be slower afaik but should be faster than always asking whether a string isnumeric().
mylist = []
while len(mylist) < 10:
try:
num = int(input("some text"))
except ValueError:
continue
if 1 <= num <= 300:
mylist.append(num)
Each of the approaches has its own trade off. You can strive for readability, performance, compactness or any other trait and depending on the trait there will be a way to measure it e.g. for performance you might want to use time.time and for readability a linter such as pylint.
A minor extra, in case you are creating a CLI tool, you might want to handle Ctrl + C (interrupt/kill program, will raise KeyboardInterrupt) and Ctrl + D (end input, will raise EOFError). Both can be handled with try/except.
First, you have to define the list 'scores'.
while score >= 1 and score <= 300: means that if the input value does not between 0 and 300, the loop will be over. Therefore, you may not be able to complete the list of 10 integers. You can check this condition by using if instead of while.
The while loop need to check if the scores list has 10 elements or not.
scores = []
while len(scores) < 10:
score = int(input("Please enter a bowling score between 0 and 300:"))
if (1 <= score <= 300):
scores.append(score)
else:
print("Score must be between 0 and 300")
print(scores)

hailstone program in python

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

While loop doesn't read condition

I'm trying to make a program that will stop when it gets 5 prime numbers from a range.
I've completed most of the program except the part where it is supposed to stop after it gets 5 numbers.
I've added a condition for it to stop, once the counter reaches 5 but it does not stop and continues to list all the numbers in the range.
Here is code I have:
condition = 0
while condition < 5:
for numbers in range(2,20):
for divisor in range(2,numbers):
if (numbers % divisor) == 0:
break
else:
print(numbers)
condition +=1
The condition+=1 never goes through and it lists all the prime numbers from 1 to 20 even though I just want the first 5.
I've tried spacing options with the "condition +=1" but it still does not work
Any help would be appreciated
While is out of for loop, so cannot work obviously. A simple solution is to check required condition later:
for numbers in range(2,20):
for divisor in range(2,numbers):
if (numbers % divisor) == 0:
break
else:
print(numbers)
condition +=1
if condition >=5:
break
I think the real problem you are having is that you have written bad code. A much better approach to this problem is to isolate as many pieces as possible.
for example:
def is_prime(x):
"return true if x is prime, otherwise false"
# implement me!
return True
def get_first_n_primes_less_than_y(n, y):
number = 2
condition = 0
while condition != n and number < y:
if is_prime(number):
print(number)
condition += 1
number += 1
get_first_n_primes(5, 20)
The above code, with some tweaking can perform the same task. However, code like this is much simpler to debug and reason about because we have isolated chunks of code (is_prime, has nothing to do with the while loop)
num_results = 5
counter = 0
range_start = 2
range_end = 20
# iterate range
for number in range (range_start, range_end):
# iterate divisors
for divisor in range (2, number):
# check division
if (number % divisor) == 0:
break
else:
print ("%s is a prime number" % number)
counter += 1
break
# check if number of results has been reached
if counter == num_results:
break
# check if number of results has been reached
if counter == num_results:
break
The problem is that you need to run the entire content of the while block before you test the condition again.
Here is a way around
condition = 0
numbers=2
while condition < 5 and numbers < 20:
for divisor in range(2,numbers):
if (numbers % divisor) == 0:
break
else:
print(numbers)
condition +=1
numbers+=1

Why is my code running infinitely?

this is an even odd calculator that runs infinitely without any errors. Does anyone know how to fix this? Is it ok for me to call the method with the input from times?
def calc(time):
i = 1
while i <= time:
num = int(input("Enter your number"))
i + 1
x=0
y=0
if (int(num) % 2 == 0):
even = True
print("even")
elif (int(num) % 2 != 0):
odd = True
print("odd")
if (odd == True):
x += 1
elif (even == True):
y += 1
times = int(input("How many numbers will you be putting in this calc?"))
calc(times)
Just a few things you have wrong, the rest are pretty good, explain are in the comments:
All the variables in [x, y , even , odd] are useless at all, so that's why I erased them.
def calc(time):
i = 1
while i <= time:
num = int(input("Enter your number"))
i+=1 # important thing here, to update the value the symbol is +=, not just +
if (int(num) % 2 == 0):
print("even")
else: # there is no need of elif, if the number is not even, by definition, it is odd
print("odd")
times = int(input("How many numbers will you be putting in this calc?"))
calc(times)
you can try it here, and see how do correctly the job :) -> https://repl.it/Nm70/0
Line number 5 should be i = i+1
I'm assuming you have a formatting issue with stackoverflow and not a formatting issue with your actual code. The lines after your while loop need to be indented which I'm assuming you are doing. The problem you have is that you aren't incrementing i. The first line after your input you have i + 1. That does nothing as you aren't assigning it to anything. You have x += 1 and y += 1 later on in your code which increments and assigns. So basically change your i+1 line to be i += 1 or i = i + 1
Everything that you want in the while loop needs to be indented by one "tab" like so:
while i <= time:
#Code goes here

Python Code to Find x Prime Numbers w/ For Loop?

I am trying to put together a simple program which could work out n prime numbers. I would like to do this by using a nested for loop, where one would go through the numbers, and another would divide that number by all of the numbers up to it to see if it would be divisible by anything.
The problem I am having is that in the main for loop, I need to start it at 2, seeing as 1 would mess up the system and I don't want it to be considered a prime. For the loop to have a starting number however, it also needs an ending number which is difficult in this instance as it is hard to generate the largest prime that will be needed prior to the loop working.
Here's the program that I am using right now. Where I have marked X is where I need to somehow put an ending number for the For Loop. I guess it would be much simpler if I let the For Loop be completely open, and simply take out anything that '1' would produce in the loop itself, but this feels like cheating and I want to do it right.
check = 0
limit = int(input("Enter the amount of Prime Numbers"))
for i in range(2,X):
check = 0
if i > 1:
for j in range(2,i):
if (i % j) == 0:
check = 1
if check == 0:
print (i)
Thanks for your help!
You can step through an unlimited amount of numbers using a generator object.
Insert the following somewhere near the top of your code:
def infinite_number_generator(initial_value=2):
""" Generates an infinite amount of numbers """
i = initial_value
while True:
yield i
i += 1
What this does is it creates a function for constructing generator objects that "pause" whenever they reach the yield statement to "yield" whatever value is specified by the yield command, and then continue to execute from the next line beneath the yield statement.
Python's own range function is itself an example of a generator, and is roughly equivalent to (ignoring the step argument and other peculiarities)
def range(start, end):
i = start
while i < end:
yield i
i += 1
So your program would then look like this:
def infinite_number_generator(initial_value=2):
""" Generates an infinite amount of numbers """
i = initial_value
while True:
yield i
i += 1
check = 0
limit = int(input("Enter the amount of Prime Numbers"))
for i in infinite_number_generator():
check = 0
for j in range(2,i):
if (i % j) == 0:
check = 1
if check == 0:
print (i)
if i == limit:
break
I should also point out that the code you provided is buggy - it will never stop printing because there's no checking whether you've found your limit number of primes yet or not.
This should do what you want.
check = 0
limit = int(input("Enter the amount of Prime Numbers"))
counter = 0
i = 2
while counter < limit:
check = 0
if i > 1:
for j in range(2,i):
if (i % j) == 0:
check = 1
if check == 0:
counter += 1
print (i)
i += 1
In your code you start i with 2 and always increment by 1, so the i will always remain greater than 1, therefore the test if i > 1 is useless.
For efficiency you can stop the check at the square of i or i/2 (no divisors in [i/2 + 1, i[ ).
you can update your code as follow:
n = int(input("Enter the amount of Prime Numbers: "))
FoundPrimes = 0
i = 2
while FoundPrimes < n:
isPrime = True
for j in range(2,1 + i//2):
if (i % j) == 0:
isPrime = False
if isPrime:
FoundPrimes += 1
print(i, end = '\t')
i += 1

Categories