Did I choose the correct equation to calculate this? - python

I'm not sure if there is actually an error here, but I (out of curiosity) created a program that calculated how many people across ~241 generations had... let's say intimate relations before just one person in Generation Z was born, and then following that how many people had intimate relations before the whole population of Generation Z was born.
Prerequisites: There are 72.1 million people in Gen Z, and one Generation lasts 25 years. All relationships are monogamous. Each couple has one child.
import time
#I made this program out of pure curiousity (I'm not lewd, I promise) and I found it pretty interesting.
#Bunny art
print(" z")
print(" z")
print(" z")
print("(\(\ ")
print("(– -)")
print("(‘)(’)")
#Variable Declarations
generationLength = 25
totalYears = 6026
numberOfGenerations = totalYears / generationLength
numberOfCalculations = 0
numberOfPeople = 1
numberOfPeopleOnEarth = 7750000000
numberOfPeopleInThisGeneration = 72100000
def howManyPeopleHadSexBeforeICameIntoExistence():
#Mathematics
numberOfCalculations = 0
while (numberOfCalculations < numberOfGenerations):
numberOfPeople = numberOfGenerations * 2
numberOfCalculations = numberOfCalculations + 1
#Output
time.sleep(2)
print("\nCalculating pointless knowledge...")
time.sleep(2)
print("At least " + str(round(numberOfPeople)) + " people in had sex before one person in Generation Z was born.")
#Mathematics
total = round(numberOfPeople * numberOfPeopleInThisGeneration)
#Output
time.sleep(2)
print("\nCalculating extra trivia...")
time.sleep(2)
print("At least " + str(total) + " had sex before every person in Generation Z was born.")
howManyPeopleHadSexBeforeICameIntoExistence()

import time
# I made this program out of pure curiousity (I'm lewd, I promise) and I found it pretty interesting.
# Bunny art
print(" z")
print(" z")
print(" z")
print("(\(\ ")
print("(– -)")
print("(‘)(’)")
# Variable Declarations
generationLength = 25
totalYears = 6026
numberOfGenerations = totalYears / generationLength
numberOfPeopleOnEarth = 7750000000
numberOfPeopleInThisGeneration = 72100000
percentage_of_current_generation = numberOfPeopleInThisGeneration/numberOfPeopleOnEarth
max_age = 100
def howManyPeopleHadSexBeforeICameIntoExistence():
numberOfPeople = numberOfPeopleInThisGeneration * (2 ** numberOfGenerations) - numberOfPeopleInThisGeneration
# Output
time.sleep(2)
print("\nCalculating pointless knowledge...")
time.sleep(2)
print("At least " + str(round(numberOfPeople)) + " people in history had sex before one person in Generation Z was born.")
# Mathematics
total_alive = round(numberOfPeopleInThisGeneration * (2 ** (max_age/generationLength)) - 1)
# Output
time.sleep(2)
print("\nCalculating extra trivia...")
time.sleep(2)
print("At least " + str(total_alive) + " people currently alive had sex before every person in Generation Z was born.")
howManyPeopleHadSexBeforeICameIntoExistence()

Related

Function must be defined with 1 argument

My code works as intended, but the bot code checker displays an error "The 'budget' function should be defined with 1 argument, I currently found 0 arguments in the definition."
I've tried to come up with multiple solutions, but none work.
invited = input("Mitu kutsutud?: ")
coming = input("Mitu tuleb?: ")
food = 10
room = 55
def budget():
max_budget = 10 * int(kutsutud) + 55
min_budget = 10 * int(tuleb) + 55
print(str(max_budget) + " eurot")
print(str(min_budget) + " eurot")
budget()
invited = input("Mitu kutsutud?: ")
coming = input("Mitu tuleb?: ")
food = 10
room = 55
#This function needs 2 arguments assuming you are
#trying to use kutsutud and tuleb as the int values in your function
#This also assumes that min and max budget are unchanging
#Also the data above cannot be used because the exist before the function was created
def budget(exampleA,exampleB):
max_budget = 10 * int(kutsutud) + 55
min_budget = 10 * int(tuleb) + 55
print(str(max_budget) + " eurot")
print(str(min_budget) + " eurot")
budget()
##################################################################################
##Make your function here.
def budget(exampleA,exampleB):
max_budget = 10 * int(kutsutud) + 55
min_budget = 10 * int(tuleb) + 55
print(str(max_budget) + " eurot")
print(str(min_budget) + " eurot")
# Set Vars here
invited = input("Mitu kutsutud?: ")
coming = input("Mitu tuleb?: ")
food = 10
room = 55
#Call function here
budget(invited, coming)
Hope this helps based on what I understood from the question.

Program skipping if statement [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 2 years ago.
I'm a beginner with python.
I've created a little program for my navigation homework which when I input the data solves it for me but it's not working. It asks the initial question to determine which type of problem to solve and then, when it's supposed to solve it, it crashes. Why is that?
import math
print("Insert all values in degree decimal form.")
prob = input("1 or 2")
if prob == 1:
fia = input("Insert value of phi in A: ")
lama = input("Insert value of lambda in A: ")
route = input("Insert value of true route: ")
vel = input("Insert speed: ")
Tma = input("Insert Established Time of Departure: ")
Tmb = input("Insert Established Time of Arrival: ")
deltaT = Tmb - Tma
print(deltaT)
m = vel * deltaT
print(m)
deltafi = (m / 60) * math.cos(route)
print(deltafi)
fib = fia + deltafi
if fib > 180:
fib1 = -(360 - fib)
fib = fib1
print(fib)
else:
print(fib)
fim = (fia + fib) / 2
print(fim)
deltalam = (m * math.sin(route) / (60 * math.cos(fim)))
lamb = lama + deltalam
if lamb > 180:
lamb1 = -(360 - lamb)
lamb = lamb1
print(lamb)
else:
print(lamb)
print("Coordinates of B: ")
print(fib, lamb, Tmb)
elif prob == 2:
fia = input("Insert value of phi in A: ")
lama = input("Insert value of lambda in A: ")
fib = input("Insert value of phi in B: ")
lamb = input("Insert value of lambda B: ")
deltafi = fib - fia
deltalam = lamb - lama
fim = (fia + fib) / 2
tanroute = (deltalam / deltafi) * math.cos(fim)
route = math.atan(tanroute)
m = (60 * abs(deltafi)) / math.cos(route)
You have to convert the prob input (and all the other inputs) into int as it is considered a string by default: prob = int(input("...")).
You can also verify this by simply printing type(prob).
Input in python receives the value as string, and you are comparing it to integer value in your if condition
update your input statement to the following line to receive integer input:
prob = eval(input("1 or 2"))
Input method interpret your data as string, not as integer.
In your if condition you've to put
if int(prob) == 1:

Loop to add more input

I have 3 more cars that I have but I need to know how to loop things like the car input so it will allow you to input it again if you do the wrong input same thing with the extras so they have to be either 1 or 0.
print("===================================================")
print("==============Car Finance Calculations=============")
print(" Choose your veicle: ")
print(" SUV type 1 ")
print(" Hatch type 2 ")
print(" Sedan type 3 ")
print("===================================================")
caaaaaaaar = int(input(" Please enter Which car you want to finance: "))
years = int(input(" enter years of loan either 3 or 4 or 5 Years: "))
if caaaaaaaar == 1:
carsvalue = int(input("Please enter you cars value: "))
residual = carsvalue * 0.30
financing = carsvalue - residual
print(" financing value for the car is: ", round(financing,2))
print(" Intrest rate is 9% ")
n = years * 12
r = 9 / (100 * 12)
Financingcost = financing * ((r*((r+1)**n))/(((r+1)**n)-1))
print(" Your Montly financing rate is: ", round(Financingcost,2))
print("================================================================================")
print("Please Choose extras: ")
print("======================================================")
print(" If you would like fuel type 1 if not type 0")
print(" If you would like insurance type 1 if not type 0")
print(" if you would like Maintenance type 1 if not type 0")
print("======================================================")
if caaaaaaaar == 1:
x, y, z = [int(x) for x in input("Enter Your extras with spaces:").split()]
print("=======================================")
if x == 1:
print("Yes you want fuel")
fuelcost = 80 * 4.33
print("fuel cost is", round(fuelcost,2))
if x == 0:
print("you dont want fuel as an extra")
fuelcost = 0
print("Fuel cost is: ", fuelcost)
print("=======================================")
if y == 1:
print("yes you want insurance")
insurancecost = (1200 / 12)
print("Insurance cost is: ", round(insurancecost,2))
if y ==0:
print("you dont want insurance")
insurancecost = 0
print("insurance cost is: ",insurancecost)
print("=======================================")
if z == 1:
print("yes you want maintenance")
maintenancecost = (100 * 1)
print("Maintenance cost is: ", round(maintenancecost,2))
if z == 0:
print("you dont want maintenance")
maintenancecost = 0
print("maintenance cost is: ",maintenancecost)
print("=======================================")
total_cost_for_extras = fuelcost + maintenancecost + insurancecost
print("Total cost for the selected extras is: ", round(total_cost_for_extras,2))
TOTALFOREVERYTHING = total_cost_for_extras + Financingcost
print("Total monthly financing rate is: ", round(TOTALFOREVERYTHING,2))
You want to use a while loop.
Like this:
carsEntered = 0
while (carsEntered <= 4):
caaaaaaaar = int(input(" Please enter Which car you want to finance: "))
years = int(input(" enter years of loan either 3 or 4 or 5 Years: "))
carsEntered += 1
You could also use a for loop instead but that depends on what you want to do.
As per my understanding of the question you want to run an iteration until the user gives the right answer.
In that case, you can use flag variable in while.
flag = False
while(flag is False):
if(condition_statisfied):
flag = True
I suggest that you put your vehicle types in a dictionary:
vehicle_type_dict = {
1: "SUV type",
2: "Hatch type",
3: "Sedan type"
}
and do a while-loop to check if your input is in the dictionary:
while True:
caaaaaaaar = int(input(" Please enter Which car you want to finance: "))
if caaaaaaaar not in vehicle_type_dict:
continue #loop again if input not in the dictionary
#read next line of code if input is in the dictionary
#do something below if input is correct
years = int(input(" enter years of loan either 3 or 4 or 5 Years: "))
break #end loop
My recommendation is to take a functional approach to this problem. You are calling int(input()) multiple times and want to validate the user input before proceeding on to the next lines each time. You can do this in a function that will continue to loop until the input is confirmed as valid. Once the input is validated, you can exit the function's frame by returning the value using the return key word.
# This is the function definition.
# The code in this function does not execute until the function is called.
def prompt_int(
text,
minimum=0,
maximum=1,
error="The value you entered is not valid try again."
):
# when the function is called it will start a second while loop that will keep looping
# until valid input is entered
while True:
try:
val = int(input(text))
if minimum <= val <= maximum:
return val
raise ValueError
except ValueError:
print(error)
# This is the outer while loop. It will keep looping forever if the user so chooses.
while True:
# instead of calling print() a bunch one option is to assign a docstring to a variable
car_prompt = '''
===================================================
==============Car Finance Calculations=============
Choose your veicle:
SUV: 1
Hatch: 2
Sedan: 3
===================================================
Please enter the number for the car you want to finance or 0 to exit:\n
'''
# This is where we first call the function.
# Our docstring will be passed into the function to be used as a prompt.
# We also pass in some args for maximum and minimum params
caaaaaaaar = prompt_int(car_prompt, 0, 3)
# 0 is false so we can exit the while loop if the user enters 0
if not caaaaaaaar:
break
year_prompt = "Enter years of the car loan (3, 4 or 5):\n"
years = prompt_int(year_prompt, 3, 5)
if caaaaaaaar == 1:
val_prompt = "Please enter you cars value:\n"
carsvalue = prompt_int(val_prompt, 0, 2147483647)
residual = carsvalue * 0.30
financing = carsvalue - residual
print("Financing value for the car is: ", round(financing, 2))
print("Intrest rate is 9% ")
n = years * 12
r = 9 / (100 * 12)
Financingcost = financing * ((r * ((r + 1) ** n)) / (((r + 1) ** n) - 1))
print(" Your Montly financing rate is: ", round(Financingcost, 2))
print("================================================================================")
print("Please Choose extras: ")
print("======================================================")
x = prompt_int("If you would like fuel type 1 else type 0:\n")
y = prompt_int("If you would like insurance type 1 else type 0:\n")
z = prompt_int("If you would like Maintenance type 1 else type 0:\n")
print("======================================================")
if x == 1:
print("Yes you want fuel")
fuelcost = 80 * 4.33
print("fuel cost is", round(fuelcost, 2))
else:
print("you dont want fuel as an extra")
fuelcost = 0
print("Fuel cost is: ", fuelcost)
print("=======================================")
if y == 1:
print("yes you want insurance")
insurancecost = (1200 / 12)
print("Insurance cost is: ", round(insurancecost, 2))
else:
print("you dont want insurance")
insurancecost = 0
print("insurance cost is: ", insurancecost)
print("=======================================")
if z == 1:
print("yes you want maintenance")
maintenancecost = (100 * 1)
print("Maintenance cost is: ", round(maintenancecost, 2))
else:
print("you dont want maintenance")
maintenancecost = 0
print("maintenance cost is: ", maintenancecost)
print("=======================================")
total_cost_for_extras = fuelcost + maintenancecost + insurancecost
print("Total cost for the selected extras is: ", round(total_cost_for_extras, 2))
TOTALFOREVERYTHING = total_cost_for_extras + Financingcost
print("Total monthly financing rate is: ", round(TOTALFOREVERYTHING, 2))
elif caaaaaaaar == 2:
# Put your code for car 2 in this block.
# If it is like car 1 code except the value of a few variables
# then make another func
pass
else:
# Car 3 code...
pass

questions repeated 4x, float not callable, error on code

I dont understand why the code doesnt work and they have repeated the questions to me 4 times. and say that float is not callable. i have tried doing this for quite awhile but i dont seem to get anything at all. is there any easier way for python3? I just learnt this language 2 weeks ago. its not a whole new world to me but many of the things i am not familiar with. such as indentation
def get_taxi_info():
flag_down = float(input("What's the flag-down fare: $"))
within = float(input("What's the rate per 400 meters within 9.8km? $"))
beyond = float(input("What's the rate per 350 meters beyond 9.8km? $"))
distance = float(input("What's the distance traveled (in meters)? "))
peak = input("Is the ride during a peak period? [yes/no]")
mid6 = input("Is the ride between midnight and 6am? [yes/no]")
location = input("Is there any location surcharge? [yes/no]")
surloca = float(input("What's the amount of location surcharge?"))
return (flag_down, within, beyond, distance, peak == 'yes', mid6 == 'yes', location == 'yes', surloca)
def calculate_taxi_fare():
dist = get_taxi_info()
if dist[3] > 9800:
extra = (dist[3] - 9800) % 350
if extra == 0:
a = (extra//350) + 22
else:
a = (extra//350) + 23
return a
elif dist[3] <= 9800:
extra = (dist[3] - 1000) % 400
if extra == 0:
a = (extra//400)
else:
a = (extra//400) + 1
return a
def peakornot():
peak = get_taxi_info()
if peak[4] == True and peak[5] == False:
surcharge = 1.25
return surcharge
elif peak[4] == False and peak[5] == True:
surcharge = 1.50
return surcharge
taxifare = calculate_taxi_fare()
info = get_taxi_info()
peak1 = peakornot()
taxifare = calculate_taxi_fare()
if info[6] == True:
payable = ((info[0] + (info[1] * taxifare()) + (info[2] * taxifare())) * peak1[0]) + info[7]
print ("The total fare is $" + str(payable))
elif info[6] == False:
payable = ((info[0] + (info[1] * taxifare()) + (info[2] * taxifare())) * peak1[0]) + info[7]
print ("The total fare is $" + str(payable))
The function calculate_taxi_fare returns a float, so on this line taxifare is a float
taxifare = calculate_taxi_fare()
Therefore you cannot say taxifare() because it looks like a function call, so you can just use for example
info[1] * taxifare

no matter what i do, when i add the modifier to the characters strength it keeps saying it isnt defined how do i fix it?

import time
import random
c1_strength = 12
c1_skill = 22
c2_strength = 16
c2_skill = 12
Modifier_skill = int(c1_skill) - int(c2_skill)
print("The skill modifier equals:\n")
print (Modifier_skill)
time.sleep(0.5)
Modifier_strength = int(c2_strength) - int(c1_strength)
print("The strength modifier equals:\n")
print (Modifier_strength)
time.sleep(0.5)
Player_1 = (random.randint(1,6))
print("Player_1 has rolled a 6 sided dice and rolled a:\n")
print(Player_1)
Player_2 = (random.randint(1,6))
print("Player_2 has rolled a 6 sided dice and rolled a:\n")
print(Player_2)
while(Player_1) == (Player_2):
print("no changes will be made")
break
if (Player_1) > (Player_2):
p1_strength = int(c1_strength) + int(Modifier_strength)
print("Player_1's new strength is:\n")
print(p1_strength)
p1_skill = int(c1_skill) + int(Modifier_skill)
print("Player_1's new skill is:\n")
print(p1_skill)
p2_strength = int(c2_strength) - int(Modifier_strength)
print("Player_2's new strength is:\n")
print(p2_strength)
p2_skill = int(c2_skill) - int(Modifier_skill)
print("Player_2's new skill is:\n")
print(p2_skill)
if (Player_1) > (Player_2):
pl2_strength = int(c2_strength) + int(Modifier_strength)
print("Player_1's new strength is:\n")
print(pl2_strength)
pl2_skill = int(c2_skill) + int(Modifier_skill)
print("Player_1's new skill is:\n")
print(pl2_skill)
pl1_strength = int(c1_strength) - int(Modifier_strength)
print("Player_2's new strength is:\n")
print(pl1_strength)
pl1_skill = int(c1_skill) - int(Modifier_skill)
print("Player_2's new skill is:\n")
print(pl1_skill)
this is my code, not sure whats wrong but when run it keeps saying that p1 strength is not defined. Another strange thing is that sometimes the code will work once or twice but then the next part will create an error, then after somehow fixing that the first part breaks again
First of all I'm barely sure what is even going on. this is hideous python. the problem is that p1_strength is defined in the if block
if(Player_1 > Player_2):
p1_strength = int(c1_strength) + int(Modifier_strength)
if this block does not execute, i.e. if Player_1 <= Player_2, p1_strength will be undefined.
this can be fixed by initializing your variables in the top of your script with something for instance, 0
c1_strength = 12
c1_skill = 22
c2_strength = 16
c2_skill = 12
p1_strength = 0
pl2_strength = 0

Categories

Resources