Syntax error if, elif statements [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 8 years ago.
Improve this question
I'm having trouble trying to get this code to work. It keeps coming up with SyntaxError: invalid syntax
adult = int(input("No adults:")
child = int(input("No children:")
type = int(input("Well done or Rare:")
if adult < 0:
print("Enter number >=0)
elif child < 0:
print("Enter number >=0)
elif type != "W" or type != "R":
print("error")
If the user types in the correct number I want it to go to the next question in line. If user inputs incorrect data I want the error message and then the same question to be repeated.
Thanks!!

Try this:
adult = int(input("No adults:"))
child = int(input("No children:"))
type = int(input("Well done or Rare:"))
if adult < 0:
print("Enter number >=0")
elif child < 0:
print("Enter number >=0")
elif type != "W" or type != "R":
print("error")
Compare it with your code.
Your code includes: missing ), ", bad indentation.
Note: Using type as a variable will mask the built-in function "type" within the scope of the function or the block which variable is defined within. So while doing so does not raise a SyntaxError, it seems a bad programming experience.

You have some missing brackets:
int(input("No adults:")
^
int(input("No children:")
^
int(input("Well done or Rare:")
^ need another to close int()
Also, make sure your indentation is correct:
if adult < 0:
print("Enter number >=0)
elif child < 0:
print("Enter number >=0)
elif type != "W" or type != "R":
print("error")

Related

Why is my if statement not comparing strings properly? [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 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

How to get the code to make the user pick between different ranges of random numbers in python? [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 1 year ago.
Improve this question
I want to make a code that generates random numbers from 3 different choices that the user can pick from but the code just doesn't recognize the variable I put to represent those choices. Here is what I've got so far:
import random
choose = int(input("1, 2 or 3? "))
if choose == 1:
num == random.randint(1, 10)
elif choose == 2:
num == random.randint(10, 50)
elif choose == 3:
num == random.randint(1, 100)
else:
print("Invalid input")
print(num)
Can someone help?
There is some confusion. == is for comparison like is a equal to b? and = is for assignment. So, just replace to this num = random.randint(10, 50).
Also, you should consider moving print(num) inside the if...elif...else statements as it can raise an error when invalid input is provided.
import random
choose = int(input("1, 2 or 3? "))
if choose == 1:
num = random.randint(1, 10)
print("Your Number: "num)
elif choose == 2:
num = random.randint(10, 50)
print("Your Number: "num)
elif choose == 3:
num =random.randint(1, 100)
print("Your Number: "num)
else:
print("Invalid input")

Why does when I ask for a value in an input, and put in that input it does not return the value i want [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 1 year ago.
Improve this question
When I run this code and put in 15 as my input, why does it say you are older than me when I specifically told Python when the input is 15 to print you are my exact age.
age=input("What is your age?")
if int(age) >= 15:
print("Your older than me!")
elif int(age) <= 15:
print("Your younger than me!")
elif int(age) == 15:
print("Your my exact age!")
The first if statement you have will evaluate true when age is 15, that is because >= checks for greater or equal. You can change that to just >. That also goes for <=, this will check for less or equal. So age <= 15 will evaluate to true. Change that to only <
you placed <= and >= statements, the equal in those means bigger/smaller or equal to X.
in your code you need to replace them with > and < because you already have an equal statement.

Trouble with Python: "TypeError: 'str' object not callable" when using round() function, value is a FLOAT variable [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 2 years ago.
Improve this question
I am quite new to Python, and have just learned basic conditionals and logic operators. I am currently working on a project that takes the weight of a user and converts it to kg if it is in lbs, or lbs if it is in kg, depending on user input.
While I was testing out my program, the console spit an error:
I double checked my code and I am rounding a variable that stores a float value. It is not a string, so I don't know why I got this error. I tried changing the variable name and reseting but those didn't help. Am I missing something painfully obvious here? I apologize if I am, I'm still very new to Python and to programing in general but would like to get good at it. Here is my source code:
import sys
un_weight = int((input("Weight: ")))
value = input("Is your weight in (L)bs or (K)g: ")
if (value == "K") or (value == "k"):
conv = un_weight * 2.2
elif (value == "L") or (value == "l"):
conv = un_weight / 2.2
else:
print("That weight type does not exist. Please try again.")
round = input("Do you want your number rounded? (Y/N): ")
if (round == "Y") or (round == "y") or (round == "Yes") or (round == "yes"):
print("Rounding Number... ")
weight = round(conv)
round_op = True
elif (round == "N") or (round == "n") or (round == "No") or (round == "no"):
print("Rounding operation terminated. Calculating decimal weight...")
round_op = False
else:
print("That is not a valid answer. Please try again.")
exit()
if (value == "K") or (value == "k") and not round_op:
print(f"Your weight is {conv} Lbs.")
elif (value == "L") or (value == "l") and not round_op:
print(f"Your weight is {conv} Kg.")
elif (value == "K") or (value == "k") and round_op:
print(f"Your rounded weight is about {weight} Lbs.")
elif (value == "L") or (value == "l") and round_op:
print(f"Your rounded weight is about {weight} Kg.")
else:
print("Error: Operation failed. Please try again later.")
exit()
As you can see, the un_weight variable is immediately converted into an integer with the int() function, so I don't know why Python thinks it is a string (if that even is what it's saying). Please excuse the dumb question; I would just like to know the reason behind this. Thanks for the help in advance.
The problem is here:
round = input("Do you want your number rounded? (Y/N): ")
You've replaced the round() function with your variable that contains the input string.
Don't use variable names that are the same as built-in functions. There can only be one thing named round -- if it's your string, then it's not the mathematical function.

Why aren't these two strings the same, dictionary and 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 5 years ago.
Improve this question
In the code:
skill = input("Which skill would you like to increase by 1 ?: ")
for x in abilities:
if x.lower() == skill.lower():
abilities[x] += 1
break
print("Sorry, I don't see that skill...")
and the dictionary being:
abilities = {
"STR" : 10,
"DEX" : 10,
"CON" : 10,
"INT" : 10,
"WIS" : 10,
"CHR" : 10 }
Then when for the input the string "STR" is put in, I get the response telling me the strings are not identical.
To my knowledge they are? Is there a really simple mistake here which I'm accidentally looking over, or is there a certain rule with this kind of thing?
for x in abilities:
if x.lower() == skill.lower():
abilities[x] += 1
break
print("Sorry, I don't see that skill...")
that will print the error message regardless of the loop outcome.
Just add a else to your for loop and it will work
for x in abilities:
if x.lower() == skill.lower():
abilities[x] += 1
break
else:
# called when for loop ended without hitting break or return
print("Sorry, I don't see that skill...")
however this is a very inefficient way of counting, you're not using the dictionary as it is, but just as a list of tuples, so linear search, highly inefficient
Use (without a loop):
skill = skill.upper() # so casing matches the keys
if skill in abilities:
abilities[x] += 1
You know that abilities' keys are all upper-case strings, so you should convert the input to uppercase too:
skill = input("Which skill would you like to increase by 1 ?: ").upper()
if skill in abilities:
abilities[x] += 1
else:
print("Sorry, I don't see that skill...")

Categories

Resources