Why is the elif statement taking priority over my if statement? - if-statement

So I've got a number guessing game, all my previous code works fine, and you can probably see that I have the randomly generated number printed on the screen. But when I guess the number correctly I still get told I am wrong?
num = randrange(0, 100)
if num > 0 and num < 50:
print("The number is greater than 0 but smaller than 50")
elif num > 50 and num < 100:
print("The number is smaller than 100 but greater than 50")
print(num)
print('Start Guessing')
a = input()
a = input()
if a == num:
print ("You got the correct number, woohoo")
elif num > 0 and num < 20:
print ("Hint: The number is bigger than 0 but smaller than 20")
elif num > 20 and num < 40:
print ('Hint: The number is bigger than 20 but smaller than 40')
elif num > 40 and num < 60:
print ('Hint: The number is bigger than 40 but smaller than 60')
elif num > 60 and num < 80:
print ('Hint: The number is bigger than 60 but smaller than 80')
elif num > 80 and num < 100:
print ('Hint: The number is bigger than 80 but smaller than 100')
Sorry for the weird looking code, I've never used this site before.

Your code appears to be Python. You should indicate that in a tag. Also, since Python if statements rely on indentation you should post your code with proper indentation.
In the code:
a = input()
if a == num:
You are comparing a string to a number. You should cast a to an int.
if int(a) == num:

Related

Program determines how many numbers are positive, negative, or zeros

(Edit: Using python 2.7) I’m trying to get the user to input 10 numbers and the program needs to count and determine how many are negative, positive, or zeros.
However, everytime I run the program, it doesn’t give me the right number of negative or positive (or zero) numbers
i =[]
for i in range(10)
i = input('Enter Next Number: ')
n = 0
p = 0
z = 0
if (i > 0):
p = p+1
elif (i < 0):
n = n+1
elif (i == 0):
z = z+1
print "The number of negative numbers is",n
print "The number of positive numbers is",p
print "The number of zeros is",z
As Johnny Mopp suggested in his comment, you need to declare your counters outside of the loop. If you declare them inside, they are reset at every iteration and you are only counting the last number input by the user
n = 0
p = 0
z = 0
for i in range(10):
i = input('Enter Next Number:')
if (i > 0):
p = p+1
elif (i < 0):
n = n+1
else:
z = z+1
print "The number of negative numbers is",n
print "The number of positive numbers is",p
print "The number of zeros is",z
You will also want to convert the inputs to integers. If you really wish to add them to the list you will then need to iterate through the list after gathering all of the inputs. If retaining the values in a list is not needed #Bentaye answer will work just fine.
i =[]
n = 0
p = 0
z = 0
for num in range(10):
x = int(input('Enter Next Number: '))
i.append(x)
for y in range(len(i)):
if (i[y] > 0):
p = p+1
elif (i[y] < 0):
n = n+1
elif (i[y] == 0):
z = z+1
print ("The number of negative numbers is",n)
print ("The number of positive numbers is",p)
print ("The number of zeros is",z)

How can I improve this Python code to be more efficient?

I've just started to learn Python (my first dabble in coding) and this is my first time posting... I hope I'm not abusing the forum by asking this question (I'm essentially asking an expert to help me learn). Please let me know if this is frowned upon in the community.
For this assignment from a Michigan open course, I've been instructed to ask a user for input until the user enters "done", at which point the code should calculate the largest, smallest, sum, and average. In all my test-runs, it's worked fine. But I feel like there's probably a much simpler way to write this code. Can anyone offer suggestions for improvement?
largest = None
smallest = None
count = 0
sum = 0
while True:
try:
num = raw_input("Enter a number: ")
if num == "done" : break
num = float(num)
count = count + 1
sum = sum + num
avg = sum/count
if largest is None:
largest = num
if smallest is None:
smallest = num
if num < smallest:
smallest = num
elif num > largest:
largest = num
continue
except: print 'Invalid input'
print "Maximum is", int(largest)
print "Minimum is", int(smallest)
print "Count:", int(count)
print "Sum:", int(sum)
print "Average:", avg
Well there are a few things here:
you can drop the continue statement since it is the end of the loop anyway;
you can compress the if statements into if largest is None or num > largest: this will shortcircuit and make the loop smaller;
you can use x += y instead of x = x + y; and
you do not have to calculate the average inside the loop; calculating it once when the loop finishes, is enough.
So:
largest = None
smallest = None
count = 0
sum = 0
while True:
try:
num = raw_input("Enter a number: ")
if num == "done" : break
num = float(num)
count += 1
sum += num
if largest is None or num > largest:
largest = num
if smallest is None or num < smallest:
smallest = num
except: print 'Invalid input'
print "Maximum is", int(largest)
print "Minimum is", int(smallest)
print "Count:", int(count)
print "Sum:", int(sum)
print "Average:", sum/count
But in terms of big oh, you cannot improve much: calculating the sum, etc. simply require O(n) and it also costs O(n) to read the input anyway.
Furthermore some software engineering advice: don't use the blanket exception, always specify the exception you expect so:
largest = None
smallest = None
count = 0
sum = 0
while True:
try:
num = raw_input("Enter a number: ")
if num == "done" : break
num = float(num)
count += 1
sum += num
if largest is None or num > largest:
largest = num
if smallest is None or num < smallest:
smallest = num
except ValueError: print 'Invalid input'
print "Maximum is", int(largest)
print "Minimum is", int(smallest)
print "Count:", int(count)
print "Sum:", int(sum)
print "Average:", sum/count
An alternative approach to accomplish this is to store all of the inputs in a list, and then use the built-ins min(),max(),len() and sum() to find values:
num=raw_input("Enter a number: ")
nums=[]
while num!="done": #check if user has finished entering inputs
try:
nums.append(int(num)) #append the input as an integer to a list
num=raw_input("Enter a number: ") #get another input
except ValueError:
print "Invalid input"
print "Maximum is",max(nums)
print "Minimum is",min(nums)
print "Count:",len(nums)
print "Sum: ",sum(nums)
print "Average: ",sum(nums)/len(nums)
Output:
Enter a number: 1
Enter a number: 2
Enter a number: 3
Enter a number: 4
Enter a number: 5
Enter a number: 6
Enter a number: done
Maximum is 6
Minimum is 1
Count: 6
Sum: 21
Average: 3.5

how to change a variable name in a while loop?

I have a question. I want to use a while loop and in the while loop I have to assign a view lists, but they shouldn't be assigned to the same variable over and over again. but I don't know how much lists I have to assign.
K = 2
D = 2
while( K <= 2 or K >= 20):
K = int(raw_input("Give the number of candidates running for speaker. "))
if(K <= 2 or K >= 20):
print("Sorry, wrong input.")
while(D <= 2 or D >= 1000):
D = int(raw_input("Give the number of people who take part in the meeting. "))
if(D <= 2 or D >= 1000):
print("Sorry, wrong input.")
row = 1
vlist = [[]*D]
while(D > row):
while(K < len(vlist[row-1])):
number = int(raw_input("Give a number of a person you want to win: "))
if(0 < number < K and number not in vlist[row-1]):
vlist[row-1].append(number)
else:
print("Sorry, wrong input, try again.")
row += 1
this is what I have now, but it throws the following error: List index out of range. I don't get why...
First item of list is empty: len(vlist[0])
returns 0, so list[row-1] is trying to acces element of -1 index.

Using < & > (less than and greater than) in an if statement in Jython

I'm writing a small program that requires a few if statements like so:
number=x/(y*y)
if number <5:
print "blahblahblah"
if number >5 or <10:
print "blahblahblah"
if number >10.5 or >15.0:
print "blahblahblah"
if number >15:
print "blahblahblah"
Basically I'm having trouble with using both > and < in my if statement and can't work out how to say "if less than 4 or more than 5"
When I load the program I get the following error -
Invalid syntax
Your code contains at least one syntax error, meaning it is not legal jython.
Any help would be greatly appreciated
Here you go:
if number > 10 and number < 20 then:
print "Number between 10 and 20"
Each comparison is an independent expression, combined together with and, or, etc.
As an addition to Paul answer with or, and etc you can use if 5 < number < 10::
if number < 5:
print("a")
if 5 < number < 10:
print("b")
if 10 < number < 15:
print("c")
if number > 15:
print("d")
You can also use elif (short of else if) and else which I prefer:
if number < 5:
print("a")
elif number < 10:
print("b")
elif number < 15:
print("c")
else:
print("d")
BTW in your code you used or instead of and.

How to calculate first n prime numbers?

Assume the availability of a function is_prime. Assume a variable n has been associated with a positive integer. Write the statements needed to compute the sum of the first n prime numbers. The sum should be associated with the variable total.
Note: is_prime takes an integer as a parameter and returns True if and only if that integer is prime.
Well, I wrote is_prime function like this:
def is_prime(n):
n = abs(n)
i = 2
while i < n:
if n % i == 0:
return False
i += 1
return True
but it works except for n==0. How can I fix it to make it work for every integer?
I'm trying to find out answers for both how to write function to get the sum of first n prime numbers and how to modify my is_prime function, which should work for all possible input, not only positive numbers.
Your assignment is as follows.
Assume the availability of a function is_prime. Assume a variable n has been associated with a positive integer. Write the statements needed to compute the sum of the first n prime numbers. The sum should be associated with the variable total.
As NVRAM rightly points out in the comments (and nobody else appears to have picked up on), the question states "assume the availability of a function is_prime".
You don't have to write that function. What you do have to do is "write the statements needed to compute the sum of the first n prime numbers".
The pseudocode for that would be something like:
primes_left = n
curr_num = 2
curr_sum = 0
while primes_left > 0:
if is_prime(curr_num):
curr_sum = curr_sum + curr_num
primes_left = primes_left - 1
curr_num = curr_num + 1
print "Sum of first " + n + " primes is " + curr_sum
I think you'll find that, if you just implement that pseudocode in your language of choice, that'll be all you have to do.
If you are looking for an implementation of is_prime to test your assignment with, it doesn't really matter how efficient it is, since you'll only be testing a few small values anyway. You also don't have to worry about numbers less than two, given the constraints of the code that will be using it. Something like this is perfectly acceptable:
def is_prime(num):
if num < 2:
return false
if num == 2:
return true
divisor = 2
while divisor * divisor <= num:
if num % divisor == 0:
return false
divisor = divisor + 1
return true
In your problem statement it says that n is a positive integer. So assert(n>0) and ensure that your program outer-loop will never is_prime() with a negative value nor zero.
Your algorithm - trial division of every successive odd number (the 'odd' would be a major speed-up for you) - works, but is going to be very slow. Look at the prime sieve for inspiration.
Well, what happens when n is 0 or 1?
You have
i = 2
while i < n: #is 2 less than 0 (or 1?)
...
return True
If you want n of 0 or 1 to return False, then doesn't this suggest that you need to modify your conditional (or function itself) to account for these cases?
Why not just hardcode an answer for i = 0 or 1?
n = abs(n)
i = 2
if(n == 0 || n == 1)
return true //Or whatever you feel 0 or 1 should return.
while i < n:
if n % i == 0:
return False
i += 1
return True
And you could further improve the speed of your algorithm by omitting some numbers. This script only checks up to the square root of n as no composite number has factors greater than its square root if a number has one or more factors, one will be encountered before the square root of that number. When testing large numbers, this makes a pretty big difference.
n = abs(n)
i = 2
if(n == 0 || n == 1)
return true //Or whatever you feel 0 or 1 should return.
while i <= sqrt(n):
if n % i == 0:
return False
i += 1
return True
try this:
if(n==0)
return true
else
n = abs(n)
i = 2
while i < n:
if n % i == 0:
return False
i += 1
return True