Combining integers and strings when asking for input? - string

This is a very basic question as I am new to computer programming but I am having problems. The question is asking me to write in Python 3 an equation for area of a rectangle that allows the user to input the width and length in square feet and output the answer in square feet. This is what I've tried:
width = int(input("What is the width of the rectangle?")
10 ft^2
length = int(input("What is the length of the rectangle?")
5 ft^2
area = str(length*width("feet squared.")
but I get errors when even trying to input an integer with "feet squared" attached to it. Can anybody help me?

You must change the area assigment part to,
area = str(length*width) + " feet squared."
That is you must use the string concatenation operator + here.
or
area = "{0} feet squared.".format(length*width)

Example answer using numbers following rules stated in question:
width = input("What is the width of the rectangle?"
# What is the width of the rectangle? 10
length = input("What is the length of the rectangle?")
# What is the width of the rectangle? 5
area = "{0} feet squared.".format(length*width)
print(area)
# 50 feet squared.

Related

Convert Excel column width between characters unit and pixels (points)

"One unit of column width is equal to the width of one character in the Normal style. For proportional fonts, the width of the character 0 (zero) is used."
So ColumnWidth in Excel is measured as a number of "0" characters which fits in a column. How can this value be converted into pixels and vice versa?
As already mentioned ColumnWidth value in Excel depends on default font of a Workbook which can be obtained via Workbook.Styles("Normal").Font. Also it depends on current screen DPI.
After carrying out some research for different fonts and sizes in Excel 2013 I've found out that we have 2 linear functions (Arial cannot be seen because it overlaps with Tahoma.):
As it can be seen in the picture the function for ColumnWidth < 1 is different from the major part of the line chart. It's calculated as a number of pixels in a column / number of pixels needed to fit one "0" character in a column.
Now let's see what a typical cell width consists of.
A - "0" character width in the Normal Style
B - left and right padding
C - 1px right margin
A can be calculated with GetTextExtentPoint32 Windows API function, but font size should be a little bit bigger. By experiment I chose +0.3pt which worked for me for different fonts with 8-48pt base size. B is (A + 1) / 4 rounded to integer using "round half up". Also screen DPI will be needed here (see Python 3 implementation below)
Here are equations for character-pixel conversion and their implementation in Python 3:
import win32print, win32gui
from math import floor
def get_screen_dpi():
dc = win32gui.GetDC(0)
LOGPIXELSX, LOGPIXELSY = 88, 90
dpi = [win32print.GetDeviceCaps(dc, i) for i in (LOGPIXELSX,
LOGPIXELSY)]
win32gui.ReleaseDC(0, dc)
return dpi
def get_text_metrics(fontname, fontsize):
"Measures '0' char size for the specified font name and size in pt"
dc = win32gui.GetDC(0)
font = win32gui.LOGFONT()
font.lfFaceName = fontname
font.lfHeight = -fontsize * dpi[1] / 72
hfont = win32gui.CreateFontIndirect(font)
win32gui.SelectObject(dc, hfont)
metrics = win32gui.GetTextExtentPoint32(dc, "0")
win32gui.ReleaseDC(0, dc)
return metrics
def ch_px(v, unit="ch"):
"""
Convert between Excel character width and pixel width.
`unit` - unit to convert from: 'ch' (default) or 'px'
"""
rd = lambda x: floor(x + 0.5) # round half up
# pad = left cell padding + right cell padding + cell border(1)
pad = rd((z + 1) / 4) * 2 + 1
z_p = z + pad # space (px) for "0" character with padding
if unit == "ch":
return v * z_p if v < 1 else v * z + pad
else:
return v / z_p if v < z_p else (v - pad) / z
font = "Calibri", 11
dpi = get_screen_dpi()
z = get_text_metrics(font[0], font[1] + 0.3)[0] # "0" char width in px
px = ch_px(30, "ch")
ch = ch_px(px, "px")
print("Characters:", ch, "Pixels:", px, "for", font)
2022 and still the same Problem... Found threads going back to 2010 having the issue...
To start of: Pixel != Points
Points are defined as 72points/inch: https://learn.microsoft.com/en-us/office/vba/language/glossary/vbe-glossary#point
Though that definition seems stupid, as a shape with a fixed width of 100points, would display the exact same size in inch on every monitor independent of monitor configuration, which is not the case.
Characters is a unit that is defined to the number of 0 characters of the default text format. A cell set to a width of 10 characters, can fit 10 "0" characters, when the cell content is formatted to the default format.
My case is that I need to place pictures into the document and place text into cells next to it. But pictures hover over the document and cells are hidden below it. Depending on the size of the Picture, more or less cells are hidden. Thus, I can't just say I place text 5 cells to the left of the picture. Autosizing a column to the contents of the cells of the column, does not account for the hovering picture.
A picture is bound to the cell that is below the top left corner of the picture. I need to set the size of that cell to the size of the picture to solve the issue.
A Picture is a Shape. A Shape returns its width as Points (Shape.Width).
A Range can be set to a cell like Worksheet.Range["A1"]. From a Range you can get the width in Characters (Range.ColumnWidth) or in Points (Range.Width). But you can only set the width of a Range in Characters (Range.ColumnWidth).
So we can retrieve the size of the Picture (Shape) in Points and need to convert them to Characters to set the cell to the correct width...
Some research showed that the Points size of a cell contains a constant for spacing (padding before and after the cell content) and probably the seperator lines between cells.
On my system:
A cell set to a width of 1 **Characters** = 9 **Points**
A cell set to a width of 2 **Characters** = 14.25 **Points**
A cell set to a width of 3 **Characters** = 19.5 **Points**
As I said, there is a constant within the Points. Thus going from 1 Characters, to 2 Characters, the difference is only the size of the letter.
SizeOfLetter = 14.25 Points - 9 Points = 5.25 Points
we can then subtract that SizeOfLetter from the Points for 1 Characters and get the Points constant.
PointsConstant = 9 Points - 5.25 Points = 3.75 Points
Verify:
Points size for a cell containing 3 "0" letters = 3SizeOfLetter + PointsConstant = 35.25 Points + 3.75 Points = 19.5 Points
As the values depend on your system, YOU CAN'T USE THOSE VALUES!
Best way is to use code to calculate it for your system:
C# code:
Excel.Application excelApp = new Excel.Application();
Excel.Workbook workbook1 = excelApp.Workbooks.Add();
Excel.Worksheet sheet1 = (Excel.Worksheet)workbook1.ActiveSheet;
// Evaluate the Points data for the document
double previousColumnWidth = (double)sheet1.Range["A1"].ColumnWidth;
sheet1.Range["A1"].ColumnWidth = 1; // Make the cell fit 1 character
double points1 = (double)sheet1.Range["A1"].Width;
sheet1.Range["A1"].ColumnWidth = 2; // Make the cell fit 2 characters
double points2 = (double)sheet1.Range["A1"].Width;
double SizeOfLetter = points2 - points1;
double PointsConstant = points1 - pointsPerCharater;
// Reset the column width
sheet1.Range["A1"].ColumnWidth = previousColumnWidth;
// Create a function for the conversion
Func<double, double> PointsToCharacters = (double points) => (points - PointsConstant ) / SizeOfLetter ;

How do you limit the number of decimal places in the output of multiple numbers?

I've recently started learning Python and have made a simple program to calculate the area of a circle, however, I don't like the output of the answer and wanted to know how it would be possible to limit the number of decimal places in the output for multiple variables.
Example code:
import numpy as np
rad = input("Insert the radius of your circle: ")
radius = float(rad)
area = np.pi*(radius**2)
per=2*np.pi*radius
print("The area and perimeter of your chosen circle of radius "+str(radius)+" are: "+str(area)+" and "+str(per)+" respectively")
Output I get:
Insert the radius of your circle: 56.3
The area and perimeter of your chosen circle of radius 56.3 are: 9957.87481815703 and 353.7433327942107 respectively
Output I would like:
Insert the radius of your circle: 56.3
The area and perimeter of your chosen circle of radius 56.3 are: 9957.87 and 353.74 respectively
Many thanks!
Use f-strings
f-Strings: A New and Improved Way to Format Strings in Python
PEP 498: Literal String Interpolation
Formatted string literals
no need to use +
no need to convert the type
set the number of decimal places shown, with :.0xf, where x is the number of places to the right of the decimal, that will be shown.
Your last line should be:
print(f'The area and perimeter of your chosen circle of radius {radius:.03f} are: {area:.03f} and {per:.03f} respectively')
Output from you code with new f-string:
Insert the radius of your circle: 6
The area and perimeter of your chosen circle of radius 6.000 are: 113.097 and 37.699 respectively

Calculate the number of circles that fit on the circumference of another circle

I'm looking for an algorithm (or pseudo code) that can calculate the maximum number of (smaller) circles with diameter "s" that can be squeezed into the circumference of another (larger) circle with radius "r" ...
Image: http://teasy.space/images/terracolony-squeezingcircles2.jpg
You can alternate between radius/diameter etc if you wish -- as these are the only 2 parameters (other than the center (large circle) coordinate) that i have, i.e. that are known ...
The outer circles may not overlap but can fit "snug" together ...
After various upgrades to my routine through the years, I'm currently using an algorithm that is not perfect (and it needs to be accurate or the galaxy breaks down lol)
which does a broad interpolation between small outside circle diameter and large inside circle circumference, to somewhat accurately plot the circle count in a polygon style fitting pattern, which causes problems (i.e. overlaps) when using larger outside circles ...
; try to fit a random number of circles
num_Circles = Rand( min,max )
; check if the number of circles exceed the maximum that can fit
If num_Circles * SmallCircle_Diameter > LargeCircle_Circumference
; adjust the amount accordingly
num_Circles = LargeCircle_Circumference / SmallCircle_Diameter
End If
Another assumption is that the size of the smaller outer circles never exceeds that of the larger inner circle ...
something less to worry about ;)
I'm using this algorithm for one of my projects called Terra Colony, based on Gravity Well, a 2D space/gravity realtime colonization simulation game with moons, planets, stars, black/white holes, etc
Image: http://teasy.space/images/terracolony-squeezingcircles1.jpg
This is an issue that has plagued this project for over a decade!
Hopefully you can point me in the right direction :D
I have previously done many experiments and wrote different programs to find a solution, and have traveled the internet looking for formulas and solutions which in the end are very close, but not close enough! :P
Thank you! <3
Teasy
P.S. I tried to add the tag "circumference" but it apparently requires "1500 reputation" (points i guess, maybe to prevent spam)
There is formula that establishes relation between radius of big circle R, radius of small circle r and number of (touching) small circles N
R = r / Sin(Pi/N)
So maximum number of small circles might be found as
Sin(Pi/N) = r / R
Pi / N = arcsin(r / R)
and finally
N = Pi / arcsin(r / R)
Example:
R=5
r=2.5
so
N = Pi / arcsin(1/2) =
Pi / (Pi/6) =
6
Given the diam. of the small circle 'd' and the number of them 'c'
then the dia. of the large circle 'D' is
D=d/sin(180/c)

Translating Pseudocode steps into Python algorithm

I'm entirely new to programming and I'm supposed to turn pseudocode into a Python algorithm for a class assignment. I've tested mine algorithm (if you can even call it that) a few too many times and keep coming up with error messages. Any suggestions or resources that might be able to help would be greatly appreciated!
Pseudocode Order:
Declare Real radius
Declare Real area
Display “ Enter value for radius : “
Input radius
Set area = 3.14 * radius * radius
Display Area
Attempted Code:
radius = 1.0
Area = 1.0
print(" Enter value for radius : ")
radius = input(" Enter value for radius : ")
Area = 3.14 * radius * radius
print(Area)
and the error:
TypeError: can't multiply sequence by non-int of type 'float'
input() returns a string, thus your TypeError. You tried to multiply a string by a float.
Updated Code here:
radius = 1.0
print("Enter value for radius : ")
radius = input()
print(type(radius))
Area = 3.14 * (float(radius) * float(radius))
print(Area)
Output:
Enter value for radius :
5
<class 'str'>
78.5
The best way to do this is:
import math
radius = input("Enter a radius: ")
area = math.pi * radius ** 2
print("The area is: " + str(area) + "cm squared.")
A few things happen here:
On the first line we import the math module, which contains a bunch of values (like π) and lots of methods (like tan). For more on modules, take a look here.
On the second line, we ask for the radius. Note that unlike lower level programming languages, we don't have to initialise it. Python figures out that it is an float (a decimal) by itself. EDIT: If you are using python 2, you do have to cast, just as Damien pointed out, by using radius = float(input("Enter an area: ))
On line three we set the area equal to πr^2. We call the math.pi value, which is very precise, then we multiply that by r ^ 2 (in python if we want to a to the power of b we write a ** b)
On line 4 we print the area as a String. Note that we have to cast the float area to be a string using the str() function. This is basically Java's easy way to print anything that isn't a string as a string (a collection of characters).
Hope that helps!
Well, I will add some explain to this:
radius = 1.0 #this is not mandatory, you can create the variable and assign the value in the same moment
area = 1.0
radius = float(input(" Enter value for radius : ")) #here is so important to convert the input into a float, that's the other error you had
area = 3.14 * radius * radius t isn't working
print(area)

How to make an input only take numbers

I havn't been able to find a solution to this problem on the internet (maybe im not looking hard enough) but i can't figure out how to make an input only take numbers. Im trying to get the input to go through some equations and the program brakes everytime i put a letter in the input. I was wondering if there was a way to detect if the input was a letter or number. I'll show my program.
Radius=input("What is the radius of the circle/sphere?")
Areacircle=(int(Radius)**2)*3.14159265359
Perimetercircle=2*3.14159265359*int(Radius)
Permsphere=4*3.14159265359*(int(Radius)**2)
Areasphere=(4/3)*3.14159265359*(int(Radius)**3)
print("The radius' length was:",Radius)
print("The surface area of each circle is:",Areacircle)
print("The perimeter of the circle is:",Perimetercircle)
print("The volume of the sphere would be:",Areasphere)
print("The perimeter of the Sphere would be:",Permsphere)
As suggested in the comments, you can handle a ValueError when the conversion to int fails (and save doing this same conversion throughout the rest of your code).
Radius = None
while not Radius:
unchecked_radius = input("What is the radius of the circle/sphere? ")
try:
Radius = int(unchecked_radius)
except ValueError:
print('"{}" is not an integer. Redo.'.format(unchecked_radius))
I recommend reading the Python Tutorial section on Handling Exceptions, which has a very similar example.

Resources