Issue with including variables in print function - python

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.

Related

My function is too long. In order to pass class I need < 18 lines

So I am a total beginner yet this is 100% my code and I am proud of it. Now mind you I need a little cleaning up, however it does what I want it too. My issue is this: In order to turn this in for credit, one of the things is that procedures(functions) should not contain more than 18 lines. My function gameCont() has many more. Would anyone have suggestions on how I could shorten it up? Additionally I am obviously challenged when it comes to function parameters so any help is appreciated. Please be gentle as I am BRAND NEW! :)
game1 = "When dealing with SCUBA diving there are many dangers to consider. The very first one is _1_. \
I mean if you take water into your lungs, you are NOT SCUBA diving. Another is rising to the surface too quickly which could \
result in the _2_. Now this is a funny name, as I am sure when it happens, you dont feel 'bendy'. Let's also consider Nitrogen Narcosis.\
If you dont know what that is, well when you are very deep and your body is absorbing more nitrogen than it is used to, you can get \
feeling kinda _3_ feeling as though you just drank not one, but _4_ martinis"
game1_answers = ["drowning", "bends", "drunk", "2"]
game2 = "When you first learn to dive you are taught to do dives within a no DECOmpression limit(NDL). \n This means you do not want to \
stay that deep too long or you will rack up _1_. \n If you DO stay longer than what the NDL allows, you will have an obligation to \
take your time getting to the surface allowing that _2_ gas to leave your body. If you were taking IN gas you may call it \
in-gassing, but when you are decompressing, it may be called _3_-gassing. You are taught also, how to read _4_"
game2_answers = ["deco", "nitrogen", "off", "tables"]
game3 = "Equipment used by cold water divers such as myself are as such. On my head I would wear a _1_. To help regulate the breathing\
pressure from my SCUBA tank I would use a _2_. To help me propel through the water I would place_3_ on my feet. Considering \
we cannot see underwater I need to be wearing a _4_ on my face. Diving in the tropic, many people would use wetsuits, however it's\
very cold where I dive so we wear _5_ suits."
game3_answers = ["hood", "regulator", "fins", "mask", "dry"]
def howManyTries():
gameTries = raw_input("Thanks for giving my quiz a try, how many attempts do you want? ")
return int(gameTries)
def game_choice(): #this function is used to determin which difficulty the user wants and returns the proper game and answer list
user_input = raw_input("Greetings. This is my Udacity project for fill in the blanks. Which one of my options would you like?\
easy, hard, or hardest? Please take note of capitalization ")# this will define the user_input variable to raw input placed in by user
print ("\n" * 20)# just something to clean up the screen
print "Decided to choose " + user_input + '?' " Well " + user_input + " it is"# this confirms to the user which difficulty they chose.
print ""
print ""
if user_input == "easy": #easy returns game1 and game1 answers
return game1, game1_answers
elif user_input == "hard": # hard returns game2 and game2 answers
return game2, game2_answers
elif user_input == "hardest": #hardest returns game3 and game 3 answers
return game3, game3_answers
else:
print "It seems that " + user_input + " is not a valid response" #in case the user doesnt choose or spell choice correctly
def gameCont():
blanks = 1 #this assings blank to 1 which will tell the user which blank they are guessing in below prompt
attempts = howManyTries() #this calls the howManyTries function for a user choice integer
quiz, answers = game_choice() #this returns 2 values (game# and game# answers)
while attempts > 0: #while attempts (called from function) is greater than 0 we will loop this
print quiz #prints the chosen quiz for user updated each time the loop runs with correct answer
print("\n" * 10) #clears some more screen to loook better for the user
guess = raw_input("Reading the above paragraph, What would your guess be for _" + str(blanks) + "_") #asks for guess for current blank which always starts at 1
print("\n" * 10) #clears some more screen to loook better for the user
if guess == answers[blanks - 1]: #because indexing count starts at zero, and blanks start at 1 this will check if answer is equal to blanks - 1
print "As you can see your correct choice has replaced the variable, great job!!"#this will print if the guess is correct
quiz = quiz.replace("_" + str(blanks) +"_", answers[blanks - 1]) # here is the line of code that replaces the blank with the correct guess
blanks += 1 # this adds 1 to the blank which will prompt the user to move to the NEXT blank when loop begins again
if blanks > len(answers):
print ("\n" * 10)
print "YOU DID IT!! Here is the final paragraph with all the correct answers"
print ("\n" * 2)
print quiz
break
elif guess != answers[blanks -1]: #if the answer does not match the list index
attempts = attempts - 1 #then we will subtract 1 from the attempts
print ("\n" * 10)
print "Oops that is not correct, there should be hints in the paragraph" # lets user know they were wrong
print "You have " + str(attempts) + " attempts left." # lets the user know how many attempts they have left
print ""
if attempts < 1:
print "Well it looks like you are out of choices, Try again?"
break
print "Thanks for playing"
gameCont()
All of the printing that you're doing could be done in a separate function
def game_print(newlines_before, text, newlines_after)
print ("\n" * newlines_before + text + "\n" * newlines_after)
Two suggestions:
Delegate tasks that are accomplished by your function to smaller functions. So, for example, if you had a function that needed perform task A and performing that task could be divided into tasks B, C, and D, then create helper functions and call them inside of the function that does task A.
You have long strings, maybe store them somewhere else? Create a class just for constant strings of related functions and access that when you need a particular string. It'll make it less likely that you'll make a mistake when you need to use that string in multiple locations.
class Constants:
str1 = "..."
str2 = "..."
print(Constants.str1)
you can call a function from inside another function. inside an if statement you could call a small new function that just prints some stuff. this should make it easy to get the function size down.
something like this should work:
def correct(quiz, blanks):
print "As you can see your correct choice has replaced the variable, great job!!"
quiz = quiz.replace("_" + str(blanks) +"_", answers[blanks - 1]) # here is the line of code that replaces the blank with the correct guess
blanks += 1 # this adds 1 to the blank which will prompt the user to move to the NEXT blank when loop begins again
if blanks > len(answers):
print ("\n" * 10)
print "YOU DID IT!! Here is the final paragraph with all the correct answers"
print ("\n" * 2)
print quiz`
remember that you still want to break after calling that function in order to exit your loop.

How to remove parentheses and comma from printed output

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.

Python 3, Variables in loops

I'm new to python, and just playing around, getting to learn different features with this code.(Please read note)
less = ["science", "maths"]
for i in range(0,len(less)):
a = ("You have got; " + (less[i]))
b = (a)
#By putting in print here I figured out that it added science first then maths overrides it.
print(b)
print (b)
At the moment when you print the string at the moment it says:
"You have got; maths"
But i was trying to get it to say:
"You have got; science maths"
Basically, i'm trying to find a way to just add to the variable and not one override the other so when i print it at the end it will have both science and maths.
I am going to expand upon it which is why i need to have the length of the list is the loop and etc.
You can iterate simply over objects in the list and make print statement not terminate the line.
less = ["science", "maths"]
print ("You have got; ", end="")
for i in less:
print (i, end=" ")
less = ["science", "maths"]
print ('You have got; {}'.format(' '.join(less)))
To achieve this, use join:
>>> less = ["science", "maths"]
>>> print("You have got; %s" % ' '.join(less))
You have got; science maths
Explanation: join joins the elements in the list as a single string which you may add at the end of your required string

Dictionary value is not changed inside a for loop assignment

So I am learning python using Learn python the hard way. I am trying to develop a inventory system. The goal is to build this into a class that will be pulled by the room class. I am going to use a dictionary for the inventory so that when I create the inventory for each room I can say where they are in the room.
So in the bedroom I can say that there is a knife on the bed rather than just saying you see knife, candle, oil.
Right now I am working on picking up the item when someone says take knife. I am able to do a weird search and set that value to None so that when someone looks in the room it does not show up but I seem to be running into a scope issue. I read multiple other questions on this site that said since its a mutable object i don't need to do Global dict and when i tried that it got an error. I am able to edit the object but when i go back out of my if statement and for loop it won't carry over.
Please help me :)
#This is the inventory in this room
inventory = {'desk': 'Miniature Fusion Warhead',
'bed':'knife', 'sink':None}
def take(item):
if item in inventory.itervalues():
#add_item_to_inventory(item)
for key, value in inventory.iteritems():
if value == item:
print ("Wow.\n"
"Look at you.\n"
"Picking shit up and everything.")
value = None
else:
print ("What do you think this is?"
" The dollar store? We don't "
"got that shit here!")
# Prints out what items are in the room.
# I am hoping to later come up with an idea for how
# To make different variations of this, and have it randomly
# pick between the different ways it says what it sees.
for key, value in inventory.iteritems():
if value != None:
print "You see a %s on the %s." % (value, key)
print "What do you want to pick up?"
ui = raw_input(">")
split_ui = ui.split()
print split_ui
if len(split_ui) > 1:
if split_ui[0] == "take":
print ("You reach over to grab the %s."
"\n...") % split_ui[1]
take(split_ui[1])
else:
print ("What you talking bout Willis? "
"Don't you know this is just about "
"takin shit.")
else:
print ("Who taught you how to talk?"
"\n...\nLet me show you how its done.\n"
"Use a verb, like take, then throw in an "
"object like knife.")
print inventory
This is the output that I am given.
You see a knife on the bed.
You see a Miniature Fusion Warhead on the desk.
What do you want to pick up?
>take knife
['take', 'knife']
You reach over to grab the knife.
...
Wow.
Look at you.
Picking shit up and everything.
{'sink': None, 'bed': 'knife', 'desk': 'Miniature Fusion Warhead'}
Important note: This currently only works if you take the knife and not the Warhead. I need to figure out another solution for items with multiple words.
Thanks!
The value inside your loop is different than the real value of the dictionary.
It is just a reference to that value, so when you do value = None you actually change
the value of the reference to hold the new value None and not the value of the dictionary.
To demonstrate it better this is before the assignment inside the for key, value in inventory.iteritems():
------- -------------------------
|value| -------> |value of the dictionary|
------- -------------------------
this is after value = None
-------------------------
|value of the dictionary|
-------------------------
------- ------
|value| -------> |None|
------- ------
As you can see the dictionary value does not change. Only the variable value of the for loop
changes. This variable belongs to the scope of the for loop and after that it is discarded.
An alternative would be instead of value = None to do:
inventory[key] = None
zbs is correct, you're only changing the value of the pointer to the dict value. However, you're making this way too hard:
#This is the inventory in this room
inventory = {'Miniature Fusion Warhead': 'desk',
'knife':'bed'}
player_inventory = set()
def take(item):
if item in inventory:
print("You picked up the {}".format(item))
player_inventory.add(item)
del inventory[item]
else:
print("That item doesn't exist")
while True:
print('')
print("Inventory: " + ', '.join(player_inventory))
for k,v in inventory.items():
print("You see a {} on the {}".format(k, v))
print("What do you want to pick up?")
ui = raw_input("> ").split()
verb = ui[0]
item = ' '.join(ui[1:])
if verb == 'take':
if item:
print("You take the {}".format(item))
take(item)
else:
print("That item doesn't exist")
else:
print("That's not an action")

Python, first time using Decimal and quantize

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()

Categories

Resources