Can you create a global variable which you can check to decide how much you want to print ? By doing that you can control the amount of logging as you require.
if printLevel > 3:
print("Bobby hits a fly ball for an out")
Answer from Cobusve on Stack OverflowCan you create a global variable which you can check to decide how much you want to print ? By doing that you can control the amount of logging as you require.
if printLevel > 3:
print("Bobby hits a fly ball for an out")
Yes, you could put all the print statements into an if structure eg..
if printStuff:
print 'I dont like baseball'
print 'I love it!'
Then it is just a matter of setting printStuff to True if you want to print or False if you dont.
#This is a game where a user can skip playing if they guess a magic word from the star, it's a word they dont even no exist. I want to know how can I not print a value if this word is guessed.
name = input("What is your name? ")
welcome = print(f"Hi {name} I am thinking of a number between 1, 20!")
print(welcome)
#here I want to creat a magic word, where if placed in the name input some prints telling the user they guessed the magic word pop out. soo..
if name == "cheat word":
print("wow! you guessed the cheat word, and the secret number is (#NohelpNeeded)
# What I want help with, is when the cheat word is guessed, i don't want the print stored in value welcome to print out, so just the print saying ("wow! you...etc") gets printed. Thank you
Videos
I am writing a mini-program for basic payment calculation, and after the calculation the results are printed in the terminal. However, I get the following warnings from Ruff (the Python linter that I use):
src/pf_example/food_payment.py:39:5: T201 print found src/pf_example/food_payment.py:51:5: T201 print found src/pf_example/food_payment.py:52:5: T201 print found src/pf_example/food_payment.py:54:5: T201 print found src/pf_example/food_payment.py:56:9: T201 print found
I know that I can turn off this check in the settings, BUT I don't why print is bad in the code. What would be the alternatives if not using print?
Not is very similar to the if condition !=. If a value is truthy, then it returns false. If a value is falsy, it returns true. Since most strings are truthy, it returns false, and since a None value is falsy, it returns true
so for example print(not(True)) would return false and print(not(False)) would return true
In Python, empty sequences such as (), [], '' and {} all evaluate to False, as well as the interger 0. You can check this by using the bool() function on any of these values.
In your first print, the not operator returns the boolean value that is the opposite of the boolean value of ("0"), which isn't an empty sequence nor 0. In other words, if you call bool(("0")), you will get True in return, and not True returns False.
In your second print, it's exactly the opposite happening. bool(()) is False, therefore not () should be True.
BTW: In your first print example, the value ("0") is not a tuple, but a string. I mention this just in case you were thinking otherwise.
Your program does not output anything because you are never calling your function.
This will do what you expect:
def GetNum():
x = int(input("Input something: "))
while (x > 0):
x = int(input("Input something: "))
print(x)
GetNum()
I removed the function argument Text, added a call to the GetNum function and added type conversions from str to int for both input() calls.
You haven't called your GetNum function.
You need to add the following to the bottom of your script:
GetNum(None)
Text is not used, so None is a null object.
You may want to read up on defining functions, function arguments and calling functions, which is out-of-scope for StackOverflow - See http://www.tutorialspoint.com/python/python_functions.htm
As the title suggests, for some reason my code is printing the contents of a file on the terminal, despite there being no print statement (i searched through all the code and commented all the prints out)
file = open (filename,"r")
file = file.read()
could that be the culprit?
def bla(value, rep):
try:
print value*rep
except TypeError:
print "sorry '%s' is not a valid parameter" % rep
see "Ask forgiveness not permission" - explain
def bla(value, rep):
if isinstance(value, int ):
print(value*rep)
else:
print("sorry '" + rep "' is not a valid parameter")
Use with
Based on @FakeRainBrigand solution I'm suggesting a safer solution:
import os, sys
class HiddenPrints:
def __enter__(self):
self._original_stdout = sys.stdout
sys.stdout = open(os.devnull, 'w')
def __exit__(self, exc_type, exc_val, exc_tb):
sys.stdout.close()
sys.stdout = self._original_stdout
Then you can use it like this:
with HiddenPrints():
print("This will not be printed")
print("This will be printed as before")
This is much safer because you can not forget to re-enable stdout, which is especially critical when handling exceptions.
Bad practice: Without with
The following example uses enable/disable prints functions that were suggested in previous answer.
Imagine that there is a code that may raise an exception. We had to use finally statement in order to enable prints in any case.
try:
disable_prints()
something_throwing()
enable_prints() # This will not help in case of exception
except ValueError as err:
handle_error(err)
finally:
enable_prints() # That's where it needs to go.
If you forgot the finally clause, none of your print calls would print anything anymore.
It is safer to use the with statement, which makes sure that prints will be reenabled.
Note: It is not safe to use sys.stdout = None, because someone could call methods like sys.stdout.write()
Python lets you overwrite standard output (stdout) with any file object. This should work cross platform and write to the null device.
import sys, os
# Disable
def blockPrint():
sys.stdout = open(os.devnull, 'w')
# Restore
def enablePrint():
sys.stdout = sys.__stdout__
print 'This will print'
blockPrint()
print "This won't"
enablePrint()
print "This will too"
If you don't want that one function to print, call blockPrint() before it, and enablePrint() when you want it to continue. If you want to disable all printing, start blocking at the top of the file.
I would assume it's due to buffering. Try adding flush=True as one of the optional parameter to print.
When using print, a newline character is added to your string unless you're overriding it (as you do) with the end parameter. For performance reasons, there exists an I/O buffer that only prints when it encounters a newline or the buffer fills up. Since your string doesn't contain a newline character anymore, you have to manually flush the buffer (i.e. send it to be printed).
from time import sleep
hash = '#'
while True:
print('\r' + hash, end='', flush=True)
hash = hash + '#'
sleep(1)
So I am currently trying to learn some python by using online resources. I am currently going through the ThinkPython2 book and got to a part in chapter 3 that goes over defining your own function. Currently when I run the code the function will print out correctly but will add a random "None" after it is done printing the lines.
def print_lyrics():
print("Somebody once told me")
print("The world is gonna roll me")
print(print_lyrics())
<file directory on this line> Somebody once told me The world was gonna roll me None Process finished with exit code 0
Any help?