I'm starting to practice Python programming so please excuse if it's some very basic concept for you.
I'm trying to print result based on number comparison.
User Input: Any number between 1 to 100
Outputs: Based on comparisons, the output should be printed accordingly. Please look at the code below:
x = int(input("Enter a number: ").strip())
if 0<x<101:
if (x%2 == 1):
print("Weird")
elif (x%2 == 0 & 1<x<6):
print("Not Weird - between 2 to 5; inclusive")
elif (x%2 == 0 & 5<x<21):
print("Weird - between 5 to 20; inclusive")
elif (x%2 == 0 & x>=20):
print("Not Weird - Greater than 20")
else:
print("Please enter a number between 1 & 100, limits inclusive. Exiting program...")
It does the job for first 3 if comparisons. But if I input any even number above 20, it prints the final else loop statement.
I modified the last if to 20<x<100, then it runs properly.
For some reason, I can't get the x>20 condition work. Any ideas what I'm doing wrong?
Quick Answer: Use and instead of &. and is for boolean operators and & is used for bitwise operations (can be good for arrays which this is not).
Another note, you have 5<x<20 which is not actually inclusive of 5 and 20 (use 5<=x<=20 or 4<x<21) and x>=20 is not just greater than 20 it is also equal (use x>20). However if you actually want to restrict it to less than or equal to 100 obviously use 20<x<101.
As suggested by outflanker in the comments above, pasting the corrected code.
x = int(input("Enter a number: ").strip())
if 0<x<101:
if (x%2 == 1):
print("Weird")
elif (x%2 == 0 and 1<x<6):
print("Not Weird - between 2 to 5; inclusive")
elif (x%2 == 0 and 5<x<21):
print("Weird - between 5 to 20; inclusive")
elif (x%2 == 0 and x>=20):
print("Not Weird - Greater than 20")
else:
print("Please enter a number between 1 & 100, limits inclusive. Exiting program...")
Related
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.
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")
I am trying to learn Python basics. I am designing a code that would print a triangle, code posted below. The expected output of the program must be a triangle from the right side not from the left which part of the code to modify to get the expected output.
The output of the program should not be like below
I want the output to be like this
Any help on this is highly appreciated. Thanks
while True:
n = int(input("enter a number between 0 and 10:"))
if 0 <= n <= 10:
break
print('try again')
rows = n
for num in range(rows+1):
for i in range(1, num+1):
if num % 2 == 0:
#print(end="" '#')
print('#',end="")
else:
#print(num)
print(num,end="")
print(" ")
We can use a list to create the elements (when it's an odd number just append the value in number times otherwise character '#' number times as the description said )of the triangle and then use a for loop to print them as below:
while True:
n = int(input("enter a number between 0 and 10:"))
if 0 <= n <= 10:
break
print('try again')
result = [idx*'#' if idx % 2 == 0 else f'{idx}'*idx for idx in range(1, n+1) ]
for i in range(len(result)):
print(' '*(n-i-1), result[i])
The result would be:
1
##
333
####
55555
Hope this can help you :)
Checking your code with the input (5) gives the output (1##333####55555 )
but the following code for the same input (5) gives the output (55555####333##1 )
while True:
n = int(input("enter a number between 0 and 10:"))
if 0 <= n <= 10:
break
print('try again')
rows = n
for num in range(rows, 0,-1):
for i in range(num+1, 1,-1):
if num % 2 == 0:
#print(end="" '#')
print('#',end="")
else:
#print(num)
print(num,end="")
print(" ")
Hope this answer your question
So im new to python and this question should be fairly easy for anybody in here except me obvisouly haha so this is my code
for c in range(0,20):
print("number",c+1)
number = input ("Enter number:\n")
number = int(number)
if (number < 1 or number > 9):
print("try again by inputing a positive number < 10")
c -=1
so as you may think if the number someone inputs is bigger than 9 or smaller than 0 i just want my c to stay where it is so i get 20 positive numbers from 1-9 instead it doesnt do that and it keeps increasing even tho i have the c-=1 thingy down there
First, do not use range(0,20) but range(20) instead.
Second, range returns an iterator. This means, that when you do c-=1 you do not go back in the iterator, you decrease the number returned by the iterator. Meaning that if c=5 and the number you entered in input is 20, c will become 4, but when returning to the start of the loop, c be be 6.
You probably want something of this sort:
c = 0
while c < 20:
print("number",c+1)
number = input ("Enter number:\n")
number = int(number)
if (number < 1 or number > 9):
print("try again by inputing a positive number < 10")
continue
c += 1
an alternative and simple solution to this would be:
i=20
while(i!=0):
number = input("Enter number:\n")
number = int(number)
if (number <1 or number >9):
print("Invalid no try within 0-9 ")
else
print(number)
i-=1
I'm relatively new to Python and trying to build a function to check primes because I thought it would be a good starter project, but my code returns everything as a prime, so it's obviously gone wrong. I get this is an inefficient way to do it, but I want to understand how to do it the long way first. Here's my code so far:
def Prime(n):
if n == 1 or n == 2 or n == 3:
print("This number is prime.")
else:
i = n - 1
while i > 0:
if n % i == 0:
break
print("This number is not prime.")
else:
i = i - 1
print("This number is prime.")
def Main():
n = int(input("What is the number you'd like to check?"))
Prime(n)
answer2 = input("Thank you for using the prime program.")
Main()
Mathematically speaking you could check only all the int between 0 and sqrt(n) to judge a number is prime or not as for the logic, you are missing negative number handling plus other things please see my following code:
def prime(n):
n = abs(n)
if n<4: return True
i = int(sqrt(n))
while i > 1:
if n % i == 0: return False
i -= 1
return True
plus you should add this to your import
from math import sqrt
Here is your program with a couple changes:
def Prime(n):
if n == 1 or n == 2 or n == 3:
print("This number is prime.")
else:
i = n - 1
while i > 1:
if n % i == 0:
print("This number is not prime.")
return
i = i - 1
print("This number is prime.")
return
def Main():
n = int(input("What is the number you'd like to check? "))
Prime(n)
print "Thank you for using the prime program."
Main()
First, i is now compared until i > 1 rather than 0 as every number is divisible by 1 and hence all numbers would be prime if the original condition was used.
Secondly, the break statement is substituted with return. Although break would work, the program would need more modifications in that case because the message for a prime number would always be printed at the end (along with not a prime message). Also, the return statement was moved after the print to actually get a print. More importantly, the message that a number is a prime was moved outside the while - otherwise the message would be printed on every iteration.
I also removed the else and the i is decremented right in the while loop which is to me a more readable alternative.
Finally, your last statement was, I assume, supposed to be an output, which it is now. I also added a space to the user prompting message so that the number displays more nicely.
It's not easy to explain the logic flaw, but you can see the following code
def Prime(n):
if n == 1 or n == 2 or n == 3:
print("This number is prime.")
else:
i = n - 1
while i > 0:
if i == 1 or n == 2 or n == 3:
print("This number is prime.")
break
if n % i == 0:
print("This number is not prime.")
break
else:
i = i - 1
def Main():
n = int(input("What is the number you'd like to check? "))
Prime(n)
print("Thank you for using the prime program.")
Main()
Ok, first off, your code will never print "This number is not prime." because you've put a break statement right before it. You would want to reverse those two lines such that it becomes:
print("This number is not prime.")
break
Also, the line i = n - 1 should be changed to i = n so that you check the starting number as well, and not just the numbers lesser than it. So if you try the code now, you'll notice that you're printing whether every number that you check is prime or not, not just the input value. To remedy this using your code structure, use a flag. For example:
def Prime(n):
flag = true
if n == 1 or n == 2 or n == 3:
print("This number is prime.")
else:
i = n
while i > 0:
if n % i == 0:
print("This number is not prime.")
break
else:
i = i - 1
if flag == true:
print("This number is prime.")
The flag check should be outside the loop.