Edit: Apparently I was using python 2. Switching to 3 fixed the issue and now I am getting the proper results without the parentheses/commas. Thanks for the replies - problem solved :D
Beginner at Python and coding in general. Struggling with my first project assignment, but I've gotten so close on my own.
My assignment is to create a code in python that counts the number of coins from a given value i.e. quarters, nickels, dimes, pennies.
My initial code looks like this:
coins=input('Enter amount of change: ')
print("Quarters", coins//25)
coins = coins%25
print("Dimes", coins//10)
coins = coins%10
print("Nickles", coins//5)
coins = coins%5
print('Pennies', coins//1)
Which prompts something like, "Enter amount of change: 86"
('Quarters', 3)
('Dimes', 1)
('Nickles', 0)
('Pennies', 1)
These are the correct values, but my instructor wants it to look like this:
Enter amount of change: 86
Quarters: 3
Dimes: 1
Nickles" 0
Pennies: 1
I can get the colon in there, but how can I remove the parentheses and commas? Thanks
You can use str.format() to produce the required output. For example for quarters:
print('Quarters: {}'.format(coins//25))
This will work in both versions of Python.
The simplest solution I've always used to print values in Python 2, which is the Python version you appear to be using, is the following:
coins=int(input('Enter amount of change: '))
print "Quarters: %i" % (coins//25)
coins = coins%25
print "Dimes: %i" % (coins//10)
coins = coins%10
print "Nickles: %i" % (coins//5)
coins = coins%5
print 'Pennies: %i' % (coins//1)
The % symbol, when used with strings, allows whatever value you want to be printed to be substituted in the string. To substitute multiple values, you separate them with commas. For example:
someInt = 1
someStr = 'print me!'
print "The values are %i and %s" % (someInt, someStr)
This code will substitute in someInt and someStr for %i (used for integers) and %s (used for strings), respectively.
However, the % symbol also functions as the modulus operator, so it does 2 different things when it is being used with strings and when it is being used among two numbers.
Please check :
coins=input('Enter amount of change: ')
print "Quarters:",coins//25
coins = coins%25
print "Dimes:",coins//10
coins = coins%10
print "Nickles:",coins//5
coins = coins%5
print "Pennies:",coins//1
To use the print() syntax on python2 add this to the top of your program:
from __future__ import print_function
otherwise python will interpret the argument to print as a tuple and you'll see ().
I am using Python 3 and the following lines exactly give what your instructor wants:
coins=float(input("Enter amount of change: "))
print("Quarters:", round(coins//25))
coins = coins%25
print("Dimes:", round(coins//10))
coins = coins%10
print("Nickels:", round(coins//5))
coins = coins%5
print("Pennies: %.0f" % coins)
It seems like you are using Python 2. I think you intended to use Python 3 given your use of input() and print() methods, but the code will work in Python 2 by changing print() methods to print keywords. Your code would look like the following in "proper"* Python 2:
coins = input('Enter amount of change: ')
print 'Quarters: ' + str(coins // 25)
coins = coins % 25
print 'Dimes: ' + str(coins // 10)
coins = coins % 10
print 'Nickles: ' + str(coins // 5)
coins = coins % 5
print 'Pennies: ' + str(coins)
Hope this helped!
Footnote: Using % is preferred over using string concatenation, but I still believe that it is easier to read for beginners this way.
Related
quizes = [["Andrew"], ["Amy"], ["Jared"], ["Bob"], ["Sarah"]]
for i in range(len(quizes)):
grade = eval(input("Enter", quizes[i][0],"grade:"))
quizes[i].append(grade)
print(quizes[i])
Hey guys so I been working on this for the past week and can't solve this. I am trying to get my program to ask "Enter [person1] grade: " and so on and append a second element to each sublist which will be their grade and then print the contents of the entire list. Any help is appreciated
The problem is input takes 1 string as a parameter, you are passing 3 instead. So:
quizes = [["Andrew"], ["Amy"], ["Jared"], ["Bob"], ["Sarah"]]
for l in quizes:
grade = eval(input(f"Enter {l[0]} grade:"))
l.append(grade)
print(l)
However, I respectfully don't understand the point of using eval here. Eval turns data into code. Using eval on user input creates a great security hole. In the above code, what if the user input quizes.clear()? The whole array will be emptied. What if he inputs something eviler?
Consider (assumes valid grades only contain numbers):
quizes = [["Andrew"], ["Amy"], ["Jared"], ["Bob"], ["Sarah"]]
for l in quizes:
while True:
try:
grade = float(input(f"Enter {l[0]} grade:"))
except ValueError:
print("Please input a number.")
else:
l.append(grade)
break
print(quizes)
The main problem is that input() accepts only one argument as the input prompt, unlike print which can take any number of arguments - you're giving 3 parameters to the input function - "Enter", quizes[i][0], and "grade:".
You can try concatenating them - like input("Enter "+str(quizes[i][0])+" grade:") (the str() conversion is not needed if you know that all the quizes[i][0] will be strings already),
or even use string formatting - "Enter {} grade".format(quizes[i][0]) or f"Enter {quizes[i][0]} grade:"
This should be enough, but there are 2 more changes you can make to your code if you like -
Iterate over the nested lists directly (for sub_list in quizes:)
Using int() or float() to convert a returned input string containing a number will also work in place of eval
For example
for quiz in quizes:
grade = eval(input("Enter {} grade:".format(quiz[0])))
quiz.append(grade)
print(quiz)
EDIT: Python docs on string formatting The f"..." syntax works only for Python 3.6+
You need to change:
grade = eval(input("Enter", quizes[i][0],"grade:"))
to
grade = eval(input("Enter " + quizes[i][0] + " grade:"))
input does not behave as print does. You can't use commas to join text in any other function (except for a very small number of custom functions and modules), and you should stay away from them at if that's confusing for you to only use them sometimes.
With that change, does your code work now? You didn't tell us why it wasn't working the way you expected.
Now that I'm looking at it, what did yours do wrong?
quizes = [["Andrew"], ["Amy"], ["Jared"], ["Bob"], ["Sarah"]]
for quiz in quizes:
grade = eval(input("Enter " + quiz[0] + " grade:"))
quiz.append(grade)
print(quiz)
print(quizes)
I want to make this code much more elegant, using loop for getting user input into a list and also making the list as a list of floats withot having to define each argument on the list as a float by itself when coming to use them or print them...
I am very new to python 3.x or python in general, this is the first code i have ever written so far so 'mercy me pardon!'
Name = "john"
Place = "Colorado"
print (("Hello %s What's up? \nare you coming to the party tonight in %s\n
if not at least try to make simple calculator:") % (Name, Place))
print ("you will input 2 numbers now and i will devide them for you:")
calc =list(range(2))
calc[0] = (input("number 1:"))
calc[1] = (input("number 2:"))
print (float(calc[0])/float(calc[1]))
Since you are saying you are new to Python, I'm going to suggest you experiment with a few methods yourself. This will be a nice learning experience. I'm not going to give you answers directly here, since that would defeat the purpose. I'm instead going to offer suggestions on where to get started.
Side note: it's great that you are using Python3. Python3.6 supports f-strings. This means you can replace the line with your print function as follows.
print(f"Hello {Name} What's up? "
"\nare you coming to the party tonight in {Place}"
"\n if not at least try to make simple calculator:")
Okay, you should look into the following in order:
for loops
List comprehension
Named Tuples
functions
ZeroDivisionError
Are you looking for something like this :
values=[float(i) for i in input().split()]
print(float(values[0])/float(values[1]))
output:
1 2
0.5
By using a function that does the input for you inside a list comprehension that constructs your 2 numbers:
def inputFloat(text):
inp = input(text) # input as text
try: # exception hadling for convert text to float
f = float(inp) # if someone inputs "Hallo" instead of a number float("Hallo") will
# throw an exception - this try: ... except: handles the exception
# by wrinting a message and calling inputFloat(text) again until a
# valid input was inputted which is then returned to the list comp
return f # we got a float, return it
except:
print("not a number!") # doofus maximus user ;) let him try again
return inputFloat(text) # recurse to get it again
The rest is from your code, changed is the list comp to handle the message and input-creation:
Name = "john"
Place = "Colorado"
print (("Hello %s What's up? \nare you coming to the party tonight in %s\n"+
" if not at least try to make simple calculator:") % (Name, Place))
print ("you will input 2 numbers now and i will devide them for you:")
# this list comprehension constructs a float list with a single message for ech input
calc = [inputFloat("number " + str(x+1)+":") for x in range(2)]
if (calc[1]): # 0 and empty list/sets/dicts/etc are considered False by default
print (float(calc[0])/float(calc[1]))
else:
print ("Unable to divide through 0")
Output:
"
Hello john What's up?
are you coming to the party tonight in Colorado
if not at least try to make simple calculator:
you will input 2 numbers now and i will devide them for you:
number 1:23456dsfg
not a number!
number 1:hrfgb
not a number!
number 1:3245
number 2:sfdhgsrth
not a number!
number 2:dfg
not a number!
number 2:5
649.0
"
Links:
try: ... except:
Lists & comprehensions
Below is a short doctor program that I am making and this is the start, unfortunately, it doesn't work. Here is the error I receive -
TypeError: input expected at most 1 arguments, got 4
least = 0
most = 100
while True:
try:
levelofpain = int(input("How much is it hurting on a scale of", (least), "to", (most)))
while llevelofpain < least or levelofpain > most:
print ("Please enter a number from", (least), "to", (most))
levelofpain = int(input("How much is it hurting on a scale of", (least), "to", (most)))
break
except ValueError:
print ("Please enter a number from", (least), "to", (most))
Thanks in advance!
p.s. using python 3.3
The error message is self-explanatory -- you are passing four arguments to input(...) where it is only accepting one.
The fix is to turn the argument into a single string.
levelofpain = int(input(
"How much is it hurting on a scale of {} to {}? ".format(least, most)))
For formatting strings, you probably want to use Python's .format() function. Take a look at this question: String Formatting in Python 3
There are two main methods for formatting strings in Python, the new way using the .format method of the str class, and the old C style method of using the % symbol:
str.format():
"This is a string with the numbers {} and {} and {0}".format(1, 2)
C Style Format (%):
"This is another string with %d %f %d" % (1, 1.5, 2)
I strongly recommend not using the C Style Format, instead use the modern function version. Another way I don't recommend is replacing the input function with your own definition:
old_input = input
def input(*args):
s = ''.join([str(a) for a in args])
return old_input(s)
input("This", "is", 1, 2, 3, "a test: ")
I have developed a piece of code for school and i have got to the end a run into a final problem, to finish the game i need to print off the end values of the results of the sums carried out and i am having problem including the variable names as inputted by the user, here is the code;
import random
print('Welcome to the game')
char1=input('What is the fist characters name: ')
char2=input('What is the second characters name: ')
char1st=int(input('What is the strength of '+char1))
char1sk=int(input('What is the skill of '+char1))
char2st=int(input('What is the strength of '+char2))
char2sk=int(input('What is the skill of '+char2))
strmod = abs (char2st - char1st) // 5
sklmod = abs (char2sk - char1sk) //5
char1rl=random.randint(1,6)
char2rl=random.randint(1,6)
if char1rl>char2rl:
char1nst=(char1st+strmod)
char1nsk=(char1sk+sklmod)
char2nsk=(char2sk-sklmod)
char2nst=(char2st-strmod)
elif char2rl>char1rl:
char2nst=(char2st+strmod)
char2nsk=(char2sk+sklmod)
char1nsk=(char1sk-sklmod)
char1nst=(char1st-strmod)
else:
print('both rolls where the same, no damage was given or taken')
if char1nst <= 0:
print(str(+char1+' has died'))
elif char2nst <=0:
print(str(+char2+' has died'))
else:
print(+char1( ' now has a strength value of '+char1nst' and a skill value of '+char1nsk'.'))
print(+char2( ' now has a strenght value of '+char2nst' and a skill value of '+char2nsk'.'))
I wrote the bit at the end in the hope that it would print the end values but i get a syntax error ?! and don't have clue why it is happening. Can someone please help me edit the last four lines so it will print in the format of:
Bob now has a strength value of 4 and a skill value of 7
I have used my method before but its not working this time so if someone could point out where i went wrong and how to amend this problem that would be great !!!!
You have concatenation operators (+) in places where you don't need them (at the beginning of print() and you don't have them in places where you do need them (after the variable in of '+char1nsk'.'). That's what's causing the syntax error.
You might consider string formatting instead of string concatenation:
print "%s now has a strength value of %d and a skill value of %d" % (char1, char1nst, char1nsk)
You are trying to use the + operator without anything to append:
print(str(+char2+' has died'))
You don't need the str nor the + operators there, just use multiple arguments to the print() function:
if char1nst <= 0:
print(char1, 'has died'))
elif char2nst <=0:
print(char2, 'has died'))
else:
print(char1, 'now has a strength value of', char1nst, 'and a skill value of', str(char1nsk) + '.'))
print(char2, 'now has a strength value of', char2nst, 'and a skill value of', str(char2nsk) + '.'))
Only in the last two lines do I use str() and + to avoid a space between the value an the . full stop.
You could, instead, use string formatting with the str.format() method to get a more readable string formatting option for those last 2 lines:
template = '{} now has a strength value of {} and a skill value of {}.'
print(template.format(char1, char1nst, char1nsk))
print(template.format(char2, char2nst, char2nsk))
Because the text is the same for both lines, you can re-use a template string here.
Try removing the + int the beginning of the print statements. Change it to this:
print char1 +' has died'
print char2 +' has died'
else:
print(char1 +' now has a strength value of '+char1nst+' and a skill value of '+char1nsk+'.')
print(char2 +' now has a strenght value of '+char2nst+' and a skill value of '+char2nsk+'.')
well since your using python3 why not use .format?
insert {} into your string where you want a value, then call the format() method on that string with the values you want in the correct order.
else:
temp = "{} now has a strength value of {} and a skill value of {}."
print(temp.format(char1, char1nst, char1nsk))
print(temp.format(char2, char2nst, char2nsk))
cleanest soluton if you ask me.
I was just wondering if anybody had any input on how to improve this code. My goal is for it to be as pythonic as possible since I'm trying to really learn python well. This program works fine, but if you see anything that you think could be done to improve (not major changes, just basic "Im new to python" stuff) this program please let me know.
#!/usr/bin/python
from decimal import *
print "Welcome to the checkout counter! How many items are you purchasing today?"
numOfItems = int(raw_input())
dictionary = {}
for counter in range(numOfItems):
print "Please enter the name of product", counter + 1
currentProduct = raw_input()
print "And how much does", currentProduct, "cost?"
currentPrice = float(raw_input())
dictionary.update({currentProduct:currentPrice})
print "Your order was:"
subtotal = 0
for key, value in dictionary.iteritems():
subtotal = subtotal + value
stringValue = str(value)
print key, "$" + stringValue
tax = subtotal * .09
total = subtotal + tax
total = Decimal(str(total)).quantize(Decimal('0.01'), rounding = ROUND_DOWN)
stringSubtotal = str(subtotal)
stringTotal = str(total)
print "Your subtotal comes to", "$" + stringSubtotal + ".", " With 9% sales tax, your total is $" + stringTotal + "."
print "Please enter cash amount:"
cash = Decimal(raw_input()).quantize(Decimal('0.01'))
change = cash - total
stringChange = str(change)
print "I owe you back", "$" + stringChange
print "Thank you for shopping with us!"
Call the product dictionary "products" or some similarly descriptive name, instead of just "dictionary"
Generally, if you are iterating over a range, use xrange instead of range for better performance (though it's a very minor nitpick in an app like this)
You can use subtotal = sum(dictionary.itervalues()) to quickly add up all the item prices, without having to use the loop.
You should definitely use Decimal throughout to avoid inaccuracies due to float.
You can use a formatting string like '%.2f' % value (old-style format) or '{:.2f}' .format(value) (new-style format) to print out values with two decimal places.
The tax value should be a constant, so it can be changed easily (it's used in two places, once for the calculation and once for the display).
Updating a dictionary, I would use dict[key] = value, rather than dict.update({key:value})
Instead of concatenating strings, try using format specification. This looks cleaner and saves you having to convert values to strings explicitly.
C-style: "Qty: %d, Price: %f" % (qty, price)
string.format: "Qty: {0}, Price {1}".format(qty, price)
1 to add key-value in a dict, you can use:
dictionary[currentProduct] = currentPrice
but, you don't need a dict in this case, because dict is orderless. You can use a list of tuple.
2 Why not use Decimal(raw_input()), then you can do all the calculation in decimal without using floats.
3 To print the result, you don't need convert values to str first, you can use str.format()