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
Related
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.
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
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.
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.