python第二大奇数_最大奇数Python代码简化

该博客探讨了一种不使用数组、异常处理、导入、列表或for循环的Python程序,旨在从用户输入中找到最大的奇数。程序通过字符串处理和while循环实现,但作者认为代码过于冗长,寻求更简洁、更‘Pythonic’的解决方案。博客内容包括现有的代码实现,并表达了优化代码的愿望。
摘要由CSDN通过智能技术生成

Write a program that asks the user to input 10 integers, and then prints the largest odd number that was entered. If no odd number was entered, it should print a message to that effect.

我需要在不使用数组、异常、导入、列表或for循环的情况下完成它。只能使用条件语句和while循环。我写了下面的代码,但我觉得我的算法太长了。这个程序能用更简洁的方式写吗?我问这个问题的目的是想看看是否有更“Pythonic”的方法来编写同一个程序,我在下面提供了这个程序的代码。在s = (input('Enter 10 numbers: '))

t = '' # initialize empty "number" string

x = len(s)-1

y = 0 # initialize checked integer

z = 0 # initialize preceding integer

i = 0 # initialize counter

while i <= x:

print('i=', i)

while i <= x and s[i] != ' ':

t = t + s[i] # concatenate "string number"

i = i+1

if len(t) > 0: # to not run out of string index

y = int(t)

if y%2 != 0: # compare odd numbers

if y > z:

z = y

if y < z and z%2 == 0: # if y is a negative odd integer

z=y

if i <= x and s[i] == ' ':

i=i+1

t = '' # reset the "number" string

if z == 0:

print('No odd numbers entered')

else:

print('The largest odd number entered is', z)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值