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'
Related
I'm trying to create a "football" game on python and if the user wants to pass the ball, my code is supposed to have a 50% probability of having an incomplete pass or a completion yielding between 3 and 15 yards
I know that to print the yardage, the code would look something like
import random
input("Enter r to run and p to pass")
p = print(random.randint(3,15))
but I'm not sure how to make "Incomplete" show up as a 50% probabilty
You can use the code below. As you have defined a statement to pick a random number between 3-15, you can create another statement to pick 0 or 1 (not %50 guaranteed). Also in your code, you are assigning return value of the print function to a parameter. This is definitely wrong! Print function returns nothing so assigning it to another variable is meaningless.
x = random.randint(0,1)
if x == 1:
random.randint(3,15)
else:
# incomplete pass
You could use something like this.
import random
inp = input("Enter r to run and p to pass")
if(inp == "p"):
print(random.choice([random.randint(3,15),0]))
elif(inp == "r"):
print("ran successfully")
This: random.choice([random.randint(3,15),0]) is the important bit. random.choice takes multiple values (in this case 2) in a list, and picks one randomly (2 values => 50% probability).
I also fixed the input output thing. To get input from the user you assign the value of input to a variable like this: example = input("Your input here: "). If you ran that line of code, and answered with potato for instance, you'd be able to print example and get potato (or whatever the user answered) back.
If you'd like to really flesh your game out, I'd suggest looking into template strings. Those let you do wonderful things like this:
import random
inp = input("Enter r to run and p to pass")
if(inp == "p"):
print(random.choice([f"Successfully passed the ball {random.randint(3,15)} yards","You tripped, the ball wasn't passed."]))
elif(inp == "r"):
print("Ran successfully.")
I'm very new to Python and programming in general, so excuse me if the code is terrible and the problem rather easy to solve.
I have written code to allow a user to have employee data printed based on 3 different inputs, which they are allowed to choose from.
The options the user has available to them are to pick employees based on their payroll number; a minimum and maximum salary range; their job title.
I made two functions for the formatting. The first one turns the lines of the text file into lists, then the second function grabs those individual lists and formats them.
Then the code requests the user to input the file name. If the file cannot be found, they get to try again. If it is correct, the file is loaded and then runs through the functions to print out a neat table.
Then the user is asked what method they want to choose from to select specific employees. They are given 4 options, 3 are mentioned at the start and the fourth is to just end the program.
I managed to successfully get the first option to print out the employees without hassle, as is the same for the fourth option to end the program. I almost have the third one completed, I just need to find a way to print the name without a comma. My problem resides within the second option: how do I print the employees and their details if they fall between the minimum and maximum salary ranges entered by the user if the range isn't an integer since it has to include a '£' sign?
Here's the code. It's the biggest chunk in the program because I just have no clue how to make it work properly -
def detailsPrint(field) : #takes tuple and prints
print("{:30}" "{:6}" "{:15}" "{:7}".format(field[3] + ", " + field[4], field[0], field[2], "£" + field[1]))
if display == 2 :
maxSalary = "£1000000"
minpay = input("Enter the minimum pay : ")
maxpay = input("Enter the maximum pay : ")
if len(minpay) and len(maxpay) < maxSalary :
for s in employeeList :
if s[1] >= minpay :
detailsPrint(s)
The outcome should be something like (example) Simpson, Bart 12345 Consultant £55000 if the minpay were to be £50000 and maxpay £60000
edit: Managed to get it working. Here's the code
if display == 2 :
x = False
maxSalary = 1000000
minpay = int(input("Enter the minimum pay: "))
maxpay = int(input("Enter the maximum pay: "))
if int(minpay) > int(maxSalary) or int(maxpay) > int(maxSalary) :
x = False
print("No employees earn over £1000000. Try again.")
if int(minpay) or int(maxpay) < int(maxSalary) :
for s in employeeList :
if int(s[1]) >= minpay and int(s[1]) <= maxpay :
detailsPrint(s)
x = True
if x == False :
print("No employees could be found within that range. Try again")
print("\n")
Simplest solution: don't ask for the £ char ;-)
A solution that work with your requirement is to change the line
if len(minpay) or len(maxpay) > maxSalary :
with something like
if int(minpay[1:]) > int(maxSalary[1:]) or int(maxpay[1:]) > int(maxSalary[1:]) :
which check the numeric value of the strings (your condition seems wrong anyway to me)
You could replace all "£" signs to "" in a string.
YourString.replace("£", "")
The objective is to write a program that will increase the population every 7 and 35 seconds and decrease every 13 seconds. I am trying to use a loop for this program and I am having some problems with getting the right casting for each variable. Here's the code:
#(1)There is a birth every 7 seconds (2)There is a death every 13 seconds (3)There is a new
immigrant every 35 seconds.
#CURRENT POP: 307,357,870
populationCurrent = input("What is the current population")
x=0
while x!=100:
if (x%7==0):
populationCurrent=populationCurrent+1
x=x+1
elif (x%13==0):
populationCurrent=populationCurrent-1
x=x+1
elif (x%35==0):
populationCurrent+=1
x=x+1
else:
x=x+1
print("The population will be "+int(populationCurrent)+".")
Thank you for your time.
I think you are confused in python2 and python3, there's a difference in input() function of python 2.x and python 3.x, where input() function gives an integer value in python 2 and str in python 3
input() is str by default so, this should be converted to int
populationCurrent = str(input("What is the current population"))
You cannot concatenate string and int
print("The population will be "+str(populationCurrent)+".")
Its easier to do this than iterate through 100 times
populationCurrent += 100//7 + 100//35 - 100//13
You need to convert populationCurrent to an integer immediately after you read the string.
populationCurrent = int(input("What is the current population"))
Note that if you don't enter a string that is a valid integer representation, this will raise a ValueError. You might want to consider how to handle that (catch it and use a default value? catch it and try to read another value? Let the exception propagate?)
With this change, you'll have to convert the integer value back to a string for the output:
print("The population will be "+str(populationCurrent)+".")
or using any of the various string formatting tools available. It's better to have populationCurrent as an integer, since there are more places in your code that assume it to be an integer than assume it to be a string.
The only thing you need to do is convert populationCurrent from string to int:
populationCurrent = int(input("What is the current population?"))
The more concerning stuff is that your code doesn't do what it's supposed to: when x is 35 you will only have one birth, since 35 % 7 is 0, but no immigrant will arrive. Do something like this, removing the elif statements which do not make the code that more efficient anyway:
while x!=100:
if (x%7==0):
populationCurrent=populationCurrent+1
if (x%13==0):
populationCurrent=populationCurrent-1
if (x%35==0):
populationCurrent+=1
x=x+1
print("The population will be ", populationCurrent, ".")
Though still note that the loop will stop after x gets to 100. You could reset it but I don't know for how long you want it to run.
def intInput(prompt):
while 1:
try: return int(input(prompt))
except ValueError: print("Invalid Input!")
def YearToModifier(x):
if x%35 ==0 or x%7 ==0: return 1
if x%13 == 0: return -1
return 0
populationCurrent = intInput("What is the current population?") #ensure you get an int
n_years = intInput("How Many Years?") #ensure you get an int
#in this case populationChange is independent of initial population (this is rarely the case in reality)
populationChange = sum(YearToModifier(x) for x in range(n_years))
#the population in the future is the initialPopulation + population Change ... duh...
populationFuture = populationCurrent + populationChange
print("The Population will be %d!"%populationFuture)
there you go
WRT #martjinpeters comment on OP you could change YearToModifier to
def YearToModifier(x):
return sum([x%35 ==0,x%7 ==0,-1*int(x%13 == 0)])
of coarse as #AshokaLella points out you can calculate the total births/immigrations/deaths for a given number of years without actually visiting each year
births = n_years//7
immigrations = n_years//35
deaths = n_years//13
populationChange = births + immigrations - deaths
I have been testing some my code and for some reason my if statement is being ignored. The first if statement works but the second if statement doesn't, i have tried changing it to elif and it still doesn't work. Thanks in advance.
import random
diff = input("What is the ritual difficulty? ")
level = input("How many ritual levels do you have that pertain to this ritual? ")
bag = []
for success in xrange(10):
bag.append("Success")
bag.append("Flaw")
bag.append("Fail")
extra = level - diff
if extra >= 1:
extra = extra / 2
int(extra)
for chance in xrange(extra):
bag.append("Success")
if extra < 0:
for chance in xrange(extra):
bag.append("Flaw")
bag.append("Fail")
bag.append("Backlash")
print bag
random.shuffle(bag)
outcome = bag.pop()
print "The outcome of the ritual is: ", outcome
You second if will be entered if the diff is larger than the level. However, even if it does get entered it won't actally do something:
if extra < 0:
for chance in xrange(extra):
bag.append("Flaw")
bag.append("Fail")
bag.append("Backlash")
The xrange function will yield an empty "list" (it's not actually a list, as the documentation for xrange explains) for negative values, i.e. nothing will be appended to the bag.
It is not ignored, but when you run a for loop on xrange(extra) with extra being negative, then obviously this loop is immediately terminated.
P.S.: you might wanna try xrange(-extra) instead...
I'm toying around with writing creating a serial code generator/validator, but I can't seem to get how to do a proper check.
Here's my generator code:
# Serial generator
# Create sequences from which random.choice can choose
Sequence_A = 'ABCDEF'
Sequence_B = 'UVWQYZ'
Sequence_C = 'NOPQRS'
Sequence_D = 'MARTIN'
import random
# Generate a series of random numbers and Letters to later concatenate into a pass code
First = str(random.randint(1,5))
Second = str(random.choice(Sequence_A))
Third = str(random.randint(6,9))
Fourth = str(random.choice(Sequence_B))
Fifth = str(random.randint(0,2))
Sixth = str(random.choice(Sequence_C))
Seventh = str(random.randint(7,8))
Eighth = str(random.choice(Sequence_D))
Ninth = str(random.randint(3,5))
serial = First+Second+Third+Fourth+Fifth+Sixth+Seventh+Eighth+Ninth
print serial
I'd like to make a universal check so that my validation code will accept any key generated by this.
My intuition was to create checks like this:
serial_check = raw_input("Please enter your serial code: ")
# create a control object for while loop
control = True
# Break up user input into list that can be analyzed individually
serial_list = list(serial_check)
while control:
if serial_list[0] == range(1,5):
pass
elif serial_list[0] != range(1,5):
control = False
if serial_list[1] == random.choice('ABCDEF'):
pass
elif serial_list[1] != random.choice('ABCDEF'):
control = False
# and so on until the final, where, if valid, I would print that the key is valid.
if control == False:
print "Invalid Serial Code"
I'm well aware that the second type of check won't work at all, but it's a place holder because I've got no idea how to check that.
But I thought the method for checking numbers would work, but it doesn't either.
The expression `range(1, 5)' creates a list of numbers from 1 to 4. So in your first test, you're asking whether the first character in your serial number is equal to that list:
"1" == [1, 2, 3, 4]
Probably not...
What you probably want to know is whether a digit is in the range (i.e. from 1 to 5, I assume, not 1 to 4).
Your other hurdle is that the first character of the serial is a string, not an integer, so you would want to take the int() of the first character. But that will raise an exception if it's not a digit. So you must first test to make sure it's a digit:
if serial_list[0].isdigit() and int(serial_list[0]) in range(1, 6):
Don't worry, if it's not a digit, Python won't even try to evaluate the part after and. This is called short-circuiting.
However, I would not recommend doing it this way. Instead, simply check to make sure it is at least "1" and no more than "5", like this:
if "1" <= serial_list <= "5":
You can do the same thing with each of your tests, varying only what you're checking.
Also, you don't need to convert the serial number to a list. serial_check is a string and accessing strings by index is perfectly acceptable.
And finally, there's this pattern going on in your code:
if thing == other:
pass
elif thing != other:
(do something)
First, because the conditions you are testing are logical opposites, you don't need elif thing != other -- you can just say else, which means "whatever wasn't matched by any if condition."
if thing == other:
pass
else:
(do something)
But if you're just going to pass when the condition is met, why not just test the opposite condition to begin with? You clearly know how to write it 'cause you were putting it in the elif. Put it right in the if instead!
if thing != other:
(do something)
Yes, each of your if statements can easily be cut in half. In the example I gave you for checking the character range, probably the easiest way to do it is using not:
if not ("1" <= serial_list <= "5"):
Regarding your python, I'm guessing that when your wrote this:
if serial_list[0] == range(1,5):
You probably meant this:
if 1 <= serial_list[0] <= 5:
And when you wrote this:
if serial_list[1] == random.choice('ABCDEF'):
You probably meant this:
if serial_list[1] in 'ABCDEF':
There are various other problems with your code, but I'm sure you'll improve it as you learn python.
At a higher level, you seem to be trying to build something like a software activation code generator/validator. You should know that just generating a string of pseudo-random characters and later checking that each is in range is an extremely weak form of validation. If you want to prevent forgeries, I would suggest learning about HMAC (if you're validating on a secure server) or public key cryptography (if you're validating on a user's computer) and incorporating that into your design. There are libraries available for python that can handle either approach.