Why is my if statement not comparing strings properly? [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 months ago.
Improve this question
I'm writing code for a program that asks the user for their telephone number. It goes through multiple conditionals until a valid number format is given. One of the conditions is that the first 3 digits of the input must be between 200 and 999. The problem is I'm pretty sure I'm writing it correctly, but I have no idea why it's not 'tripping' the condition when I put an invalid number in. Like, say, '127-444-9870'. All the other conditions are tripping. I thought maybe I just couldn't compare strings in this way, but when I ran it in the console, it worked properly. To test I put num1 = '1' and num2 = '3' and then ran num1 < num2 which returned 'true'. So, I think what I'm doing is possible.
Here's my code so far:
number = ''
while number.lower() != 'q':
number = input('Enter phone number or q to quit: ')
numnums = number.split('-')
if number.lower() == 'q':
break
elif number.count('-') != 2:
print('Phone number should have 2 dashes.')
elif not numnums[0].isdigit() or len(numnums[0]) != 3:
print('First part of phone number must be a 3-digit number.')
elif not numnums[1].isdigit() or len(numnums[1]) != 3:
print('Second part of phone number must be a 3-digit number.')
elif not numnums[2].isdigit() or len(numnums[2]) != 4:
print('Last part of phone number must be a 4-digit number.')
elif '200' > numnums[0] > '999':
print('first 3 digits must be between 200 and 999')
else:
number = number.replace('-', '.')
print(f'Phone number with dashes replaced: {number}')

You're using the wrong operator. > is greater than, and < is less than. You code says: "if numnums[0] is less than 200 and numnums[0] is greater than 999, then do this code". Instead, you want it to say: "if numnums[0] is greater than 200 and numnums[0] is less than 999". Just change this line:
elif '200' > numnums[0] > '999':
to
elif '200' < numnums[0] < '999':
You may also want to consider changing these types from strings to numbers. It will make your code more readable. Like this:
elif 200 < int(numnums[0]) < 999:
However, this doesn't change the output of your code.

Two mistakes here:
elif '200' > numnums[0] > '999'
The logic doesn't make sense because there are no numbers smaller than 200 and larger than 900.
You're comparing strings (numnums[0] is a string) while your logic requires comparing numbers.
It should be something like
elif 999 > int(numnums[0]) > 200

Related

Why the While loop continues and how to calculate the average based on numbers input? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last month.
Improve this question
Hi I'm trying to solve this coding homework:
Write a program that always asks the user to enter a number. When the user enters the negative number -1, the program should stop requesting the user to enter a number. The program must then calculate the average of the numbers entered excluding the -1.
I define the while loop to make sure it keeps asking, as:
while n != -1
str(input("enter your number:"))
But whenever I try to input -1, it just keeps on asking to enter the number regardless.
Also, I'm not sure what is the best way to define the average excluding -1, none of the lessons prior to this assignment talked about this. I have Googled about it but none of the examples match this particular assignment, even fumbling around did not help.
Thank you for your help :)
Presumably n is meant to be the user input, but you're never assigning a value to n. Did you mean to do this?
n = str(input("enter your number:"))
Also, you're comparing n to -1, but your input isn't a number; it's a string. You can either convert the input to a number via n = int(input(...)), or compare the input to a string: while n != '-1'.
You could ask for a number the if it is not equal to -1 enter the while loop. So the code would be:
n = float(input("What number?"))
if n != -1:
sum += n
nums_len = 1
while n != -1:
sum += 1
nums_len += 1
n = float(input("What number?"))
print("The average is", str(sum/nums_len))
Thanks everyone, this is the final code with the correct values that gives the average of user inputs
n = float(input("What number?"))
if n != -1:
sum = 0
nums_len = 0
while n != -1:
sum += n
nums_len += 1
n = float(input("What number?"))
print("The average is", float(sum/nums_len))

Showing all odd numbers instead of prime numbers [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last year.
Improve this question
def prime_num_gen():
try:
r = int(input('Type in the number till which you want to generate your prime numbers : '))
if r <= 2:
print('There is no prime number smaller than 2, 2 is the smallest prime number')
#A list to store primes
#Storing 2 already, because I need a number to start with
prime_num = [2]
#Counter
#Counter will be divided and if it's a prime; will append it
x = 3
#Starting with 3 cus 2 is already considered
#Having a jump of 2, cus no even num is prime, so considering only odd nums
while x <= r:
for num in range(3,x,2):
if num % x == 0:
x += 2
break
else:
prime_num.append(x)
x += 2
print(prime_num)
except:
print('Please only give input as a number!\nTry again')
For some reason, this code is including all odd numbers as prime numbers. I am complete a novice in coding and even if this seems like a pretty obvious mistake, please tell me so 🙏.
Any help will be appreciated!!
There is a small bug in your code. Instead of the condition
if num % x == 0:
You should do
if x % num == 0:
Since num will always be smaller than or equal to x, so its modulus with x will always give the number once again.
Here is a slightly different implementation that can be faster in different ranges. The basic algorithm is quite simple.
def isprime(n):
for i in range(2,int(n**0.5)+1):
if n%i == 0:
return False
return True
for i in range (1,100):
if isprime(i) == True:
print(i)
It takes O(N log (log N)) time to find all prime numbers less than N.

Odd and Even HackerRank challenge [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I'm trying to solve a problem on HackerRank and I sent the code, it worked in amost all the scnarios except for scnario 7 and 3 where they insert 18 and it should return "Weird" and when they insert 20 it should return "Weird" as well according to the website.
The rules of the challenge are:
Given an integer, n, positive number from 1 to 100 , perform the following conditional actions:
If n is odd, print Weird
If n is even and in the inclusive range of 2 to 5, print Not Weird
If n is even and in the inclusive range of 6 to 20, print Weird
If n is even and greater than 20, print Not Weird Input Format
A single line containing a positive integer, .
Constraints
Output Format
Print Weird if the number is weird. Otherwise, print Not Weird.
And my code was:
n = 0
n = int(input('Type a number between 1 and 100: '))
odd = False
even = True
# ODD / EVEN
if (n%2) == 0:
n = even #True
else:
n = odd #False
# Is this odd or is this even?
if n == odd:
print ('Weird')
if n == even > 5 < 20:
print('Weird')
elif n == even > 1 < 6:
print ('Not Weird')
else:
print('Not Weird')
I can't see what I did wrong, can you help me to solve it so it can work in all scnarios?
There's a lot to unpick here. As this is an assignment, I'm not going to print the full solution out here, but I will point out the mistakes you've made so you can come to the correct solution.
First issue: reassigning 'n'.
You assign the value from the input to n, then subsequently replace it with the value of odd or even. This means you have lost the original input number. Instead you should assign the result to a new variable (such as 'isEven').
Second issue: uneccesarry 'if'
The result of 'n%2 == 0' is already True/False, depending if n is an even/odd number. So you can simply assign the result, rather than use an 'if' block.
Third issue: multiple operators
Logical operators have an order of operation, and resolution. The statement 'n == even > 5 < 20' makes no logical sense. Instead you should do independent Boolean comparisons, and join them with "and" or "or". E.g. 'if isEven and n < 5 and n> 20'.

Is there a way to say if a number is greater than or less than in python? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
Im trying to find a way to say that 'if the number a user picks is below 1 or above 20, then print "invalid input"'.
I'm using this for a number guessing game and its to find numbers that aren't in the range of 1 to 20, so that they do not count as guesses.
I have tried:
if userNum < 1
print("invalid input")
if userNum > 20
print("invalid input")
I have also tried this:
if 1 > userNum > 20
print("invalid input")
You're missing a colon after the condition.
Try this
if 1 > userNum > 20:
print("invalid input")
First you need to make sure that your user input is a number, not a string.
As soon as you are comparing numbers, you can use < and > to test for smaller/greater.
if userNum > 20 or userNum < 1:
print("invalid input")
def funcCmp(num):
if num < 0 or num > 20:
print ("Invalid")
funcCmp(21)
funcCmp(-1)
Simple or operator does your condition checking ! Try with above

Python Doesn't return to while loop [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm new with Python and I'm having a bit of trouble with my program. Whenever I input a second number that is larger than the first number "mCounter" should be set to false, and since there is a while loop, it should ask me to input the number of digits again. For some reason this doesn't happen. Whenever I input a second number that is larger than the first the program just stops.
Any help would be greatly appreciated.
Thanks!
import random
#Introduction
print('Choose the mode that you would like to enter by typing the letters in the brackets')
problem = input('Multiplication(M) Addition (A) Subtraction (S) Division (D): ')
#Multiplication
if problem == 'M' or problem == 'm':
mCounter = False
while mCounter == False:
mInput1 = int(input('Enter the amount of digits you would like in the first number you are multiplying.\nThe first number should be greater or equal to the second number: '))
mInput2 = int(input('Enter the amount of digits you would like in the second factor: '))
mCounter = True
if mInput2 > mInput1:
print('The first number MUST be greater or equal to the second number. Please try again!')
mCounter == False
else:
print('nothing')
To set the value of mCounter, do this:
mCounter = False
rather than this:
mCounter == False
The code you have there is just comparing the value of mCounter with False, and then ignoring the result of that comparison.
Instead of:
mCounter == False
you want:
mCounter = False
You need an assignment, rather than a conditional check.
The statement mCounter == False doesn't change mCounter. You have to use = for assignment.
if mInput2 > mInput1:
print('The first number MUST be greater or equal to the second number. Please try again!')
mCounter = False #<-- use = instead of ==

Categories

Resources