2018/5/18 15:03:57当前位置推荐好文程序员浏览文章

运行.py文件

运行环境:Mac
软件:IDLE

方法/步骤

直接用IDLE

能直接在IDLE shell中编写python代码,但是不建议

  • 用 IDLE shell,利使用菜单栏open -> 打开.py 文件
  • 打开.py文件,选中.py文件,直接点击F5 || 运使用菜单栏 Run -> Run Module

用Sublime Text

  • 用 IDLE shell,利使用菜单栏open -> 打开.py 文件
  • 打开.py文件,选中.py文件,直接点击F5 || 运使用菜单栏 Run -> Run Module

你能直接在Sublime Text 编写代码,直接选中.py文件,直接点击F5,能不使用关心打开的.py文件的内容

终端执行python脚本 (for Mac)

  • cd 到文件夹目录
  • 在文件首行增加#!/usr/bin/env python
  • 增加权限 chmod 777 filename.py
  • 执行脚本./filename.py

注意: input() 在终端输入字符串时需要使用adfjakd或者"adfad"格式

# -- coding: UTF-8 --# Filename : test.py# author by : sjw#### output Hello World!print(Hello World)

number sum

num1 = input(input first number:)num2 = input(input second number:)sum = float(num1) + float(num2)print(num {0} add {1} = sum {2}.format(num1, num2, sum))print(sum of two numbers is %.1f %(float(input( first number:))+float(input(second :))))

get num sqrt

num = float(input(num sqrt number:))num_sqrt = num  0.5print(%0.3f sqrt is %0.3f%(num, num_sqrt))import cmathnum = int(input(input number:))num_sqrt = cmath.sqrt(num)print({0} sqrt num:{1:0.3f}+{2:0.3f}j.format(num, num_sqrt.real, num_sqrt.imag))

ax2 + bx + c = 0

import cmatha = float(input(a:))b = float(input(b:))c = float(input(c:))d = (b2)-(4ac)sol1 = (-b-cmath.sqrt(d))/(2a)sol2 = (-b+cmath.sqrt(d))/(2a)print(sol:{0} {1}.format(sol1,sol2))

triangle area

a = float(input(a:))b = float(input(b:))c = float(input(c:))s = (a+b+c)/2area = (s(s-a)(s-b)(s-c))  0.5print(triangle area:%.2f %area)

random

import randomprint(random.randint(0,9))

temperature

celsius = float(input(celsius:))fahrenheit = (celsius  1.8) + 32print(celsius:%0.1f to fahreneit:%0.1f%(celsius, fahrenheit))

change a b

x = input(x:)y = input(y:)temp = xx  = yy = tempprint(x:{0} y:{1}.format(x, y))x, y = y, xprint(x:{0} y:{1}.format(x, y))

if elif else

num = float(input(number:))if num > 0:    print("num is 整数")elif num == 0:    print(num is 0)else :    print(num is 负数) num = float(input(输入数字:))if num >= 0:    if num > 0:        print(num is 正数)    else:        print(num is 0)else:    print(num is 负数)

判断字符字符串还是数字

def is_number(s):    try:        float(s)        return True    except ValueError:        pass    try:        import unicodedata        unicodedata.numeric(s)        return True    except (TypeError, ValueError):        pass    return Falseprint(is_number(sdjf))print(is_number(-32.9))

判断奇数偶数

num = input(输入数字:)if (num%2) == 0:            print({0} 是偶数.format(num))else:     print({0} 是奇数.format(num))

判断闰年

year = int(input(输入一个年份:))if (year%4) == 0:    if (year%100) == 0:        if (year%400) == 0:            print({0}是闰年.format(year))        else:            print({0}不是闰年.format(year))    else:        print("{0}是闰年".format(year))else:     print("{0} 不是闰年".format(year))

获取最大值函数

# 最简单的print(max(1, 2))print(max(a, b)) # 也能对列表和元组用print(max([1,2]))print(max((1,2))) # 更多实例print("80, 100, 1000 最大值为: ", max(80, 100, 1000))print("-20, 100, 400最大值为: ", max(-20, 100, 400))print("-80, -20, -10最大值为: ", max(-80, -20, -10))print("0, 100, -400最大值为:", max(0, 100, -400))

质数判断

# 使用户输入数字num = int(input("请输入一个数字: ")) # 质数大于 1if num > 1:   # 查看因子   for i in range(2,num):       if (num % i) == 0:           print(num,"不是质数")           print(i,"乘于",num//i,"是",num)           break   else:       print(num,"是质数")       # 假如输入的数字小于或者等于 1,不是质数else:   print(num,"不是质数")

输出指定范围内的素数

#!/usr/bin/python3 # 输出指定范围内的素数 # take input from the userlower = int(input("输入区间最小值: "))upper = int(input("输入区间最大值: ")) for num in range(lower,upper + 1):    # 素数大于 1    if num > 1:        for i in range(2,num):            if (num % i) == 0:                break        else:            print(num)

阶乘实例

num = int(input(输入一个数字))factorial = 1if num < 0:    print(抱歉,负数没有阶乘)elif num == 0:    print(0 的阶乘为1)else:    for i in range(1, num + 1):        factorial = factorial  i    print("%d 的阶乘为 %d"%(num,factorial))

九九乘法表

for i in range(1,10):    for j in range(1,i):        print({}x{}={}\t.format(i, j, ij))    print()

斐波那契数列

nterms = int(input(你需要几项))n1 = 0n2 = 1= 2if nterms <= 0:    print(输入一个整数)elif nterms == 1:    print(斐波那契数列:)    print(n1)else:    print("斐波那契数列:")    print(n1, ,, n2, end=",")    while < nterms:        nth = n1 + n2        print(nth, end=",")        n1 = n2        n2 = nth        += 1

阿姆斯特朗数

# 获取使用户输入的数字num = int(input("请输入一个数字: ")) # 初始化变量 sumsum = 0# 指数n = len(str(num)) # 检测temp = numwhile temp > 0:   digit = temp % 10   sum += digit  n   temp //= 10 # 输出结果if num == sum:   print(num,"是阿姆斯特朗数")else:   print(num,"不是阿姆斯特朗数")

获取指定期间内的阿姆斯特朗数

# Filename :test.py# author by : www.runoob.com # 获取使用户输入数字lower = int(input("最小值: "))upper = int(input("最大值: ")) for num in range(lower,upper + 1):   # 初始化 sum   sum = 0   # 指数   n = len(str(num))    # 检测   temp = num   while temp > 0:       digit = temp % 10       sum += digit  n       temp //= 10    if num == sum:       print(num)

十进制转二进制、八进制、十六进制

dec = int(input("输入数字:"))print(十进制为:,dec)print("二进制为:",bin(dec))print("八进制为:",oct(dec))print("十六进制为:",hex(dec))

ASCII码与字符相互转换

c = input(请输入一个字符:)print(c + 的ASCII码为, ord(c))a = int(input(请输入一个ASCII码:))print(a ,对应的字符为, a))

最大公约数算法

def hcf(x, y):   """该函数返回两个数的最大公约数"""    # 获取最小值   if x > y:       smaller = y   else:       smaller = x    for i in range(1,smaller + 1):       if((x % i == 0) (y % i == 0)):           hcf = i    return hcf

使用户输入两个数字

num1 = int(input("输入第一个数字: "))num2 = int(input("输入第二个数字: ")) print( num1,"和", num2,"的最大公约数为", hcf(num1, num2))

最小公倍数算法

# 定义函数def lcm(x, y):    #  获取最大的数   if x > y:       greater = x   else:       greater = y    while(True):       if((greater % x == 0) (greater % y == 0)):           lcm = greater           break       greater += 1    return lcm # 获取使用户输入num1 = int(input("输入第一个数字: "))num2 = int(input("输入第二个数字: ")) print( num1,"和", num2,"的最小公倍数为", lcm(num1, num2))

简单计算器实现

# 定义函数def add(x, y):   """相加"""    return x + y def subtract(x, y):   """相减"""    return x - y def multiply(x, y):   """相乘"""    return x  y def divide(x, y):   """相除"""    return x / y # 使用户输入print("选择运算:")print("1、相加")print("2、相减")print("3、相乘")print("4、相除") choice = input("输入你的选择(1/2/3/4):") num1 = int(input("输入第一个数字: "))num2 = int(input("输入第二个数字: ")) if choice == 1:   print(num1,"+",num2,"=", add(num1,num2)) elif choice == 2:   print(num1,"-",num2,"=", subtract(num1,num2)) elif choice == 3:   print(num1,"",num2,"=", multiply(num1,num2)) elif choice == 4:   print(num1,"/",num2,"=", divide(num1,num2))else:   print("非法输入")

Python 生成日历

import calendaryy = int(input("输入年份:"))mm = int(input(输入月份:))print(calendar.month(yy,mm))

用递归斐波那契数列

def recur_fibo(n):   """递归函数   输出斐波那契数列"""   if n <= 1:       return n   else:       return(recur_fibo(n-1) + recur_fibo(n-2)) # 获取使用户输入nterms = int(input("您要输出几项? ")) # 检查输入的数字能否正确if nterms <= 0:   print("输入正数")else:   print("斐波那契数列:")   for i in range(nterms):       print(recur_fibo(i))

文件 IO

##encoding=utf8# 写文件with open("test.txt", "wt",encoding=utf8) as out_file:    out_file.write("kajdfkjadkfjkladjfka")    s = "该文本会写入到文件中\n看到我了吧!"    out_file.write(s)# Read a filewith open("test.txt", "rt",encoding=utf8) as in_file:    text = in_file.read()print(text)

字符串判断

str = "测试"print(str.isalnum()) # 判断所有字符都是数字或者者字母print(str.isalpha()) # 判断所有字符都是字母print(str.isdigit()) # 判断所有字符都是数字print(str.islower()) # 判断所有字符都是小写print(str.isupper()) # 判断所有字符都是大写print(str.istitle()) # 判断所有单词都是首字母大写,像标题print(str.isspace()) # 判断所有字符都是空白字符、\t、\n、\r

字符串大小写转换

str = "qwertyuiop"print(str.upper())          # 把所有字符中的小写字母转换成大写字母print(str.lower())          # 把所有字符中的大写字母转换成小写字母print(str.capitalize())     # 把第一个字母转化为大写字母,其他小写print(str.title())          # 把每个单词的第一个字母转化为大写,其他小写 

计算每个月天数

import calendarmonthRange = calendar.monthrange(2016,9)print(monthRange)

获取昨天日期

# 引入 datetime 板块import datetimedef getYesterday():     today=datetime.date.today()     oneday=datetime.timedelta(days=1)     yesterday=today-oneday      return yesterday # 输出print(getYesterday())
网友评论