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 6 years ago.
Improve this question
I am probably just tackling this the wrong way but at line 2 I am trying to subtract 2 user inputs within a print string.
BTW this is just for a nim sum game, where the user chooses the amount and goes first, then plays the computer.
def setup(startamt, userturn):
print(str("there are " + startamt - userturn + " balls left"))
def main():
startamt = input("How many balls do you want to start with?(15 or more) ")
userturn = input("How many balls will you take?(1-4) ")
setup(startamt, userturn)
The first problem is that input() returns a string (str) object, so to do a calculation you need to convert them to integers (int()) or floating point (float()) numbers.
Since you are on 3.6 then you can use Literal string interpolation. For example:
startamt = "52"
userturn = "9"
print(f"there are {str(int(startamt) - int(userturn))} balls left")
The preceding f indicates we are using interpolation, which is done inside the { }.
In your second line, the startamt - userturn are each being evaluated as strings.
You can either do:
print("there are " + int(startamt) - int(userturn) + " balls left"))
or using string formatting which is more Pythonic:
print("there are {} balls left".format(int(startamt) - int(userturn)))
This seems to work
def setup(startamt, userturn):
print("there are", str((int(startamt) - int(userturn))), "balls left"
def main():
startamt = input("How many balls do you want to start with?(15 or more) ")
userturn = input("How many balls will you take?(1-4) ")
setup(startamt, userturn)
main()
Related
This question already has answers here:
Why does multiplication repeats the number several times? [closed]
(7 answers)
Closed 1 year ago.
I’ve written a piece of code that instead of print the product, prints a number a certain number of times. Whats wrong with it?
twelve = 12
name = input("What is your name? \nAnswer: ")
print("Cool name!")
nums = input("\n\nHow much pocket money did you receive last month?\nAnswer: ")
total = nums * twelve
print("\n\nI think you get ", total + " pounds in pocket money per year! Nice!")
The reason is that your nums variable is a string, which is the default with all Python inputs. Try converting it to int:
nums = int(input(...))
Or float if you are inputting a floating point number.
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 5 years ago.
Improve this question
So, the part of this project I cannot get to work is the sum() function.
It works during:
a = [1, 2, 3, 4, 5]
b = sum(a)
print b
But in my program, I have a user created list and the sum() keeps getting an error. len() works, but I also need the sum to obtain an average.
namelist = []
agelist = []
while True:
name = raw_input("Enter a name or type Exit to end data entry: ")
namelist.append(name)
if name == "Exit": #creates an exit point from data entry
break
age = raw_input("How old is " + name + "? ")
agelist.append(age)
lenage = len(agelist)
sumage = sum(agelist) #here is the problem -<<
avgage = sumage / lenage
print avgage
How can I get the sumage to work?
Is it not working because I did not define how long the list is?
The variable age has type string, so you need to convert it to an integer:
agelist.append(int(age))
The reason for the error is that agelist is a list of strings (inputs from the user) and before you can "add" those inputs you need to convert them either to an integer number or (probably) to a floating number (depending on what kind of average you want: an integer or floating point in Python 2):
sumage = sum(map(int, agelist)) # OR, replace int with float
This question already has answers here:
Using python, How can I make a pyramid using for loops?
(3 answers)
Closed 6 years ago.
I have spent the last half hour playing around and I still don't know how to make it so a character is added each time it loops.
This picture can better explain it better of what I mean.
here's my code:
triangle_char = input("Enter a character: \n")
triangle_height = int(input("Enter triangle height: \n"))
for row in range(triangle_height):
print(triangle_char)
(My previous answer was not very well thought out, so edit:)
You just need to keep adding your triangle_char to a string. Start by declaring an empty string
string = ""
and then every iteration of the loop, add one character to it
string += triangle_char
For example:
triangle_char = input("Enter a character: \n")
triangle_height = int(input("Enter triangle height: \n"))
string = ""
for row in range(triangle_height):
string += triangle_char
print(string)
Will give you the result you are looking for
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 7 years ago.
Improve this question
I am really new to Python and programming (2 days to be exact). I was messing around in idle trying to come up with a more complicated process than just print "Hello world." I was wondering if any of you could tell me why it is marking my print and elif statements invalid. I am using Python 2.7.10, thanks!
A = raw_input("Do you live in the US or Canada?")
if A == " US" or "Canada":
print "Welcome!"
else:
print "We're sorry, but your country is currently not supported!"
B = int(raw_input("How much is your package?")
if B >= 25
print "Your shipping is $4.00"
elif B >= 50
print "Your shipping is $8.00"
else:
print "Congrats, your shipping is free!"
Probably the first thing you notice about python is that consistent indentation is not just a good idea, it is mandatory. Experienced programmers, whether they write Python or not, always do that anyway so it is no big deal. Use spaces (4 is the norm) and avoid tabs - change your editor to replace a tab with 4 spaces.
It is a bad idea to use float on money amounts because of rounding. Better to use a large type, like Decimal, or store the amount as an int in cents, then insert a decimal point when you display. For simplicity I have stuck with using float, but be warned.
You have a number of logic errors in your code, as well as issues with style. Programming style is not just about what looks nice, it is whether you can understand your code later, when you come back to it.
Style points:
Don't use UPPERCASE for variables. By convention UPPERCASE is reserved for constants
Use meaningful variable names, not A and B
Here is a corrected program, with comments. Please read the comments! :
# This is a comment, it is ignored by python
# This is used later on by sys.exit()
import sys
# Logically the user would enter "Yes" or "No" to this quesion,
# not US or Canada!
ans = raw_input("Do you live in the US or Canada? ") # Notice the space after ?
# Note how the condition has been expanded
if ans == "US" or ans == "Canada":
print "Welcome!"
else:
print "We're sorry, but your country is currently not supported!"
# Now what? Your program just carried on. This will stop it
sys.exit()
# I'm using a floating point number for simplicity
amount = float(raw_input("How much is your package? "))
# I changed this around, since 50 is also >= 25!
# However, this is strange. Usually the more you spend the LESS the shipping!
# You were missing the : after the condition
if amount >= 50:
print "Your shipping is $8.00"
amount += 8 # This adds 8 to the amount
elif amount >= 25:
print "Your shipping is $4.00"
amount += 4 # This adds 4 to the amount
else:
print "Congrats, your shipping is free!"
# print the amount showing 2 decimal places, rounding
print "Amount to pay: $%.2f" % (amount)
You have plenty more to do. Maybe cope with the user entering lower or mixed case letters for the country name - and ask yourself if the question is logical to the user.
Later you might want to have a list of valid countries, and use in to test if the user entered a valid country. Then expand it to use a dictionary, indicating currency symbols, shipping amounts, and currency conversion rates for each country.
Enjoy Python!
Fixed it for you :). Take a look to see what's different, and you will learn, young padawan:
A = raw_input("Do you live in the US or Canada?")
if A == "US" or A == "Canada":
print "Welcome!"
else:
print "We're sorry, but your country is currently not supported!"
B = float(raw_input("How much is your package?"))
if B >= 25:
print "Your shipping is $4.00"
elif B >= 50:
print "Your shipping is $8.00"
else:
print "Congrats, your shipping is free!"
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I am a newbie on python. I have just create a program taking a 2's complement binary number and convert it to decimal value. (The way of conversion is described at http://sandbox.mc.edu/~bennet/cs110/tc/tctod.html.)
I am aware that there are some certain rules on how to format your program and some "good habits" on how to design your program. Like how you put a header, comment, etc. And how you design the structure of it. I could not find a guide on Internet so I decide to ask here.
This is my first time making post on stackoverflow, so please bear with me if I make any mistakes. : )
Here is my code.
def secBiToDecimal(number):
""" This program takes a 2's complement binary number as input and returns its decimal value
"""
output = ""
" Check the sign of this number and calculate its value in according way."
if number[0]=='0':
output += "+"
temp = 0
for i in range(1,len(number)):
temp += (int(number[i]) * (2**(len(number)-i-1)))
output += str(temp)
print output
elif number[0]=='1':
output += "-"
carryout = 1
" flip the digits"
number = list(number)
for i in range(len(number)):
if number[i] == "1":
number[i]='0'
else:
number[i]='1'
" add 1 to number in binary sense "
for i in range(1,len(number)):
if carryout == 0 and number[len(number)-i]=='0':
break
elif carryout == 1 and number[len(number)-i]=='0':
number[len(number)-i]='1'
break
elif carryout == 0 and number[len(number)-i]=='1':
number[len(number)-i]='1'
break
elif carryout == 1 and number[len(number)-i]=='1':
number[len(number)-i]='0'
number = "".join(number)
temp = 0
for i in range(1,len(number)):
temp += int(number[i]) * (2**(len(number)-1-i))
output += str(temp)
print output
One of the most important things to consider with regard to code formatting, styling and conventions is the "house rules". If your "house" (i.e. work place, team, school, teacher, etc.) expects things done in a certain way, then that is the way you should do it.
Standards and conventions found on the internet can be used as source material for discussions on changing the house rules, or to develop your own personal standard for personal projects.
But do use some standard, and keep an offline copy of the documentation for that standard if you can, so that you can read your own code 6, 12, 24 months down the line ;).