我必须输入几个城市及其人口,并用城市名称打印最大和最小人口。
我已经找到了如何获取最大值并与国家一起打印,但是,我不知道如何获取最小值。
n =int(input("Enter the number of municipalities "))
for i in range(n):
city = input("Enter the municipality: ")
population = float(input("Enter the population: "))
#processing information to calculate sum and max, min and range
sum += population
if max < population:
max = population
maxcity = city
print("The municipality with the highest population of", max, "million was " + maxcity)
对于最小值,我需要与最大值相同的结果。我可以在if循环中添加些什么来实现这一目标?我不允许使用内置的max(),min()函数!
答案 0 :(得分:1)
使用此:
max_value = 0
max_city = ''
min_value = 10**20
min_city = ''
for i in range(n):
city = input("Enter the municipality: ")
population = float(input("Enter the population: "))
if max_value < population:
max_value = population
max_city = city
if min_value > population:
min_value = population
min_city = city
print("The municipality with the highest population of", max_value, "million was " + max_city)
print("The municipality with the lowest population of", min_value, "million was " + min_city)
输出:
Enter the municipality: f
Enter the population: 10
Enter the municipality: g
Enter the population: 15
Enter the municipality: h
Enter the population: 80
The municipality with the highest population of 80.0 million was h
The municipality with the lowest population of 10.0 million was f
答案 1 :(得分:0)
import sys
INT_max_population = sys.maxsize
INT_MIN = -sys.maxsize-1
max_city = ''
min_city =''
max_population = INT_MIN
min_population = INT_max_population
n =int(input("Enter the number of municipalities "))
for i in range(n):
city = input("Enter the municipality: ")
population = float(input("Enter the population: "))
if max_population < population:
max_population = population
max_city = city
if min_population>population:
min_population = population
min_city = city
print("The municipality with the highest population of {} million was {} ".format(max_population, max_city))
print("The municipality with the lowest population of {} million was {} ".format(min_population, min_city))
输出
Enter the number of municipalities 3
Enter the municipality: a
Enter the population: 1
Enter the municipality: b
Enter the population: 2
Enter the municipality: c
Enter the population: 3
The municipality with the highest population of 3.0 million was c
The municipality with the lowest population of 1.0 million was a