1. 程式人生 > >Python小練習(1)

Python小練習(1)

duyuheng python 比較價錢 找出一個月中的天數 計算三角的周長 點在矩形內嗎?

金融方面:比較價錢

假設你購買大米時發現它有兩種包裝。你會別寫一個程序比較這兩種包裝的價錢。程序提示用戶輸入每種包裝的重量和價錢,然後顯示價錢更好的那種包裝。下面是個示例運行

技術分享

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2017\7\28 0028 18:52


# @Author : d y h
# @File : xiaolianxi.py
#輸入對比的重量與價格
weight1,price1= eval(input("Enter weight and price for package 1 :"))
weight2,price2= eval(input("Enter weight and price for package 2 :"))
#每斤價格比較
permj1 = price1 / weight1
permj2 = price2 / weight2
#選擇價低的
if permj1 > permj2:
print("package 2 has the better price "
)
else:
print("package 1 has the better price ")


找出一個月中的天數

編寫程序提示用戶輸入月和年,然後顯示這個月的天數。例如:用戶輸入2而年份為2000,這個程序應該顯示2000年二月份有29天.如果用戶輸入月份3而年份為2005,這個程序應該顯示2555年三月份有31天。

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2017\7\28 0028 19:06
# @Author : d y h
# @File : xiaolianxi.py
#輸入月份與年份
month,year = eval(input("Enter month an year (5,2004):"

))
#閏年
leapyear = year % 4
if month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or \
month == 10 or month == 12:
month1 = 31
elif month ==4 or month == 6 or month == 8 or month ==9 or month ==11 :
month1 =30
elif leapyear == 0 and month == 2:
month1 = 29
else:
month = 28
print(year,"",month,"","",month1,"")


計算三角的周長

編寫程序讀取三角形的三個邊,如果輸入是合法的則計算它的周長。否則顯示這個輸入是非法的。如果兩邊之和大於第三邊則輸入都是合法的。下面是一個示例運行。

技術分享

技術分享

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2017\7\28 0028 19:55
# @Author : d y h
# @File : xiaolianxi.py
#輸入三角形的三個邊
lenght1,lenght2,lenght3, =eval(input("Enter three adges:"))
#算周長
perimeter = lenght1 + lenght2 + lenght3
#判斷合不合法
if lenght1 + lenght2 > lenght3 and lenght1 + lenght3 > lenght2 and \
lenght2 + lenght3 > lenght1:
print("The perimeter is",perimeter)
else:
print("The perimeter invalid",)


Turtle:點在矩形內嗎?

行編寫一個程序提示用戶輸入點(x,y)。然後檢測點是否在以(0.0)為中心、寬為100、高為50的矩形內。在屏幕上顯示則個點、矩形以及表明這個點是否在矩形內的消息如,圖所示



技術分享

程序顯示矩形,點以及表明這個點是否在矩形內的消息

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2017\7\28 0028 21:39
# @Author : d y h
# @File : zuoye.4.36.py
#輸入一個點的坐標
x,y = eval(input("Enter a coordubate :"))
import turtle
#畫正方形
turtle.penup()
turtle.goto(-50,25)
turtle.pendown()
turtle.goto(50,25)
turtle.goto(50,-25)
turtle.goto(-50,-25)
turtle.goto(-50,25)
turtle.hideturtle()

#設置用戶輸入的point
turtle.penup()
turtle.goto(x,y)
#設置顏色
turtle.color("blue")
#筆尖大小
turtle.pensize(10)
turtle.pendown()
turtle.goto(x,y)
turtle.penup()
turtle.goto(-100,-100)

#x1=用戶輸入的坐標x絕對值 y1=用戶輸入的坐標y的絕對值
x1 = abs(x)
y1 = abs(y)

#如果x的絕對值小於50並且y的絕對值小於25,則該點在圖形內。否則不在圖形內
if x1 <= 50 and y1 <= 25:
turtle.write("This point is in the graph",font=("Arial",20,"normal"))
else:
turtle.write("This point is not in the graph",font=("Arial",20,"normal"))
turtle.done()


本文出自 “duyuheng” 博客,請務必保留此出處http://duyuheng.blog.51cto.com/12879147/1951851

Python小練習(1)