if statement, print additional column in python - python

i am new to pythin and trying to work out an if statement for some data being collected.
import grovepi
import time
import datetime
import grovelcd
#headerline
print ("Time,Noise (db),Light (lux),Temperature (C),Humidity (rH)")
here i have the already existing header lines for when they are printed into a csv file.I want another displaying the information i outline below.
while True:
timestamp=time.time()
#read from a analog sensor on input 1
d= grovepi.analogRead(1)
#read from an analog sensor on input 2
a= grovepi.analogRead(2)
#read from an digital sensor on input 3
(t,h)=grovepi.dht(3,0)
above is the reading of each sensor
print ("%f,%d,%d,%f,%f"%(timestamp,d,a,t,h))
What i would like is an additional value, i am having issues getting an if statement to take the value and determine if it matches what i want. All these should be number values.
the idea i have is
if t > 35:
print("Warning")
if h > 50:
print("Warning")
if n > 75:
print("Warning")
else:
print("OK")
Essentially what i have looks like this output:
Noise Light Temperature Humidity
85 500 34 76
What im trying to achieve is this:
Noise Light Temperature Humidity Note
85 500 34 76 OK
Any help appreciated, i dont know python very well unfortunately.

If you want to print an extra column, like "1234567890,34.3,51.2,70.3,Warning" then you can do it with a simple boolean variable, like this:
while True:
...
warning = t > 35 or h > 50 or n > 75
print ("%f,%d,%d,%f,%f,%s" % (
timestamp, d, a, t, h, "Warning" if warning else "OK"
))
Above, I've defined warning as a boolean condition, and used if for the inline if operator to print either "Warning" or "OK".
If you need extra flexibility you can assign to a string variable:
while True:
...
# Note, only message for the first matching condition would display
if t > 35:
message = "Warning: T"
elif h > 50:
message = "Warning: H"
elif n > 75:
message = "Warning: N"
else:
message = "OK"
print ("%f,%d,%d,%f,%f,%s" % (timestamp, d, a, t, h, message))
And if you need to display multiple messages, you can collect a list, like this:
while True:
...
warnings = []
if t > 35:
warnings.append("WarnT")
if h > 50:
warnings.append("WarnH")
...
status = " ".join(warnings) if warnings else "OK"
print ("%f,%d,%d,%f,%f,%s" % (timestamp, d, a, t, h, status))
This would collect all warnings in a list (so it would be like ["WarnT", "WarnH"]), then if the list is not empty join with spaces (" ".join(warnings)) so it'll be "WarnT WarnH", and otherwise use "OK" as the message. Tune the output as you feel appropriate.
Hope this helps.
(BTW, you may consider using something like %0.2f instead of %f if you want a fixed number of digits. I believe you'd probably want to round to a sane precision, e.g. "59.03" instead of something like "59.031045032")

Related

Python error while finding greatest number

I am trying techgig problem of finding greatest of 3 numbers. problem as follows
You just need to take three number as input from stdin and you need to
find greatest of them.
Input Format
You will be taking three numbers as an input from stdin one on each line respectively.
Constraints
-100000 <= N <= 100000
Output Format
You need to print the greatest of the three numbers to the stdout.
Sample TestCase 1
Input
902
100
666
I done this
''' Read input from STDIN. Print your output to STDOUT '''
#Use input() to read input from STDIN and use print to write your output to STDOUT
import sys
def main():
s=sys.stdin.read()
s=s.split("\n")
a=int(s[0])
b=int(s[1])
c=int(s[2])
temp=0
e=[a,b,c]
for i in e:
if i > temp:
temp=i
print(temp)
'''if (a>b) and (a>c):
temp = a
elif (b>a) and (b>c):
temp = b
else:
temp = c
print(temp)'''
main()
It has predefined input 902, 100, 666. My code shows 902 output and expected also shows 902, but its showing failed, Why? In above code commented or non commented thing both showing failed.
I might be wrong but the output says to print using the stdout: You need to print the greatest of the three numbers to the stdout. The print in python is the same as sys.stdout.write(str(99) + '\n'). Try using stdout to print the result.
sys.stdout.write(str(temp))
temp is being initialized as 0, but the input allows for negative numbers. 0 will considered larger than any negative input though. This means your algorithm will fail for test cases that have negative input.
Initialize temp to a value smaller than the minimum allowed input:
temp = -100001 # One less than the minimum
Actually they are looking for the output as mentioned and though the logic of your code is right but the output will give a new line which will be considered wrong. To fix this we use within print statement (end = "")
so the right code becomes
Hope it helps, keep coding.

Python - PseudoCode for functions and operands

I am quite new to the PseudoCode concept... I would like to get an idea of how functions and operands like modulus, floor division and the likes would be written in PseudoCode. Writing the PseudoCode for this code might actually help me understand better...
user_response=input("Input a number: ")
our_input=float(user_response)
def string (our_input):
if (our_input % 15) == 0 :
return ("fizzbuzz")
elif (our_input % 3) == 0 :
return ("fizz")
elif (our_input % 5) == 0 :
return ("buzz")
else :
return ("null")
print(string(our_input))
Your code really isn't that hard to understand assuming the knowledge of % as the modulus operation. Floor division can really just be written as a regular division. Floor the result, if really necessary.
If you don't know how to express them, then explicitly write modulus(x, y) or floor(z).
Pseudocode is meant to be readable, not complicated.
Pseudocode could even be just words, and not "code". The pseudo part of it comes from the logical expression of operations
The basic idea of PseudoCode is either to
a) Make complicated code understandable, or
b) Express an idea that you are going to code/haven't yet figured out how to code.
For example, if I am going to make a tool that needs to read information in from a database, parse it into fields, get just the info that the user requests, then format the information and print it to the screen, my first draft of the code would be simple PseudoCode as so:
# Header information
# Get user input
# Connect to Database
# Read in values from database
# Gather useful information
# Format information
# Print information
This gives me a basic structure for my program, that way I don't get lost as I'm making it. Also, if someone else is working with me, we can divvy up the work (He works on the code to connect to the database, and I work on the code to get the user input.)
As the program progresses, I would be replacing PseudoCode with real, working code.
# Header information
user_input_row = int(input("Which row (1-10)? "))
user_input_column = input("Which column (A, B, C)? "))
dbase = dbconn("My_Database")
row_of_interest = dbase.getrow(user_input_row)
# Gather useful information
# Format information
# Print information
At any point I might realize there are other things to do in the code, and if I don't want to stop what I'm working on, I add them in to remind myself to come back and code them later.
# Header information #Don't forget to import the database dbconn class
user_input_row = int(input("Which row (1-10)? "))
#Protect against non-integer inputs so that the program doesn't fail
user_input_column = input("Which column (A, B, C)? "))
#Make sure the user gives a valid column before connecting to the database
dbase = dbconn("My_Database")
#Verify that we have a connection to the database and that the database is populated
row_of_interest = dbase.getrow(user_input_row)
# Separate the row by columns -- use .split()
# >> User only wants user_input_column
# Gather useful information
# Format information
# >> Make the table look like this:
# C C1 C2 < User's choice
# _________|________|_______
# Title | Field | Group
# Print information
After you're done coding, the old PseudoCode can even serve to be good comments to your program so that another person will know right away what the different parts of your program are doing.
PseudoCode also works really well when asking a question when you don't know how to code something but you know what you want, for example if you had a question about how to make a certain kind of loop in your program:
my_list = [0,1,2,3,4,5]
for i in range(len(my_list)) but just when i is even:
print (my_list[i]) #How do I get it to print out when i is even?
The PseudoCode helps the reader know what you're trying to do and they can help you easier.
In your case, useful PseudoCode for things like explaining your way through code might look like:
user_response=input("Input a number: ") # Get a number from user as a string
our_input=float(user_response) # Change that string into a float
def string (our_input):
if (our_input % 15) == 0 : # If our input is divisible by 15
return ("fizzbuzz")
elif (our_input % 3) == 0 : # If our input is divisible by 3 but not 15
return ("fizz")
elif (our_input % 5) == 0 : # If our input is divisible by 5 but not 15
return ("buzz")
else : # If our input is not divisible by 3, 5 or 15
return ("null")
print(string(our_input)) # Print out response
THANKS GUYS FOR ALL OF YOUR INPUT, FROM ALL I READ, I CAME UP WITH THIS, IF THERE ARE ANY AREAS U THINK NEEDS TO BE ADJUSTED PLEASE LET ME KNOW.
THANKS AGAIN
THE FUNCTION USING PYTHON
user_response=input("Input a number: ")
our_input=float(user_response)
def string (our_input):
if (our_input % 15) == 0 :
return ("fizzbuzz")
elif (our_input % 3) == 0 :
return ("fizz")
elif (our_input % 5) == 0 :
return ("buzz")
print(string(our_input))
<<------------------------------->>
IT'S PSEUDOCODE
Request an input from the user
Ensure that the input is a number
If the input is divisible by 15
send "fizzbuzz" to the main
program
But if the input is divisible by 3 and not 15
send "fizz" to the main program
But if the input is divisible by 5 and not 15 or 3
send "buzz" to the main program
Display the result.

Python if statement with multiple clauses

The code im trying to create is to print a wavelength such as radio waves or microwaves based on the wavelength value input.
userInput = input("Enter wavelength (m) value: ")
waveValue= float(userInput)
if waveValue > 10**-1 :
print("Radio Waves")
elif waveValue < 10**-3 :
print("Microwaves")
elif waveValue < 7*10**-7 :
print("Infared")
elif waveValue <4-10**-7 :
print(" Visible light")
elif waveValue <10**-8 :
print( "Ultraviolet")
elif waveValue <10**-11 :
print( "X-rays")
elif waveValue >10**-11 :
print("Gamma rays")
else :
print()
Any hints on how I can get the second if statement to work. Every input I put in just outputs radio waves because my arguments does not work properly.
Also there is 5 more inputs that I will have to use elif commands for.
Are you trying to use powers of 10 here? Because the convention for "10 to the minus 1" for example, is 1.0e-1. What you have in your code translates to "10 times -1" or -10, which I don't think you intended.
I would rewrite as:
if waveValue > 1.0e-1:
print("Radio Waves")
elif (waveValue > 1.0e-3) and (waveValue < 1.0e-1):
print("Micro Waves")
as a prior answer pointed out, it is also more efficient to order the answers so that one side of the comparison is not needed (those values have already been accounted for by earlier tests).
for example:
if waveValue < 1.0e-3:
<not in current code>
elif waveValue < 1.0e-1:
print("Micro Waves")
else:
print("Radio Waves")
Nothing wrong with your approach for a small number of "break values". For a large number of "break values" you are better off to create a table with the break values and the corresponding action.
i.e., in your case, a table with wavelength and classification. First row containing 10e-1 and "Radio Waves", 2nd row containing 10e-3 and "Microwaves"
In code, you just loop though the until until you find the correct row for waveValue.
This is common in Tax Tables. As a bonus, you can store your tax tables in an external database instead of hard-coding the values in your program.
I think your second statement is wrong.
It says waveValue >10*-1<10*-3 which I think is >-10 and < -30 and if what I say is correct then there can't be numbers bigger than -10 that are smaller than -30
A list of tuples could work quite well here:
wave_categories = []
# Load up your data of definitions
wave_categories.append((1e-3, 'Microwaves'))
wave_categories.append((1e-2, 'Somewaves'))
wave_categories.append((1e-1, 'Radiowaves'))
wave_categories.append((1, 'Ultrawaves'))
Then your detection becomes a loop:
def find_wave(wavelength):
for category_wavelength, name in wave_categories:
if wavelength < category_wavelength:
return name
raise Exception('Wavelength {} not detected in list'.format(wavelength))
To make it work for lots and lots of categories, just add more data to wave_categories.
You can use the bisect module for this:
from bisect import bisect
freqs = [10**-11, 10**-8, 4*10**-7, 7*10**-7, 10**-3, 10**-1]
names = ['Gamma rays', 'X-rays', 'Ultraviolet', 'Visible light',
'Infared', 'Microwaves', 'Radio Waves']
>>> names[bisect(freqs, 10**-2)]
'Radio Waves'
>>> names[bisect(freqs, 10**-4)]
'Microwaves'

Is something wrong with My Python 3.3.2?

When using Python 3.3.2 shell
>>> temperature = 70
>>> if temperature > 60 and temperature < 75:
print ("Just right!!")
else:
SyntaxError: invalid syntax
>>>
what am I doing wrong?? This happen ever time after I type "else:" and press enter. Im stuck
You need to indent your code properly:
>>> temperature = 70
>>> if temperature > 60 and temperature < 75:
... print('Just right!')
... else:
... print('Oh no!')
...
Just right!
When you indent it properly the ... will automatically show up (so don't type those in).
Unlike most languages, in Python indentation is important. It is how the Python interpreter indentifies blocks of code. You might hear the phrase "whitespace is significant", it means the same thing. whitespace means things you type that don't print (like spaces, the tab character, etc).
So you should always line up the identifier of blocks of code (lines that end with :) at the left margin. It is not important how many spaces you indent the body of these blocks of code (in your example, the print function is in the body of the if statement). As long as there is one space, Python will work. However, the standard is to use 4 spaces; so better get into the habit putting four spaces whenever you want to indent code.
The else: statement needs to be at the same level of indentation as the if: statement that it refers to.
>>> temperature = 70
>>> if temperature > 60 and temperature < 75:
... print ("Just right!!")
... else:
... print ("Oh noes.")
...
Just right!!
This is correct behaviour - otherwise Python wouldn't know what an else: statement is referring to:
>>> if True:
... if False:
... print("Wha?")
... else:
... print("Yay.")
... else:
... print("Huh?")
...
Yay.
You don't even need "else" after your condition. You might need it if you want to print additional info if first condition is not met
temperature = 70
if temperature > 60 and temperature < 75:
print("Just right!!")
Like others have said, you don't need the else statement if you don't want to do anything with the else case.
But, if you want to have an else statement but doesn't want to do anything, you can put pass statement:
>>> temperature = 70
>>> if 60 < temperature < 75:
... print ("Just right!!")
... else:
... pass
...
Just right!!
>>>

String formatting %02d not performing as expected? What would cause the following code to not print truncated two-digit form?

No clue why this is happening. I must be missing something obvious.
I'm trying to make a counter print out something like SMPTE code (hours:minutes:seconds:frames (assuming 24fps)).
Code thus far:
import time
s_time = time.time()
def format_time():
t = time.time() - s_time
if t < 1:
print '00:00:00:%02d' % int(t/0.041666666666666664)
elif t < 60:
t = str(t).split('.')
print '00:00:%02d:%02d' % (int(t[0]), int(int(t[1][:4])/0.041666666666666664) )
while True:
format_time()
All seems well initially, until the duration surpasses 1 second and the elif branch is entered. Seconds print out fine, but the frames print out the full multi-digit result of the calculation. Given that the formatting operator is specifying %02d, just like it does in the first if branch (which behaves as expected), why is it not obeying in the second branch? I'm at a loss trying to figure out why it is still printing the full result rather than the truncated version.
You are trying to get the integer part and the fractional part of the float to print your result. It is a good practice to use operators and functions on numeric data directly instead of adding a heavy overhead by converting the float into str and back to number.
Use the math module modf function for that. It will also simplify your algorithm.
import time
import math
s_time = time.time()
def format_time():
t = time.time() - s_time
if t < 60:
f,i = math.modf(t)
print '00:00:%02d:%02d' % (i, f/0.041666666666666664)
while True:
format_time()
PS: for your code error, in your elif block, you are passing t as an integer with a huge value instead of passing the 0.xxxxx value of it. This error wouldn't occur if you keep using the math functions of floats.
I expect you want something like this:
hours = int(t)/3600
minutes = (int(t)/60)%60
seconds = int(t)%60
frames = (t-int(t))*24
print '%02d:%02d:%02d:%02d' % (hours, minutes, seconds, frames)
%02d means: print the integer and if it's shorter than 2 digits, prefix it with zeroes.
it doesn't limit the formatted string to two digits.
edit: one way of getting the first 2 (rounded) digits of a number n would be:
n = 13900
print round(n/10**math.floor(math.log10(n)-1))
or if you don't care about rounding, just cut the string...

Categories

Resources