Print Statement using two data types - python

print("this is your "+t+" warning")
t is supposed to be an integer.
this is probably a silly and stupid question but is it possible to print a variable(in the case t with an int value) and a string("this is your" & "warning") together in one print statement[print()].
If I remember it correctly it's possible in java, not sure though.

You can use string formatting to pass your print statement as one string.
print(f"this is your {t} warning")
In case if you would like to get familiar with string formatting: https://realpython.com/python-f-strings/

yes it is. you can pass multiple values to the print function and each gets printed
print("test", 2, ['something'])

in python, + with string types will work as concatenation. If you use different data types, it will give you TypeError can only concatenate str (not "int") to str.
So you need to use , to concatenate different types:
t= 10
print("this is your",t,"Test")

t = 0
print("this is your", t, "warning")
print(f"this is your {t} warning")
print("this is your " + str(t) + " warning")
print("this is your %d warning" % t)
print("this is your %s warning" % str(t))
# to decide how many numbers after the dot change x in this '%.xf' to the number of numbers after the dot
print("this is your %.3f warning" % float(t))

name="John"
band="Sykler"
print("The band for", name, "is", band, "out of 10")

Related

using loops for input list by user

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

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.

Creating error messages on a calculator in python

So I need to make a calculator that converts strings into floats then calculate.
The problem is I need to make error messages whenever:
the user enters a string that does not contain operands and/or an operator.
the user does not enter anything (the user simply pressed the Enter key).
the user only enters an operand.
the user only enters an operator.
the user enters two operands.
the user enters an operand and an operator.
the user is trying to divide a number by 0.
the user did not put a space in between the operands and the operator.
This is how the code looks like without error messages
# Interface
print ("Equation Calculator")
print (" ")
print ("My Equation Calculator is able to")
print (" Add: +")
print (" Subtract: -")
print (" Multiply: *")
print (" Divide: /")
print (" ")
print ("The equation you enter must follow this syntax:")
print (" <openrand><speace><operator><space><operand>.")
print ("An <operand> is any float number.")
print ("An <operator> is any is any of the operators mentioned above.")
print ("A <space> is an empty space.")
# Enter the equation
equation = input ("Enter your equation: ")
# Split the equation into Operand 1,2 and Operator
operand1,operator,operand2 = equation.split(" ")
# Show the user the equation
print ("Here is the equation you have entered: " + equation)
# Addition, Converting strings (operand 1 and 2) into float
if (operator == "+"):
answer = float(operand1) + float(operand2)
# Subtraction, Converting strings (operand 1 and 2) into float
if (operator == "-"):
answer = float(operand1) - float(operand2)
# Multiplication, Converting strings (operand 1 and 2) into float
if (operator == "*"):
answer = float(operand1) * float(operand2)
# DIvision, Converting strings (operand 1 and 2) into float
if (operator == "/"):
answer = float(operand1) / float(operand2)
# Display the answer
print ("The answer is: ",answer )
So for 7 and 8th errors I did this
# Error for not having a space
if (equation.find(" ") == False):
print ("Error #1: Please check if there is a space in between the two operands and the operator.")
# Error for dividing by 0
if (operand2 == "0"):
print ("Error #7: You cannot divide by 0.")
However python just bypasses this and still crashes.
What is the problem with above code?
How can I make it so the code prints error messages in above 8 situations?
Also I cannot use the built-in functions eval( ) or exec(), break or continue or pass or sys.exit( ).
I am very new to programming in general.
Please help and thank you.
If you have some set requirements on the incoming data, it is usually a good idea to check beforehand, if the data match this requirements.
So I would test if the string given matches your requirements:
The general structure could be tested with regular expressions:
I assume only integers are used, if not you need to replace the \ds with floating pointg matching, which should be googleable.
\d+ [+\/\-*] \d+
This regex matches any digit, followed by a space,followed by one of the operator +/*- and a digit.
Please not that would cause a very generic error message - like "your input does not look like the required input", so you might be better of to test the parts separately, to give a better user experience.
Use a structure like this:
if bad_condition:
print "error"
else:
# do whatever
You can try this:
try:
assert condition, "Error Message"
except AssertionError, e:
raise Exception(e.args)
for example:
# Error for not having a space
try:
assert (equation.find(" ")), "Error #1: Please check if there is a space in between the two operands and the operator."
except AssertionError, e:
raise Exception(e.args)

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

Doctor program - python

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: ")

Categories

Resources