Python - Take an int variable and times it by a float? - python

As a learning project, I'm attempting to write a small game to simply get familiar with the Python language as well as build my programming skills. Being somewhat of a gamer, I always seem to want to add additional code to the game to make it more playable and therefore enjoyable. Right now I'm stuck on stupid and hope this is fairly easy to solve by the more familiar:
Python 3.8.8
I have an int that has been randomly selected and added it to a variable:
if act_trl_cls == trl_cls[0]:
trl_atk_pwr = random.randint(7.0, 10.0)
What I'm looking to do is create a float (for percentage purposes) add it to a variable:
if act_trl_cls == trl_cls[0]:
trl_cls_wpn_ran = random.uniform(0.01, 0.05)
trl_cls_wpn_dmg = "{:.2f}".format(trl_cls_wpn_ran) # converts to two decimal points
... and then multiply them to get a percentage, much like we do with tipping.
Example:
Bill Total: $53.56
$53.56 * .20 = $10.71
$53.56 + $10.71 = $64.27
Total: $64.27
My question is how do we represent this in Python? Everytime I attempt:
if fight_confirmation == "Y" or fight_confirmation == "y":
total = trl_atk_pwr * trl_cls_wpn_dmg
... I end up with:
0.030.030.030.030.030.030.030.03
... or some other variation depending on the random int and float chosen by the random function and respective method rather than the return value of the multiplied values assigned to each variable. Obviously this is not the correct way to do this.

You have to convert it to float before multiplication like below .
if fight_confirmation == "Y" or fight_confirmation == "y":
total = float(trl_atk_pwr) * float(trl_cls_wpn_dmg)
You are getting this because now you are getting trl_cls_wpn_dmg as a string and it will do concatenation when you are multiplying it by a number.

Related

What's the problem in this short user-defined function?

It says that "salary" is not defined or that i can't multiply this.
I want to have it with the def command so please just let it in this form just correct the mistakes, im completely new to it so just let it as easy as it is. Thank you very much :)
def computepay(Hours,RatePerHour):
if float(Hours)-40<0:
salary=float(Hours)*float(RatePerHour)
else:
salary=40.0*float(RatePerHour)+(float(Hours)-40.0)*float(RatePerHour*1.5)
Hours=input("Hours:\n")
RatePerHour=input("RatePerHour:\n")
computepay(Hours,RatePerHour)
print("Salary:")
print(salary)
I expect that someone could help me how this little program works correct
You need to return salary and then assign this to a variable. Here's an improved version of your code:
def compute_pay(hours: float, rate_per_hour: float) -> float:
if hours - 40 < 0:
salary = hours * rate_per_hour
else:
salary = 40 * rate_per_hour + (hours - 40.0)* rate_per_hour * 1.5
return salary # This is the line you are missing!
hours = input("Hours:\n")
rate_per_hour=input("RatePerHour:\n")
computer_salary = computepay(float(hours), float(rate_per_hour)) # You also need to assign the output of a function to a variable, I've given it a different name from salary just to show you that this is a different variable from the one inside your function. Also, cast to float here so you don't have to do it all over your function.
print(f"Salary: {computer_salary}")
The concept you need to learn here is called scope.
You needed to return the calculated salary.
Also, simpler if you performed the float conversion on input.
def computepay(Hours,RatePerHour):
if float(Hours)-40<0:
salary=Hours*RatePerHour
else:
salary=40.0*RatePerHour+ (Hours-40.0)*(RatePerHour*1.5)
return salary # return value
Hours = float(input("Hours:\n")) # float conversion
RatePerHour = float(input("RatePerHour:\n")) # float conversion
salary = computepay(Hours,RatePerHour)
print("Salary:")
print(salary)
Here is the correction, and some explications follow.
def computepay(Hours,RatePerHour):
salary = 0
if float(Hours)-40<0:
salary=float(Hours)*float(RatePerHour)
else:
salary=40.0*float(RatePerHour)+(float(Hours)-40.0)*float(RatePerHour) *1.5) #<=== here you multiply with out turning rateperhour as float
return salary
Hours=input("Hours:\n") RatePerHour=input("RatePerHour:\n")
salary = computepay(Hours,RatePerHour)
print("Salary:")
print(salary)
First, salary is a variable enclosed inside your function, it's not a avaliable outside of it.
Second, you get an error because you multiply a string by an integer. Convert it to float before.
float(RatePerHour*1.5) #wrong
float(RatePerHour) *1.5 # correct

Transforming an input variable into an interger

I'm completely new to python, and I wanted to create a program that "loads" a number that the user would have entered.
To do this, I made a function with an input variable,
percentage
that I then tried to transform to an interfer,
percentage_int
To then put in a while loop.
However, I get an error message, why?
def loader():
percentage = input("what percentage do you want?")
percentage_int =int(percentage)
x = 0
print("Goal:{} %".format(percentage_int))
while x < percentage_int:
x+=1
print(x)
loader()
You need to do the type conversion, that is in this case from string to integer.
If you dont do so python will consider percentage_int as the input string itself.
percentage = input("what percentage do you want?")
percentage_int = int(percentage)
Go through this tutorial which will help you learn more about type conversions with python.

Defined Argument Doesn't seem to Fire

Please mind I am very new to the Python world.
I've been looking for an answer to this online and can't seem to find the right solution, based on my understanding I feel the logic is correct. In the end, though my results are just not there.
I am compiling with Idle.
Point of the solution: Is to take a string value of Kilometers from the console. Then convert it to Miles, then output the string.
Seems simple but debugging the below code over and over again I cannot seem to figure out why after I enter my kilometer number the print with the conversion value never displays.
def main(distanceMile=None):
# Declare and initialize variables
# string called distancekilo
distanceKilo = ""
# distancemile = ""
# conversion = 0.6214
# Introduction
print("Welcome to the distance converter \n")
# Prompt for distance in Kilometers
distanceKilo = input("Enter distance in Kilometers: ")
# Default Argument
def calcConvert(value):
conversion = 0.6214
distanceMile = int(value) * conversion
return distanceMile
calcConvert(distanceKilo)
print("That distance in miles is ", distanceMile)
I would simply like to know where I am going wrong here?
Your code has three main bugs. One is the indentation at the end of calcConvert (return should be indented). Another is that the main definition at the top doesn't seem to do anything. Another is that you want to save calcConvert(distanceKilo) to a variable. This code works:
# Introduction
print("Welcome to the distance converter \n")
# Prompt for distance in Kilometers
distanceKilo = input("Enter distance in Kilometers: ")
# Default Argument
def calcConvert(value):
conversion = 0.6214
distanceMile = int(value) * conversion
return distanceMile
distanceMile = calcConvert(distanceKilo)
print("That distance in miles is ", distanceMile)
If you're new to Python, I would suggest also reading some posts and articles about the way people normally style code (like calc_convert vs calcConvert) in Python :) It's not entirely necessary, but it makes it easier for other Python users to read your code.

Why does this function not return a value?

Be forewarned, I just started learning Python, and its my first time on this site. If I act like a n00b, please don't hate.
So I have created a program that is supposed to tell you how long it will take you to get to a star (distance is specified) at the speed of light, and factors of the speed of light. It begins with a library called easygui, which creates a nice window, which the user chooses a factor. The factor they have chosen becomes the variable "choice". This section of the code works fine. Ideally, this value would then be fed into a function, which would do the factoring, and return a value for the number of days of travel. This is unsuccessful. Most likely, I have simply set this up wrong, so if anyone knows the proper way to use functions, I'd really appreciate your help! Oh, and I tried to comment like crazy, so hopefully everything makes sense!
import easygui as eg #the gui creation library I am using
dist = 41000000000000 #distance to the star
light = 300000 #speed of light
def Convert (factor): #takes in factor chosen by user
speed = light*factor #the speed is the factor multiplied by the speed of light
time = (dist/speed)/3600 # the time is the distance/divided by the speed, since thats a huge value in seconds, the /3600 should reduce it to days
return time #"should" return the value it got for "time"
msg = "Choose a warp factor:" #creates a gui window for user to select factor
title = "Warp Factor Selection"
choices = ["1", "3", "5", "10", "50", "100", "200", "500", "1000"]
choice = eg.buttonbox(msg, title, choices) #gui returns the user's selection as "choice" WORKS!
choice = float(choice) #changes choice to float
if choice == 1:
Convert(choice) #attempts to feed "choice" into the function "convert" DOES NOT WORK :(
print (Convert(1)) #then print the value created from convert (have also tried print(time) but it always returns 0)
At this point in time, it is intentionally set up to only accept the choice of 1 as the factor. I want to figure this function thing out before I go and do the rest of the possible factors
thefourtheye already explained why, but if you want to avoid this in the future you could switch to Python 3 division by putting this at the top of your file:
from __future__ import division
In Python 3, it behaves more intuitively in situations like this (1/2 == .5) while you can still get the integer division behavior with // (1//2 == 0)
When you do
(dist/speed)/3600
if the (dist/speed) is lesser than 3600, result will be 0. You can try that out yourself,
print 3599/3600
will print
0
So, you need to convert the data to float like this
def Convert (factor):
speed = light*factor
return (float(dist)/float(speed))/3600.0
You may want to do this
if str(choice) in choices:
Convert(choice)
print (Convert(choice))
That way, you don't have to make a new if condition to test each number. This just says that if choice is in choices list, execute the function with choice.

how to write program for area for circle and square

Write a program that asks the user to enter two values: an integer choice and a real number x. If choice is 1, compute and display the area of a circle of radius x. If choice is 2, compute and display the are of a square with sides of length x. If choice is neither 1, nor 2, will display the text Invalid choice.
so im guessing this is broken into 2 parts? all i can think of so far is having a choice(input) function and defining what pi and area and so on are. but i keep getting errors. what am i doing wrong?
choice = input ('Enter Choice:')
choice_1 = int (choice)
if (choice_1==1): radius = (int)
print('Enter x:',radius)
pi = 3.14159
area = ( radius ** 2 ) * pi
print ( 'The Area is=' , area )
choice_2= (choice)
if (choice_2==2): side= (int)
print('enter X:' side*side)
While you've got the actual calculations right, there are some problems with how you're receiving input. You start out well:
choice = input ('Enter Choice:')
But then do this:
choice_1 = int (choice)
That's not wrong, but there's no need for a new variable name. You could just as well do choice = int(choice).
You then go on:
if (choice_1==1): radius = (int)
The if statement is okay (although the parentheses are not necessary), but the body of it is a bit strange. I don't know what you're trying to achieve there, but it's almost certainly not doing what you want. What you'll probably want to do is remove the current body of the if statement and indent a bunch of the following code.
print('Enter x:',radius)
This will print out Enter x: followed by radius, which you just set to the int function (probably not what you want. Instead, you probably want to prompt the user and receive their input:
radius = input('Enter x: ')
And then convert it to a float:
radius = float(radius)
Back to your code. pi = 3.14159 is valid and correct, but there is no need to assign pi in your own code; just import it from math:
from math import pi
Then you've got these two lines:
area = ( radius ** 2 ) * pi
print ( 'The Area is=' , area )
You've got no problem there; those should work fine. Your code continues:
choice_2= (choice)
This is not useful. Just use choice; you don't need a new variable.
if (choice_2==2): side= (int)
The if statement, here, too, is correct, but its body, too, is senseless. Again, you probably want to prompt the user to enter something and then convert it to a float.
At the end, you've got:
print('enter X:' side*side)
First of all, you're missing a comma. Second of all, you're outputting the area after enter X:, which doesn't make that much sense. That said, you did get the calculation right.
There are a number of issues with the code. Here is a working example of what I believe you want to accomplish:
#!/usr/bin/python
pi = 3.14159265
choice = input('Enter Choice [1 or 2]:')
choice = int (choice)
if choice == 1:
radius = input('Enter x:')
area = ( radius ** 2 ) * pi
print 'The Area is=', area
if choice == 2:
side = input('Enter x:')
area = side ** 2
print 'The Area is=', area
There are a number of problems with the code you've presented: indentation, variables, inputs, and outputs. There are a number of improvements that can be made as well (such as removing duplicate statements). The code I've given above will accomplish what you want to do. So let's go through the errors to get a deeper understanding.
Indentation
First, Python programs should be indented properly. This means that lines following a conditional logic (such as an if statement) should be tabbed. The indentation is called a "block" statement. Only those lines that are indented will be evaluated (executed) if the given condition is met (e.g., the user supplied 1 or 2 as a value).
Variables
The choice_1 and choice_2 variables are not necessary. Logistically, you want to tell the reader of your source code that the user's input should be rounded to a whole integer. The extra variables are superfluous -- you can reuse the choice variable.
Inputs
The input function is used to assign the value of whatever the user typed to the variable on the left-hand-side of the expression. Examples:
choice = input ('Enter choice:')
radius = input( 'Enter x:' )
side = input( 'Enter x:' )
These input statements appear on the screen. The user types in a number and the value of that number is put inside the corresponding variable.
Outputs
The print statement is used to display a value on the screen. In your code, you had combined a text string ('Enter x') with a print statement. The computer cannot "know" that 'Enter x' means that the user must type in a value. Just like the computer does not know that 'Barney' is the name of a purple dinosaur.
radius = (int)
This seems to be the main problem.
A few things.
If that is how your script is indented, it's not going to work, period. Indenting is core to python, and you need to understand that before you'll get anything substantial working.
If the input is an integer, it will be automatically converted using input(). You're only asking for input once, so don't both creating two variables.
choice = input('Enter choice: ')
If should be using an if-elif-else statement here. Use control structures to your advantage:
if choice == 1:
radius = input('Enter radius: ')
print('Area of circle is ', (radius ** 2) * 3.14159)
elif choice == 2:
side = input('Enter side length: ')
print('Areas of square is ', side*side)
That's simplified, what you're trying to acheive.
Other than that, you shouldn't do side= (int) or radius = (int). You're assigning a type of int to the variable, when you should be getting a value from input. You'll find very quickly that there are no operators that support multiplication of type and type.

Categories

Resources