How do I add the sum of two inputs? - python

Hello everyone I am very new to Python I am taking a beginner course at my college, and I am stuck on one portion of my project. Basically the goal of my code is to produce the output so that when I enter any age and name the result is supposed to find the sum of the age and number of letters in the entered name. So far this what I have typed up.
print('What is your name?')
myName = input()
print('What is your age?')
myAge = input()
sum = myAge + str(len(myName))
print(myName + ', if we add the number of letters in your name to your age then you will be ' + sum + ' in ' + str(len(myName)) + ' years.')
When I run the script all I get is the age+length of name which gives me a combination and not a sum. example 21 + 4 = 214.
Basically my issue with this is that I don't understand how to find the sum of both inputs so that I get result of adding age and the length of letters in a name. The last portion that I am trying write should in other words be this "Name, if we add the number of letters in your name to your age then you will be # in # years."
If anyone can explain to me how I can accomplish this then I would greatly appreciate it I have spent hours looking into this issue but can't figure it out.

When you use input() it returns a string.
So when setting it to sum, you end up with "21" + "4" (which will result in a string) -> "214"
Try converting myAge to an int like so
sum = int(myAge) + len(myName)
This will make it where you add 21 + 4 (now both numbers), so you'll get 25

Result of "input()" always is a string. You need to convert your input to integer using:
myAge = int(input('What is your age?'))

During the sum of the two variables should be converted to integers or decimals
print('What is your name?')
myName = input()
print('What is your age?')
myAge = input()
sum = float(myAge) + float((len(myName)))
print(myName + ', if we add the number of letters in your name to your age then you will be ' + str(sum) + ' in ' + str(len(myName)) + ' years.')

Related

How do add whitespace in between a word in python

Hi I am a newbiew learning python and i have a very simple question and can't seem to work it out.
I have built this little program and i was just wondering one thing.
print("Hello Sir !!!")
num1 = input("Enter a number: ")
num2 = input("Enter another Number: ")
result = float(num1) + float(num2)
print(result)
num3 = input("Enter your final Number: ")
result = float(num3) / (float(num1) + float(num2))
print("Your final total is:", result)
print("You are now finished")
print("Have an Amazing day!! ")
RESULT =
Hello Sir !!!
Enter a number: 50
Enter another Number: 50
100.0
Enter your final Number: 5
Your final total is: 0.05
You are now finished
Have an Amazing day!!
Process finished with exit code 0
If i wanted to write "Your final total is:0.05" or "Your final total is:
0.05"
How would i move it closer or further away?
Thank you for your help today
If you want to add more whitespaces, you can just added it inside the string. If you want a new line, you can use "\n" in your string, which indicate the start of a new line.
Check this link to find out more about escape characters:
https://www.tutorialspoint.com/escape-characters-in-python
You can do
print("Some string: " + variable) # Add a whitespace at the end of your string
if you have string with variable or
print(variable1 + ' ' + variable2)
If you need space between 2 variables or use \n if you need to make a newline

How to have integer subtract from a string in python?

I'm currently working on a chatbot from scratch as an assignment for my intro to python class. In my assignment I need to have at least one "mathematical component". I cant seem to find out how to have my input integer subtract from a string.
Attached is a screen shot, My goal is to have them input how many days a week they cook at home and have that subtract from 7 automatically.
print('Hello! What is your name? ')
my_name = input ()
print('Nice to meet you ' + my_name)
print('So, ' + my_name + ' What is your favorite veggie?')
favorite_veggie = input ()
print('Thats nuts! ' +favorite_veggie + ' is mine too!')
print('How many days a week do you have cook at home? ')
day = input ()
print('So what do you do the other ' + ????? 'days?')
You are looking for this
day = input()
required_days = 7 - int(day)
print('So what do you do the other ' + str(required_days) + ' days?')
day = int(input())
print('So what do you do the other', 7-day, 'days?')
You may convert the result of the input to int, then do the substraction. Also input("") accepts a string as parameter, that will be shown in front of the prompt area, that makes better code
my_name = input('Hello! What is your name? ')
print('Nice to meet you ' + my_name)
favorite_veggie = input('So, ' + my_name + ' What is your favorite veggie?')
print('Thats nuts! ' + favorite_veggie + ' is mine too!')
day = int(input('How many days a week do you have cook at home? '))
non_work_day = 7 - day
what_do = input('So what do you do the other ' + str(non_work_day) + 'days?')

How do I multiply from a input variable?

I am having trouble figuring out how to multiply my users input.
I have tried changing the functions of the variables for 'int' to 'float' and to 'str' but i cant seem to figure it out. My code:
pops = input("Enter your favorite pop: ")
cost = input("Enter how much they cost: ")
how_many = input("Enter how many pops you have: ")
print('My favorite pop is ' + pops + '!')
print('They cost about ' + cost + ' dollars.')
print('I have about ' + how_many + ' pops!')
result = str(cost) * str(how_many)
print("You have spent over " + result + " dollars on pops!")
I've got next error:
result = str(cost) * str(how_many)
TypeError: can't multiply sequence by non-int of type 'str'
First of all, I highly recommend you to start with some guides/tutorials or at least read official python docs to get in touch with language basics.
Regarding your problem. I'll show you basic algorithm how to use official docs to find solution.
Let's check docs of input() function.
The function then reads a line from input, converts it to a string, and returns that.
Strings in python are represented as str. So, after execution of input() variables pops, cost and how_many contains str values.
In your code you're using str() function. Let's check in docs what does this function perform:
Return a str version of object.
Now you understand that expressions str(cost) and str(how_many) convert str to str which means .. do nothing.
How to multiply values from input?
You need to multiply two values, which requires converting str to one of numeric types.
For cost we will use float, cause it can contain fractional number. For how_many we can use int cause count normally is integer. To convert str to numbers we will use float() and int() functions.
In your code you need just edit line where error occurred and replace useless call of str() with proper functions:
result = float(cost) * int(how_many)
Result of multiplication float and int will be float.
How to print result?
Code you're using will throw an error, cause you can't sum str and float. There're several ways how to print desired message:
Convert result to str.
It's the most obvious way - just use str() function:
print("You have spent over " + str(result) + " dollars on pops!")
Use features of print() function:
In docs written:
print( *objects, sep=' ', end='\n', file=sys.stdout, flush=False )
Print objects to the text stream file, separated by sep and followed by end.
As we see, default separator between objects is space, so we can just list start of string, result and ending in arguments of print() function:
print("You have spent over", result, "dollars on pops!")
String formatting.
It's very complex topic, you can read more information by following provided link, I'll just show you one of methods using str.format() function:
print("You have spent over {} dollars on pops!".format(result))
You are trying to multiply two strings.
You should multiply like this:
result = float(cost) * int(how_many)
But don't forget to reconvert the result to string in the last line or it will give you another error (TypeError in this case)
print("You have spent over " + str(result) + " dollars on pops!")
str(item) converts item to a string. Similarly, float(item) converts item to a float (if possible).
The code:
result = float(cost) * int(how_many)
will not produce the same error as you indicated occurred, but may introduce a ValueError, if the input given is not what you are expecting.
Example:
a = "b"
float(a)
Output
ValueError: could not convert string to float: 'b'
result = int(cost) * int(how_many) can fix the issue. Cost and how_many are non-numeric and converting them to int gives the desired output.
pops = input("Enter your favorite pop: ")
cost = input("Enter how much they cost: ")
how_many = input("Enter how many pops you have: ")
print('My favorite pop is ' + pops + '!')
print('They cost about ' + cost + ' dollars.')
print('I have about ' + how_many + ' pops!')
result = float(cost) * int(how_many)
print("You have spent over " + str(result) + " dollars on pops!")
The problem is that you are trying to convert the cost to a string, conversion from one type to another except when using the bool() is illegal. That is why the program is raising a TypeError.
pops = input("Enter your favorite pop: ")
cost = input("Enter how much they cost: ")
how_many = input("Enter how many pops you have: ")
print('My favorite pop is ' + pops + '!')
print('They cost about ' + cost + ' dollars.')
print('I have about ' + how_many + ' pops!')
result = cost * how_many
print("You have spent over " + result + " dollars on pops!"

Rounding a float that is an str and used in int

I'm trying to replicated a program I made on a Scratch-like application. My problem here is I'm trying to display the user with different numerical data (subtotal, tax and total cost), but when it shows the total cost it gives repeating or terminating decimals. I'd like it to be rounded to two decimals. I've tried adding the round() command inside the program but it's difficult because I'm trying to round a variable rather than an actual number. This is my code so far (line 25 and 28 I believe is where I'm suppose to add a round() or on a new line). I'm very new to Python, I'm using version 3.5.0. I also have searched on here, but the answers were too complex for me. In addition, I got this error: typeerror type str doesn't define __round__ method when adding the round() function in places I assume won't work. Thanks. (ignore after the last else: statement)
#This program asks for the size of pizza and how many toppings the customer would like and calculates the subtotal, tax and total cost of the pizza.
largePizza = 'large'
extraLargePizza = 'extra large'
print ('Answer the follwing question in all lowercase letters.')
print ('Would you like a large or an extra large pizza?')
sizeOfPizza = input()
if sizeOfPizza == largePizza:
print('Large pizza. Good choice!')
else:
print('Extra large pizza. Good choice!')
costOfLargePizza = str(6)
costOfExtraLargePizza = str(10)
oneTopping = 'one'
twoToppings = 'two'
threeToppings = 'three'
fourToppings = 'four'
print ('Answer the following question using words. (one, two, three, four)')
print ('How many toppings would you like on your pizza?')
numberOfToppings = input()
tax = '13%'
if numberOfToppings == oneTopping:
print('One topping, okay.')
if sizeOfPizza == largePizza:
subtotalCostOfLargePizza = str(int(costOfLargePizza) + 1)
**totalCostOfLargePizza = str(int(subtotalCostOfLargePizza) * 1.13)**
print('Your subtotal cost is ' + str(subtotalCostOfLargePizza))
print('Your tax is ' + str(tax))
**print('Your total cost is ' + str(totalCostOfLargePizza))**
else:
print('One topping, okay.')
subtotalCostOfExtraLargePizza = str(int(costOfExtraLargePizza) + 1)
totalCostOfExtraLargePizza = str(int(subtotalCostOfExtraLargePizza) * 1.13)
print('Your subtotal cost is ' + str(subtotalCostOfExtraLargePizza))
print('Your tax is ' + str(tax))
print('Your total cost is ' + str(totalCostOfExtraLargePizza))

Puzzled about why I can't add strings together

I am trying to write a program that gets user information and adds it to a list and then I want to total how many user inputs there were, but I can't do it. I have tried running an accumulator, but I get TypeError: unsupported operand type(s) for +: 'int' and 'str'.
def main():
#total = 0
cel_list = []
another_celeb = 'y'
while another_celeb == 'y' or another_celeb == 'Y':
celeb = input('Enter a favorite celebrity: ')
cel_list.append(celeb)
print('Would you like to add another celebrity?')
another_celeb = input('y = yes, done = no: ')
print()
print('These are the celebrities you added to the list:')
for celeb in cel_list:
print(celeb)
#total = total + celeb
#print('The number of celebrities you have added is:', total)
main()
Here is the output as desired without the accumulator, but I still need to add the input together. I have commented out the accumulator.
Enter a favorite celebrity: Brad Pitt
Would you like to add another celebrity?
y = yes, done = no: y
Enter a favorite celebrity: Jennifer Anniston
Would you like to add another celebrity?
y = yes, done = no: done
These are the celebrities you added to the list:
Brad Pitt
Jennifer Anniston
>>>
Thanks in advance for any suggestions.
Total is an integer ( declared earlier on as )
total = 0
As the error code suggest, you are trying to join an integer with a string. That is not allowed. To get pass this error, you may :
## convert total from int to str
output = str(total) + celeb
print(" the number of celebrities you have added is', output)
or even better you can try using string formatting
##output = str(total) + celeb
## using string formatting instead
print(" the number of celebrities you have added is %s %s', % (total, celeb))
I hope this will work for you
Python is a dynamically typed language. So, when you type total = 0, the variable total becomes an integer i.e Python assigns a type to a variable depending on the value it contains.
You can check the type of any variable in python using type(variable_name).
len(object) returns integer value.
for celeb in cel_list:
print(celeb)
#end of for loop
total = 0
total = total + len(cel_list) # int + int
print('The number of celebrities you have added is:', total)
You can get the number of entries in a Python list by using the len() function. So, just use the following:
print('These are the celebrities you added to the list:')
for celeb in cel_list:
print(celeb)
total = len(cel_list)
print('The number of celebrities you have added is: ' + str(total))
Note the decreased indentation of the last two lines - you only need to run them once, after you've finished printing out the celeb's names.

Categories

Resources