def age_20():
user_age= int(input("enter the age: "))
if user_age >= 20:
user_age= user_age - 20
return (user_age, "20 years difference from now" )
if user_age < 20:
user_age= user_age + 20
return (user_age, "20 years difference from now")
print(age_20())
Return value shows:
(5, '20 years difference from now')
how can i avoid single quotation mark and parentheses?
as it stands, you are returning a tuple containing an int and a string. If you want a single return you could use something like this instead:
return (str(user_age) + "20 years difference from now")
print(age_20()[1])
Since you're returning a tuple, and assuming you only want to print the string. If you want to still print both,
age = age_20()
print(age[0],", ",age[1])
Related
Beginner in python here. I'm trying to create a program that takes the takes the total price of many things and rounds them up or down depending on their last digit. My issue is that my first "if" statement always gets ignored but all my other "elif" statements work just fine
Code:
if str(finalTotalPrice).endswith("1" or "2") :
roundedDown = round(finalTotalPrice, 1)
print("Final Total = $" + str(roundedDown) + str(0))
print()
cashPayment = float( input("How much cash will you pay with? $"))
change = (cashPayment - roundedDown)
change = round(change, 3)
print("Your change is $" + str(change))
elif str(finalTotalPrice).endswith("8" or "9") :
roundedUp = round(finalTotalPrice, 1)
print("Final Total = $" + str(roundedUp) + str(0))
print()
cashPayment = float( input("How much cash will you pay with? $"))
change = (cashPayment - roundedUp)
change = round(change, 3)
print("Your change is $" + str(change))
elif str(finalTotalPrice).endswith("5" or "0") :
print("Final Total = $" + str(finalTotalPrice))
print()
cashPayment = float( input("How much cash will you pay with? $"))
change = (cashPayment - finalTotalPrice)
change = round(change, 3)
print("Your change is $" + str(change))
Python is not natural language. and and or do not behave the way you are used to. Let's look at the documentation:
>>> help(str.endswith)
Help on method_descriptor:
endswith(...)
S.endswith(suffix[, start[, end]]) -> bool
Return True if S ends with the specified suffix, False otherwise.
With optional start, test S beginning at that position.
With optional end, stop comparing S at that position.
suffix can also be a tuple of strings to try.
Your if statements should look like this:
if str(finalTotalPrice).endswith(("1", "2")):
As pointed out by tripleee, you're actually trying to do logically the wrong thing.
roundedDown = round(finalTotalPrice, 1)
This suggests that finalTotalPrice is a float. Never use floats for money. It'll mostly work for small values, but one day things will stop adding up. Instead, use an integer representing the amount of the smallest denomination you have – here, it looks like your dollar is divided into mils (you used round(..., 3)), so a dollar should be represented as 1000.
But can you still use the round function?
>>> help(round)
Help on built-in function round in module builtins:
round(number, ndigits=None)
Round a number to a given precision in decimal digits.
The return value is an integer if ndigits is omitted or None. Otherwise
the return value has the same type as the number. ndigits may be negative.
Yes, you can; just put in -1 to round to the nearest 10, -2 to round to the nearest 100, etc..
str(finalTotalPrice).endswith("1" or "2")
Ignoring the bug for a moment, this is a bad solution. If you're using floats, it will usually give a completely wrong answer, and if you're using ints it's inefficient. Once you're using ints, you can fix this; finalTotalPrice % 10 will get the last digit, finalTotalPrice % 100 will get the last two digits, etc.. Then you can do:
if finalTotalPrice % 10 in (1, 2):
if finalTotalPrice % 10 > 7:
if finalTotalPrice % 5 == 0:
as necessary.
Additionally, your cash payment code is identical in each if branch, so it should be written after them, not in each branch. And, while we're at it, let's make your variable names conform to PEP 8, the Python Style Guide, and improve input handling:
import re
MONEY_REGEX = re.compile(r"[$]?(\d*)(?:\.(\d+))?")
def input_dollars(prompt="", places=3):
"""Input a dollar amount, returned as an integer.
The prompt string, if given, is passed to the input function.
The places argument determines how many decimal places are allowed.
The return value is shifted by that many decimal places,
so that it is an integer.
>>> input_dollars("prompt? ", places=2)
prompt? a
invalid input
prompt?
empty input
prompt? 0.
invalid input
prompt? $32
3200
>>> input_dollars("prompt? ", places=2)
prompt? 32.450
too many decimal places
prompt? 32.4
3240
>>> input_dollars("prompt? ", places=2)
prompt? .6
60
>>> input_dollars("prompt? ", places=4)
prompt? $.472
4720
"""
fix = 10 ** places
while True:
text = input(prompt)
match = MONEY_REGEX.fullmatch(text)
if match is None:
print("invalid input")
continue
integer, fractional = match.groups()
if fractional is None:
if len(integer) == 0:
print("empty input")
continue
return int(integer) * fix
if len(fractional) > places:
print("too many decimal places")
continue
ipart = int(integer) if integer else 0
fpart = int(fractional.ljust(places, '0'))
return ipart * fix + fpart
def format_dollars(dollars, places=3):
fix = 10 ** places
return "${}.{:0>{}}".format(dollars // fix, dollars % fix, places)
def print_final_total(final_total, places=3):
print("Final Total =", format_dollars(final_total, places))
print()
final_total_price = input_dollars("What's the final total price? ")
if final_total_price % 10 in (1, 2, 8, 9):
print_final_total(round(final_total_price, -2))
elif final_total_price % 5 == 0:
print_final_total(final_total_price)
cash_payment = input_dollars("How much cash will you pay with? $")
change = cash_payment - final_total_price
print("Your change is", format_dollars(change))
This code probably doesn't do what you want it to. But, then, neither does your original.
This question already has answers here:
Python input never equals an integer [duplicate]
(5 answers)
How do I compare a string and an integer in Python? [duplicate]
(3 answers)
Closed 2 years ago.
rent = int("300")
shopping = int("150")
clothes = int("200")
print("you have ", + cash, "dollars")
print("You have 3 options to spend your money")
print("$300 - Rent - 1")
print("$150 - Shopping - 2")
print("$200 - Clothes - 3")
choice = input("Enter a number between 1-3 to choose how you spend your money")
if choice == 1:
print("you now have", cash - rent, "dollars")
elif choice == 2:
print("you now have", cash - shopping, "dollars")
the if/elif part will not print the stuff included inside of it.
The return value of input is a string, which cannot equal a number. Change your conditions to choice == "1" and choice == "2".
You should also include .strip() after your call to input just in case the user enters extra whitespace before or after the number. And remember to include an else block to handle the case that they enter something else.
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 5 years ago.
I was hoping to create a code to output if a next number entered is Up, Down or Same as the first one. I wanted it to exit when '0' is entered. I also wanted it to print the 'Up', 'Down', or 'Same' result at the end when exited with '0' instead of each time a number is entered.(if user enters: 4, 6, 1, 1, then 0 to exit, the final output will be Up, Down, Same printed.) Please tell me what I am missing, here is what i have so far:
firstNumber = input('Please enter your first number:')
nextNumber=input('Enter the next number(0 to finish)')
while nextNumber !=0:
if firstNumber<nextNumber:
print ('Up')
elif firstNumber>nextNumber:
print ('Down')
elif firstNumber==nextNumber:
print ('Same')
firstNumber = nextNumber
nextNumber=input('Enter the next number(0 to finish)')
You are comparing string, not numbers.
You should cast your input to integers with int().
here:
try:
firstNumber = int(input('Please enter your first number:'))
nextNumber = int(input('Enter the next number(0 to finish)'))
except ValueError:
# Handle cast error here
pass
while nextNumber !=0:
...
Note
As blubberdiblub explained:
< > compare pointer code of strings, that means "8" < "10" returns False while 8 < 10 returns True
input
The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.
So use
int(input(...))
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 6 years ago.
I'm not sure what I'm doing wrong. I want to make it so that if the user enters a name which isn't of those specified the program should print the else statement at the bottom. I also want the elif statements to work so if the users enter their age then the correct print statement should show.
name = input("What is your name?")
if name == "Jean Gray" or "Max Eisanhardt" or "James Howlett" or "Anne Marie":
age = int(input("How old are you?")
if age <= 12:
print ('You should be placed in the junior category because you are younger than 12 years old')
elif age >= 18:
print ('You should be placed in the senior category because you are older than 18 years old')
elif age <=17:
print ('You should be places in the teen category')
else:
print("Sorry, that name is not recognised.")
Your if statement will always currently evaluate to true, you should use the syntax
if a == "value1" or a == "value 2" or a == "value3":
//do something
Test that the year passed is greater than or equal to 1582.
def gregyear():
try:
year =raw_input("Pick a year greater than or equal to 1582. It has to be divisible by four.)\n")
year =float(year)
leapyear = "Yes"
except:
print "please, only numbers"
else:
year =float(year)
if year >= 1582:
if year % 4:
print year
leapyear= "Yes"
else:
leapyear= "No"
else:
print "Wrong... print a year greater than 1582"
return leapyear
gregyear()
print "leapyear is "+ leapyear +"."
First, in Python, 0 is falsey, and all other numbers are truthy. So, when you do this:
if year % 4:
… that will trigger if year % 4 is anything except 0, meaning if the year is not divisible by 4. So your logic is backward.
Second, while gregyear does return a value, you ignore that return value If you want to use it, you have to store it:
leapyear = gregyear()
Third, you can't add strings to numbers, so this will raise a TypeError:
print "leapyear is "+ leapyear +"."
What you probably wanted is to either pass the strings and number to print to magically concatenate together while printing, like this:
print "leapyear is", leapyear, "."
Notice that I removed the extra spaces, because print with commas automatically puts spaces between its arguments.
However, a better way to write this is with string formatting:
print "leapyear is {}.".format(leapyear)
As a side note, you're also missing the rule that makes 1700, 1800, and 1900 not leap years (while 1600 and 2000 are).